PostgreSQL Source Code git master
Loading...
Searching...
No Matches
tablecmds.h File Reference
#include "access/htup.h"
#include "catalog/dependency.h"
#include "catalog/objectaddress.h"
#include "nodes/parsenodes.h"
#include "storage/lockdefs.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.

Typedefs

typedef struct AlterTableUtilityContext AlterTableUtilityContext
 

Functions

ObjectAddress DefineRelation (CreateStmt *stmt, char relkind, Oid ownerId, ObjectAddress *typaddress, const char *queryString)
 
TupleDesc BuildDescForRelation (const List *columns)
 
void RemoveRelations (DropStmt *drop)
 
Oid AlterTableLookupRelation (AlterTableStmt *stmt, LOCKMODE lockmode)
 
void AlterTable (AlterTableStmt *stmt, LOCKMODE lockmode, AlterTableUtilityContext *context)
 
LOCKMODE AlterTableGetLockLevel (List *cmds)
 
void ATExecChangeOwner (Oid relationOid, Oid newOwnerId, bool recursing, LOCKMODE lockmode)
 
void AlterTableInternal (Oid relid, List *cmds, bool recurse)
 
Oid AlterTableMoveAll (AlterTableMoveAllStmt *stmt)
 
ObjectAddress AlterTableNamespace (AlterObjectSchemaStmt *stmt, Oid *oldschema)
 
void AlterTableNamespaceInternal (Relation rel, Oid oldNspOid, Oid nspOid, ObjectAddresses *objsMoved)
 
void AlterRelationNamespaceInternal (Relation classRel, Oid relOid, Oid oldNspOid, Oid newNspOid, bool hasDependEntry, ObjectAddresses *objsMoved)
 
void CheckTableNotInUse (Relation rel, const char *stmt)
 
void ExecuteTruncate (TruncateStmt *stmt)
 
void ExecuteTruncateGuts (List *explicit_rels, List *relids, List *relids_logged, DropBehavior behavior, bool restart_seqs, bool run_as_table_owner)
 
void SetRelationHasSubclass (Oid relationId, bool relhassubclass)
 
bool CheckRelationTableSpaceMove (Relation rel, Oid newTableSpaceId)
 
void SetRelationTableSpace (Relation rel, Oid newTableSpaceId, RelFileNumber newRelFilenumber)
 
ObjectAddress renameatt (RenameStmt *stmt)
 
ObjectAddress RenameConstraint (RenameStmt *stmt)
 
ObjectAddress RenameRelation (RenameStmt *stmt)
 
void RenameRelationInternal (Oid myrelid, const char *newrelname, bool is_internal, bool is_index)
 
void ResetRelRewrite (Oid myrelid)
 
void find_composite_type_dependencies (Oid typeOid, Relation origRelation, const char *origTypeName)
 
void check_of_type (HeapTuple typetuple)
 
void register_on_commit_action (Oid relid, OnCommitAction action)
 
void remove_on_commit_action (Oid relid)
 
void PreCommit_on_commit_actions (void)
 
void AtEOXact_on_commit_actions (bool isCommit)
 
void AtEOSubXact_on_commit_actions (bool isCommit, SubTransactionId mySubid, SubTransactionId parentSubid)
 
void RangeVarCallbackMaintainsTable (const RangeVar *relation, Oid relId, Oid oldRelId, void *arg)
 
void RangeVarCallbackOwnsRelation (const RangeVar *relation, Oid relId, Oid oldRelId, void *arg)
 
bool PartConstraintImpliedByRelConstraint (Relation scanrel, List *partConstraint)
 

Typedef Documentation

◆ AlterTableUtilityContext

Function Documentation

◆ AlterRelationNamespaceInternal()

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

Definition at line 19318 of file tablecmds.c.

19322{
19326 bool already_done = false;
19327
19328 /* no rel lock for relkind=c so use LOCKTAG_TUPLE */
19331 elog(ERROR, "cache lookup failed for relation %u", relOid);
19333
19334 Assert(classForm->relnamespace == oldNspOid);
19335
19336 thisobj.classId = RelationRelationId;
19337 thisobj.objectId = relOid;
19338 thisobj.objectSubId = 0;
19339
19340 /*
19341 * If the object has already been moved, don't move it again. If it's
19342 * already in the right place, don't move it, but still fire the object
19343 * access hook.
19344 */
19346 if (!already_done && oldNspOid != newNspOid)
19347 {
19348 ItemPointerData otid = classTup->t_self;
19349
19350 /* check for duplicate name (more friendly than unique-index failure) */
19351 if (get_relname_relid(NameStr(classForm->relname),
19353 ereport(ERROR,
19355 errmsg("relation \"%s\" already exists in schema \"%s\"",
19356 NameStr(classForm->relname),
19358
19359 /* classTup is a copy, so OK to scribble on */
19360 classForm->relnamespace = newNspOid;
19361
19364
19365
19366 /* Update dependency on schema if caller said so */
19367 if (hasDependEntry &&
19369 relOid,
19371 oldNspOid,
19372 newNspOid) != 1)
19373 elog(ERROR, "could not change schema dependency for relation \"%s\"",
19374 NameStr(classForm->relname));
19375 }
19376 else
19378 if (!already_done)
19379 {
19381
19383 }
19384
19386}
#define NameStr(name)
Definition c.h:835
#define Assert(condition)
Definition c.h:943
bool object_address_present(const ObjectAddress *object, const ObjectAddresses *addrs)
void add_exact_object_address(const ObjectAddress *object, ObjectAddresses *addrs)
int errcode(int sqlerrcode)
Definition elog.c:875
#define ERROR
Definition elog.h:40
#define elog(elevel,...)
Definition elog.h:228
#define ereport(elevel,...)
Definition elog.h:152
void heap_freetuple(HeapTuple htup)
Definition heaptuple.c:1372
#define HeapTupleIsValid(tuple)
Definition htup.h:78
static void * GETSTRUCT(const HeapTupleData *tuple)
void CatalogTupleUpdate(Relation heapRel, const ItemPointerData *otid, HeapTuple tup)
Definition indexing.c:313
void UnlockTuple(Relation relation, const ItemPointerData *tid, LOCKMODE lockmode)
Definition lmgr.c:601
#define InplaceUpdateTupleLock
Definition lockdefs.h:48
char * get_namespace_name(Oid nspid)
Definition lsyscache.c:3561
Oid get_relname_relid(const char *relname, Oid relnamespace)
Definition lsyscache.c:2078
static char * errmsg
#define InvokeObjectPostAlterHook(classId, objectId, subId)
FormData_pg_class * Form_pg_class
Definition pg_class.h:160
long changeDependencyFor(Oid classId, Oid objectId, Oid refClassId, Oid oldRefObjectId, Oid newRefObjectId)
Definition pg_depend.c:459
static Datum ObjectIdGetDatum(Oid X)
Definition postgres.h:252
#define InvalidOid
static int fb(int x)
HeapTuple SearchSysCacheLockedCopy1(SysCacheIdentifier cacheId, Datum key1)
Definition syscache.c:400

References add_exact_object_address(), Assert, CatalogTupleUpdate(), changeDependencyFor(), elog, ereport, errcode(), errmsg, ERROR, fb(), get_namespace_name(), get_relname_relid(), GETSTRUCT(), heap_freetuple(), HeapTupleIsValid, InplaceUpdateTupleLock, InvalidOid, InvokeObjectPostAlterHook, NameStr, object_address_present(), ObjectIdGetDatum(), SearchSysCacheLockedCopy1(), and UnlockTuple().

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

◆ AlterTable()

void AlterTable ( AlterTableStmt stmt,
LOCKMODE  lockmode,
AlterTableUtilityContext context 
)
extern

Definition at line 4591 of file tablecmds.c.

4593{
4594 Relation rel;
4595
4596 /* Caller is required to provide an adequate lock. */
4597 rel = relation_open(context->relid, NoLock);
4598
4600
4601 ATController(stmt, rel, stmt->cmds, stmt->relation->inh, lockmode, context);
4602}
#define stmt
#define NoLock
Definition lockdefs.h:34
Relation relation_open(Oid relationId, LOCKMODE lockmode)
Definition relation.c:48
static void CheckAlterTableIsSafe(Relation rel)
Definition tablecmds.c:4506
static void ATController(AlterTableStmt *parsetree, Relation rel, List *cmds, bool recurse, LOCKMODE lockmode, AlterTableUtilityContext *context)
Definition tablecmds.c:4932

References ATController(), CheckAlterTableIsSafe(), NoLock, relation_open(), AlterTableUtilityContext::relid, and stmt.

Referenced by ProcessUtilitySlow().

◆ AlterTableGetLockLevel()

LOCKMODE AlterTableGetLockLevel ( List cmds)
extern

Definition at line 4665 of file tablecmds.c.

4666{
4667 /*
4668 * This only works if we read catalog tables using MVCC snapshots.
4669 */
4670 ListCell *lcmd;
4672
4673 foreach(lcmd, cmds)
4674 {
4676 LOCKMODE cmd_lockmode = AccessExclusiveLock; /* default for compiler */
4677
4678 switch (cmd->subtype)
4679 {
4680 /*
4681 * These subcommands rewrite the heap, so require full locks.
4682 */
4683 case AT_AddColumn: /* may rewrite heap, in some cases and visible
4684 * to SELECT */
4685 case AT_SetAccessMethod: /* must rewrite heap */
4686 case AT_SetTableSpace: /* must rewrite heap */
4687 case AT_AlterColumnType: /* must rewrite heap */
4689 break;
4690
4691 /*
4692 * These subcommands may require addition of toast tables. If
4693 * we add a toast table to a table currently being scanned, we
4694 * might miss data added to the new toast table by concurrent
4695 * insert transactions.
4696 */
4697 case AT_SetStorage: /* may add toast tables, see
4698 * ATRewriteCatalogs() */
4700 break;
4701
4702 /*
4703 * Removing constraints can affect SELECTs that have been
4704 * optimized assuming the constraint holds true. See also
4705 * CloneFkReferenced.
4706 */
4707 case AT_DropConstraint: /* as DROP INDEX */
4708 case AT_DropNotNull: /* may change some SQL plans */
4710 break;
4711
4712 /*
4713 * Subcommands that may be visible to concurrent SELECTs
4714 */
4715 case AT_DropColumn: /* change visible to SELECT */
4716 case AT_AddColumnToView: /* CREATE VIEW */
4717 case AT_DropOids: /* used to equiv to DropColumn */
4718 case AT_EnableAlwaysRule: /* may change SELECT rules */
4719 case AT_EnableReplicaRule: /* may change SELECT rules */
4720 case AT_EnableRule: /* may change SELECT rules */
4721 case AT_DisableRule: /* may change SELECT rules */
4723 break;
4724
4725 /*
4726 * Changing owner may remove implicit SELECT privileges
4727 */
4728 case AT_ChangeOwner: /* change visible to SELECT */
4730 break;
4731
4732 /*
4733 * Changing foreign table options may affect optimization.
4734 */
4735 case AT_GenericOptions:
4738 break;
4739
4740 /*
4741 * These subcommands affect write operations only.
4742 */
4743 case AT_EnableTrig:
4746 case AT_EnableTrigAll:
4747 case AT_EnableTrigUser:
4748 case AT_DisableTrig:
4749 case AT_DisableTrigAll:
4750 case AT_DisableTrigUser:
4752 break;
4753
4754 /*
4755 * These subcommands affect write operations only. XXX
4756 * Theoretically, these could be ShareRowExclusiveLock.
4757 */
4758 case AT_ColumnDefault:
4760 case AT_AlterConstraint:
4761 case AT_AddIndex: /* from ADD CONSTRAINT */
4763 case AT_ReplicaIdentity:
4764 case AT_SetNotNull:
4769 case AT_AddIdentity:
4770 case AT_DropIdentity:
4771 case AT_SetIdentity:
4772 case AT_SetExpression:
4773 case AT_DropExpression:
4774 case AT_SetCompression:
4776 break;
4777
4778 case AT_AddConstraint:
4779 case AT_ReAddConstraint: /* becomes AT_AddConstraint */
4780 case AT_ReAddDomainConstraint: /* becomes AT_AddConstraint */
4781 if (IsA(cmd->def, Constraint))
4782 {
4783 Constraint *con = (Constraint *) cmd->def;
4784
4785 switch (con->contype)
4786 {
4787 case CONSTR_EXCLUSION:
4788 case CONSTR_PRIMARY:
4789 case CONSTR_UNIQUE:
4790
4791 /*
4792 * Cases essentially the same as CREATE INDEX. We
4793 * could reduce the lock strength to ShareLock if
4794 * we can work out how to allow concurrent catalog
4795 * updates. XXX Might be set down to
4796 * ShareRowExclusiveLock but requires further
4797 * analysis.
4798 */
4800 break;
4801 case CONSTR_FOREIGN:
4802
4803 /*
4804 * We add triggers to both tables when we add a
4805 * Foreign Key, so the lock level must be at least
4806 * as strong as CREATE TRIGGER.
4807 */
4809 break;
4810
4811 default:
4813 }
4814 }
4815 break;
4816
4817 /*
4818 * These subcommands affect inheritance behaviour. Queries
4819 * started before us will continue to see the old inheritance
4820 * behaviour, while queries started after we commit will see
4821 * new behaviour. No need to prevent reads or writes to the
4822 * subtable while we hook it up though. Changing the TupDesc
4823 * may be a problem, so keep highest lock.
4824 */
4825 case AT_AddInherit:
4826 case AT_DropInherit:
4828 break;
4829
4830 /*
4831 * These subcommands affect implicit row type conversion. They
4832 * have affects similar to CREATE/DROP CAST on queries. don't
4833 * provide for invalidating parse trees as a result of such
4834 * changes, so we keep these at AccessExclusiveLock.
4835 */
4836 case AT_AddOf:
4837 case AT_DropOf:
4839 break;
4840
4841 /*
4842 * Only used by CREATE OR REPLACE VIEW which must conflict
4843 * with an SELECTs currently using the view.
4844 */
4847 break;
4848
4849 /*
4850 * These subcommands affect general strategies for performance
4851 * and maintenance, though don't change the semantic results
4852 * from normal data reads and writes. Delaying an ALTER TABLE
4853 * behind currently active writes only delays the point where
4854 * the new strategy begins to take effect, so there is no
4855 * benefit in waiting. In this case the minimum restriction
4856 * applies: we don't currently allow concurrent catalog
4857 * updates.
4858 */
4859 case AT_SetStatistics: /* Uses MVCC in getTableAttrs() */
4860 case AT_ClusterOn: /* Uses MVCC in getIndexes() */
4861 case AT_DropCluster: /* Uses MVCC in getIndexes() */
4862 case AT_SetOptions: /* Uses MVCC in getTableAttrs() */
4863 case AT_ResetOptions: /* Uses MVCC in getTableAttrs() */
4865 break;
4866
4867 case AT_SetLogged:
4868 case AT_SetUnLogged:
4870 break;
4871
4872 case AT_ValidateConstraint: /* Uses MVCC in getConstraints() */
4874 break;
4875
4876 /*
4877 * Rel options are more complex than first appears. Options
4878 * are set here for tables, views and indexes; for historical
4879 * reasons these can all be used with ALTER TABLE, so we can't
4880 * decide between them using the basic grammar.
4881 */
4882 case AT_SetRelOptions: /* Uses MVCC in getIndexes() and
4883 * getTables() */
4884 case AT_ResetRelOptions: /* Uses MVCC in getIndexes() and
4885 * getTables() */
4887 break;
4888
4889 case AT_AttachPartition:
4891 break;
4892
4893 case AT_DetachPartition:
4894 if (((PartitionCmd *) cmd->def)->concurrent)
4896 else
4898 break;
4899
4902 break;
4903
4904 case AT_MergePartitions:
4905 case AT_SplitPartition:
4907 break;
4908
4909 default: /* oops */
4910 elog(ERROR, "unrecognized alter table type: %d",
4911 (int) cmd->subtype);
4912 break;
4913 }
4914
4915 /*
4916 * Take the greatest lockmode from any subcommand
4917 */
4918 if (cmd_lockmode > lockmode)
4919 lockmode = cmd_lockmode;
4920 }
4921
4922 return lockmode;
4923}
int LOCKMODE
Definition lockdefs.h:26
#define AccessExclusiveLock
Definition lockdefs.h:43
#define ShareRowExclusiveLock
Definition lockdefs.h:41
#define ShareUpdateExclusiveLock
Definition lockdefs.h:39
#define IsA(nodeptr, _type_)
Definition nodes.h:164
@ CONSTR_FOREIGN
@ CONSTR_UNIQUE
@ CONSTR_EXCLUSION
@ CONSTR_PRIMARY
@ AT_AddIndexConstraint
@ AT_MergePartitions
@ AT_DropOf
@ AT_SetOptions
@ AT_DropIdentity
@ AT_DisableTrigUser
@ AT_DropNotNull
@ AT_AddOf
@ AT_ResetOptions
@ AT_ReplicaIdentity
@ AT_ReplaceRelOptions
@ AT_EnableRowSecurity
@ AT_AddColumnToView
@ AT_ResetRelOptions
@ AT_EnableReplicaTrig
@ AT_DropOids
@ AT_SetIdentity
@ AT_SetUnLogged
@ AT_DisableTrig
@ AT_SetCompression
@ AT_DropExpression
@ AT_AddIndex
@ AT_EnableReplicaRule
@ AT_DropConstraint
@ AT_SetNotNull
@ AT_ClusterOn
@ AT_AddIdentity
@ AT_ForceRowSecurity
@ AT_EnableAlwaysRule
@ AT_SetAccessMethod
@ AT_AlterColumnType
@ AT_DetachPartitionFinalize
@ AT_AddInherit
@ AT_ReAddDomainConstraint
@ AT_EnableTrig
@ AT_DropColumn
@ AT_AlterColumnGenericOptions
@ AT_DisableTrigAll
@ AT_EnableRule
@ AT_NoForceRowSecurity
@ AT_DetachPartition
@ AT_SetStatistics
@ AT_AttachPartition
@ AT_AddConstraint
@ AT_DropInherit
@ AT_EnableAlwaysTrig
@ AT_SetLogged
@ AT_SetStorage
@ AT_DisableRule
@ AT_DisableRowSecurity
@ AT_SetRelOptions
@ AT_ChangeOwner
@ AT_EnableTrigUser
@ AT_SetExpression
@ AT_ReAddConstraint
@ AT_SetTableSpace
@ AT_GenericOptions
@ AT_ColumnDefault
@ AT_CookedColumnDefault
@ AT_AlterConstraint
@ AT_EnableTrigAll
@ AT_SplitPartition
@ AT_DropCluster
@ AT_ValidateConstraint
@ AT_AddColumn
#define lfirst(lc)
Definition pg_list.h:172
LOCKMODE AlterTableGetRelOptionsLockLevel(List *defList)
AlterTableType subtype
Definition pg_list.h:54

References AccessExclusiveLock, AlterTableGetRelOptionsLockLevel(), AT_AddColumn, AT_AddColumnToView, AT_AddConstraint, AT_AddIdentity, AT_AddIndex, AT_AddIndexConstraint, AT_AddInherit, AT_AddOf, AT_AlterColumnGenericOptions, AT_AlterColumnType, AT_AlterConstraint, AT_AttachPartition, AT_ChangeOwner, AT_ClusterOn, AT_ColumnDefault, AT_CookedColumnDefault, AT_DetachPartition, AT_DetachPartitionFinalize, AT_DisableRowSecurity, AT_DisableRule, AT_DisableTrig, AT_DisableTrigAll, AT_DisableTrigUser, AT_DropCluster, AT_DropColumn, AT_DropConstraint, AT_DropExpression, AT_DropIdentity, AT_DropInherit, AT_DropNotNull, AT_DropOf, AT_DropOids, AT_EnableAlwaysRule, AT_EnableAlwaysTrig, AT_EnableReplicaRule, AT_EnableReplicaTrig, AT_EnableRowSecurity, AT_EnableRule, AT_EnableTrig, AT_EnableTrigAll, AT_EnableTrigUser, AT_ForceRowSecurity, AT_GenericOptions, AT_MergePartitions, AT_NoForceRowSecurity, AT_ReAddConstraint, AT_ReAddDomainConstraint, AT_ReplaceRelOptions, AT_ReplicaIdentity, AT_ResetOptions, AT_ResetRelOptions, AT_SetAccessMethod, AT_SetCompression, AT_SetExpression, AT_SetIdentity, AT_SetLogged, AT_SetNotNull, AT_SetOptions, AT_SetRelOptions, AT_SetStatistics, AT_SetStorage, AT_SetTableSpace, AT_SetUnLogged, AT_SplitPartition, AT_ValidateConstraint, CONSTR_EXCLUSION, CONSTR_FOREIGN, CONSTR_PRIMARY, CONSTR_UNIQUE, Constraint::contype, AlterTableCmd::def, elog, ERROR, fb(), IsA, lfirst, ShareRowExclusiveLock, ShareUpdateExclusiveLock, and AlterTableCmd::subtype.

Referenced by AlterTableInternal(), and ProcessUtilitySlow().

◆ AlterTableInternal()

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

Definition at line 4620 of file tablecmds.c.

4621{
4622 Relation rel;
4623 LOCKMODE lockmode = AlterTableGetLockLevel(cmds);
4624
4625 rel = relation_open(relid, lockmode);
4626
4628
4629 ATController(NULL, rel, cmds, recurse, lockmode, NULL);
4630}
void EventTriggerAlterTableRelid(Oid objectId)
LOCKMODE AlterTableGetLockLevel(List *cmds)
Definition tablecmds.c:4665

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

Referenced by AlterTableMoveAll(), and DefineVirtualRelation().

◆ AlterTableLookupRelation()

Oid AlterTableLookupRelation ( AlterTableStmt stmt,
LOCKMODE  lockmode 
)
extern

Definition at line 4532 of file tablecmds.c.

4533{
4534 return RangeVarGetRelidExtended(stmt->relation, lockmode,
4535 stmt->missing_ok ? RVR_MISSING_OK : 0,
4537 stmt);
4538}
Oid RangeVarGetRelidExtended(const RangeVar *relation, LOCKMODE lockmode, uint32 flags, RangeVarGetRelidCallback callback, void *callback_arg)
Definition namespace.c:442
@ RVR_MISSING_OK
Definition namespace.h:90
static void RangeVarCallbackForAlterRelation(const RangeVar *rv, Oid relid, Oid oldrelid, void *arg)

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

Referenced by ProcessUtilitySlow().

◆ AlterTableMoveAll()

Oid AlterTableMoveAll ( AlterTableMoveAllStmt stmt)
extern

Definition at line 17258 of file tablecmds.c.

17259{
17260 List *relations = NIL;
17261 ListCell *l;
17262 ScanKeyData key[1];
17263 Relation rel;
17264 TableScanDesc scan;
17265 HeapTuple tuple;
17268 List *role_oids = roleSpecsToIds(stmt->roles);
17269
17270 /* Ensure we were not asked to move something we can't */
17271 if (stmt->objtype != OBJECT_TABLE && stmt->objtype != OBJECT_INDEX &&
17272 stmt->objtype != OBJECT_MATVIEW)
17273 ereport(ERROR,
17275 errmsg("only tables, indexes, and materialized views exist in tablespaces")));
17276
17277 /* Get the orig and new tablespace OIDs */
17278 orig_tablespaceoid = get_tablespace_oid(stmt->orig_tablespacename, false);
17279 new_tablespaceoid = get_tablespace_oid(stmt->new_tablespacename, false);
17280
17281 /* Can't move shared relations in to or out of pg_global */
17282 /* This is also checked by ATExecSetTableSpace, but nice to stop earlier */
17285 ereport(ERROR,
17287 errmsg("cannot move relations in to or out of pg_global tablespace")));
17288
17289 /*
17290 * Must have CREATE rights on the new tablespace, unless it is the
17291 * database default tablespace (which all users implicitly have CREATE
17292 * rights on).
17293 */
17295 {
17297
17299 ACL_CREATE);
17300 if (aclresult != ACLCHECK_OK)
17303 }
17304
17305 /*
17306 * Now that the checks are done, check if we should set either to
17307 * InvalidOid because it is our database's default tablespace.
17308 */
17311
17314
17315 /* no-op */
17317 return new_tablespaceoid;
17318
17319 /*
17320 * Walk the list of objects in the tablespace and move them. This will
17321 * only find objects in our database, of course.
17322 */
17323 ScanKeyInit(&key[0],
17327
17329 scan = table_beginscan_catalog(rel, 1, key);
17330 while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
17331 {
17333 Oid relOid = relForm->oid;
17334
17335 /*
17336 * Do not move objects in pg_catalog as part of this, if an admin
17337 * really wishes to do so, they can issue the individual ALTER
17338 * commands directly.
17339 *
17340 * Also, explicitly avoid any shared tables, temp tables, or TOAST
17341 * (TOAST will be moved with the main table).
17342 */
17343 if (IsCatalogNamespace(relForm->relnamespace) ||
17344 relForm->relisshared ||
17345 isAnyTempNamespace(relForm->relnamespace) ||
17346 IsToastNamespace(relForm->relnamespace))
17347 continue;
17348
17349 /* Only move the object type requested */
17350 if ((stmt->objtype == OBJECT_TABLE &&
17351 relForm->relkind != RELKIND_RELATION &&
17352 relForm->relkind != RELKIND_PARTITIONED_TABLE) ||
17353 (stmt->objtype == OBJECT_INDEX &&
17354 relForm->relkind != RELKIND_INDEX &&
17355 relForm->relkind != RELKIND_PARTITIONED_INDEX) ||
17356 (stmt->objtype == OBJECT_MATVIEW &&
17357 relForm->relkind != RELKIND_MATVIEW))
17358 continue;
17359
17360 /* Check if we are only moving objects owned by certain roles */
17361 if (role_oids != NIL && !list_member_oid(role_oids, relForm->relowner))
17362 continue;
17363
17364 /*
17365 * Handle permissions-checking here since we are locking the tables
17366 * and also to avoid doing a bunch of work only to fail part-way. Note
17367 * that permissions will also be checked by AlterTableInternal().
17368 *
17369 * Caller must be considered an owner on the table to move it.
17370 */
17373 NameStr(relForm->relname));
17374
17375 if (stmt->nowait &&
17377 ereport(ERROR,
17379 errmsg("aborting because lock on relation \"%s.%s\" is not available",
17380 get_namespace_name(relForm->relnamespace),
17381 NameStr(relForm->relname))));
17382 else
17384
17385 /* Add to our list of objects to move */
17386 relations = lappend_oid(relations, relOid);
17387 }
17388
17389 table_endscan(scan);
17391
17392 if (relations == NIL)
17395 errmsg("no matching relations in tablespace \"%s\" found",
17396 orig_tablespaceoid == InvalidOid ? "(database default)" :
17398
17399 /* Everything is locked, loop through and move all of the relations. */
17400 foreach(l, relations)
17401 {
17402 List *cmds = NIL;
17404
17406 cmd->name = stmt->new_tablespacename;
17407
17408 cmds = lappend(cmds, cmd);
17409
17411 /* OID is set by AlterTableInternal */
17412 AlterTableInternal(lfirst_oid(l), cmds, false);
17414 }
17415
17416 return new_tablespaceoid;
17417}
AclResult
Definition acl.h:183
@ ACLCHECK_OK
Definition acl.h:184
@ ACLCHECK_NOT_OWNER
Definition acl.h:186
void aclcheck_error(AclResult aclerr, ObjectType objtype, const char *objectname)
Definition aclchk.c:2672
AclResult object_aclcheck(Oid classid, Oid objectid, Oid roleid, AclMode mode)
Definition aclchk.c:3879
bool object_ownercheck(Oid classid, Oid objectid, Oid roleid)
Definition aclchk.c:4133
char * get_tablespace_name(Oid spc_oid)
Oid get_tablespace_oid(const char *tablespacename, bool missing_ok)
#define OidIsValid(objectId)
Definition c.h:858
bool IsToastNamespace(Oid namespaceId)
Definition catalog.c:261
bool IsCatalogNamespace(Oid namespaceId)
Definition catalog.c:243
#define NOTICE
Definition elog.h:36
void EventTriggerAlterTableStart(const Node *parsetree)
void EventTriggerAlterTableEnd(void)
Oid MyDatabaseTableSpace
Definition globals.c:98
HeapTuple heap_getnext(TableScanDesc sscan, ScanDirection direction)
Definition heapam.c:1435
List * lappend(List *list, void *datum)
Definition list.c:339
List * lappend_oid(List *list, Oid datum)
Definition list.c:375
bool list_member_oid(const List *list, Oid datum)
Definition list.c:722
bool ConditionalLockRelationOid(Oid relid, LOCKMODE lockmode)
Definition lmgr.c:151
void LockRelationOid(Oid relid, LOCKMODE lockmode)
Definition lmgr.c:107
#define AccessShareLock
Definition lockdefs.h:36
char get_rel_relkind(Oid relid)
Definition lsyscache.c:2196
Oid GetUserId(void)
Definition miscinit.c:470
bool isAnyTempNamespace(Oid namespaceId)
Definition namespace.c:3759
#define makeNode(_type_)
Definition nodes.h:161
ObjectType get_relkind_objtype(char relkind)
@ OBJECT_MATVIEW
@ OBJECT_TABLESPACE
@ OBJECT_INDEX
@ OBJECT_TABLE
#define ACL_CREATE
Definition parsenodes.h:85
#define NIL
Definition pg_list.h:68
#define lfirst_oid(lc)
Definition pg_list.h:174
unsigned int Oid
void ScanKeyInit(ScanKey entry, AttrNumber attributeNumber, StrategyNumber strategy, RegProcedure procedure, Datum argument)
Definition scankey.c:76
@ ForwardScanDirection
Definition sdir.h:28
#define BTEqualStrategyNumber
Definition stratnum.h:31
Definition nodes.h:135
void table_close(Relation relation, LOCKMODE lockmode)
Definition table.c:126
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition table.c:40
TableScanDesc table_beginscan_catalog(Relation relation, int nkeys, ScanKeyData *key)
Definition tableam.c:113
static void table_endscan(TableScanDesc scan)
Definition tableam.h:1061
void AlterTableInternal(Oid relid, List *cmds, bool recurse)
Definition tablecmds.c:4620
List * roleSpecsToIds(List *memberNames)
Definition user.c:1665

References AccessExclusiveLock, AccessShareLock, ACL_CREATE, aclcheck_error(), ACLCHECK_NOT_OWNER, ACLCHECK_OK, AlterTableInternal(), AT_SetTableSpace, BTEqualStrategyNumber, ConditionalLockRelationOid(), ereport, errcode(), errmsg, ERROR, EventTriggerAlterTableEnd(), EventTriggerAlterTableStart(), fb(), ForwardScanDirection, get_namespace_name(), get_rel_relkind(), get_relkind_objtype(), get_tablespace_name(), get_tablespace_oid(), GETSTRUCT(), GetUserId(), heap_getnext(), InvalidOid, isAnyTempNamespace(), IsCatalogNamespace(), IsToastNamespace(), lappend(), lappend_oid(), lfirst_oid, list_member_oid(), LockRelationOid(), makeNode, MyDatabaseTableSpace, AlterTableCmd::name, NameStr, NIL, NOTICE, object_aclcheck(), OBJECT_INDEX, OBJECT_MATVIEW, object_ownercheck(), OBJECT_TABLE, OBJECT_TABLESPACE, ObjectIdGetDatum(), OidIsValid, roleSpecsToIds(), ScanKeyInit(), stmt, AlterTableCmd::subtype, table_beginscan_catalog(), table_close(), table_endscan(), and table_open().

Referenced by ProcessUtilitySlow().

◆ AlterTableNamespace()

ObjectAddress AlterTableNamespace ( AlterObjectSchemaStmt stmt,
Oid oldschema 
)
extern

Definition at line 19210 of file tablecmds.c.

19211{
19212 Relation rel;
19213 Oid relid;
19214 Oid oldNspOid;
19215 Oid nspOid;
19216 RangeVar *newrv;
19219
19221 stmt->missing_ok ? RVR_MISSING_OK : 0,
19223 stmt);
19224
19225 if (!OidIsValid(relid))
19226 {
19228 (errmsg("relation \"%s\" does not exist, skipping",
19229 stmt->relation->relname)));
19230 return InvalidObjectAddress;
19231 }
19232
19233 rel = relation_open(relid, NoLock);
19234
19236
19237 /* If it's an owned sequence, disallow moving it by itself. */
19238 if (rel->rd_rel->relkind == RELKIND_SEQUENCE)
19239 {
19240 Oid tableId;
19241 int32 colId;
19242
19243 if (sequenceIsOwned(relid, DEPENDENCY_AUTO, &tableId, &colId) ||
19245 ereport(ERROR,
19247 errmsg("cannot move an owned sequence into another schema"),
19248 errdetail("Sequence \"%s\" is linked to table \"%s\".",
19251 }
19252
19253 /* Get and lock schema OID and check its permissions. */
19254 newrv = makeRangeVar(stmt->newschema, RelationGetRelationName(rel), -1);
19256
19257 /* common checks on switching namespaces */
19259
19263
19265
19266 if (oldschema)
19268
19269 /* close rel, but keep lock until commit */
19270 relation_close(rel, NoLock);
19271
19272 return myself;
19273}
int32_t int32
Definition c.h:620
ObjectAddresses * new_object_addresses(void)
void free_object_addresses(ObjectAddresses *addrs)
@ DEPENDENCY_AUTO
Definition dependency.h:34
@ DEPENDENCY_INTERNAL
Definition dependency.h:35
int errdetail(const char *fmt,...) pg_attribute_printf(1
char * get_rel_name(Oid relid)
Definition lsyscache.c:2121
RangeVar * makeRangeVar(char *schemaname, char *relname, int location)
Definition makefuncs.c:473
Oid RangeVarGetAndCheckCreationNamespace(RangeVar *relation, LOCKMODE lockmode, Oid *existing_relation_id)
Definition namespace.c:740
void CheckSetNamespace(Oid oldNspOid, Oid nspOid)
Definition namespace.c:3531
const ObjectAddress InvalidObjectAddress
#define ObjectAddressSet(addr, class_id, object_id)
bool sequenceIsOwned(Oid seqId, char deptype, Oid *tableId, int32 *colId)
Definition pg_depend.c:901
#define RelationGetRelationName(relation)
Definition rel.h:550
#define RelationGetNamespace(relation)
Definition rel.h:557
void relation_close(Relation relation, LOCKMODE lockmode)
Definition relation.c:206
Form_pg_class rd_rel
Definition rel.h:111
void AlterTableNamespaceInternal(Relation rel, Oid oldNspOid, Oid nspOid, ObjectAddresses *objsMoved)

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

Referenced by ExecAlterObjectSchemaStmt().

◆ AlterTableNamespaceInternal()

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

Definition at line 19281 of file tablecmds.c.

19283{
19285
19286 Assert(objsMoved != NULL);
19287
19288 /* OK, modify the pg_class row and pg_depend entry */
19290
19292 nspOid, true, objsMoved);
19293
19294 /* Fix the table's row type too, if it has one */
19295 if (OidIsValid(rel->rd_rel->reltype))
19297 false, /* isImplicitArray */
19298 false, /* ignoreDependent */
19299 false, /* errorOnTableType */
19300 objsMoved);
19301
19302 /* Fix other dependent stuff */
19307 false, objsMoved);
19308
19310}
#define RowExclusiveLock
Definition lockdefs.h:38
void AlterConstraintNamespaces(Oid ownerId, Oid oldNspId, Oid newNspId, bool isType, ObjectAddresses *objsMoved)
#define RelationGetRelid(relation)
Definition rel.h:516
void AlterRelationNamespaceInternal(Relation classRel, Oid relOid, Oid oldNspOid, Oid newNspOid, bool hasDependEntry, ObjectAddresses *objsMoved)
static void AlterSeqNamespaces(Relation classRel, Relation rel, Oid oldNspOid, Oid newNspOid, ObjectAddresses *objsMoved, LOCKMODE lockmode)
static void AlterIndexNamespaces(Relation classRel, Relation rel, Oid oldNspOid, Oid newNspOid, ObjectAddresses *objsMoved)
Oid AlterTypeNamespaceInternal(Oid typeOid, Oid nspOid, bool isImplicitArray, bool ignoreDependent, bool errorOnTableType, ObjectAddresses *objsMoved)
Definition typecmds.c:4199

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

Referenced by AlterObjectNamespace_oid(), and AlterTableNamespace().

◆ AtEOSubXact_on_commit_actions()

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

Definition at line 19723 of file tablecmds.c.

19725{
19727
19728 foreach(cur_item, on_commits)
19729 {
19731
19732 if (!isCommit && oc->creating_subid == mySubid)
19733 {
19734 /* cur_item must be removed */
19736 pfree(oc);
19737 }
19738 else
19739 {
19740 /* cur_item must be preserved */
19741 if (oc->creating_subid == mySubid)
19742 oc->creating_subid = parentSubid;
19743 if (oc->deleting_subid == mySubid)
19744 oc->deleting_subid = isCommit ? parentSubid : InvalidSubTransactionId;
19745 }
19746 }
19747}
#define InvalidSubTransactionId
Definition c.h:742
void pfree(void *pointer)
Definition mcxt.c:1616
#define foreach_delete_current(lst, var_or_cell)
Definition pg_list.h:423
static List * on_commits
Definition tablecmds.c:135

References fb(), foreach_delete_current, InvalidSubTransactionId, lfirst, on_commits, and pfree().

Referenced by AbortSubTransaction(), and CommitSubTransaction().

◆ AtEOXact_on_commit_actions()

void AtEOXact_on_commit_actions ( bool  isCommit)
extern

Definition at line 19691 of file tablecmds.c.

19692{
19694
19695 foreach(cur_item, on_commits)
19696 {
19698
19699 if (isCommit ? oc->deleting_subid != InvalidSubTransactionId :
19700 oc->creating_subid != InvalidSubTransactionId)
19701 {
19702 /* cur_item must be removed */
19704 pfree(oc);
19705 }
19706 else
19707 {
19708 /* cur_item must be preserved */
19709 oc->creating_subid = InvalidSubTransactionId;
19710 oc->deleting_subid = InvalidSubTransactionId;
19711 }
19712 }
19713}

References fb(), foreach_delete_current, InvalidSubTransactionId, lfirst, on_commits, and pfree().

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

◆ ATExecChangeOwner()

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

Definition at line 16344 of file tablecmds.c.

16345{
16348 HeapTuple tuple;
16350
16351 /*
16352 * Get exclusive lock till end of transaction on the target table. Use
16353 * relation_open so that we can work on indexes and sequences.
16354 */
16355 target_rel = relation_open(relationOid, lockmode);
16356
16357 /* Get its pg_class tuple, too */
16359
16360 tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relationOid));
16361 if (!HeapTupleIsValid(tuple))
16362 elog(ERROR, "cache lookup failed for relation %u", relationOid);
16364
16365 /* Can we change the ownership of this tuple? */
16366 switch (tuple_class->relkind)
16367 {
16368 case RELKIND_RELATION:
16369 case RELKIND_VIEW:
16370 case RELKIND_MATVIEW:
16373 case RELKIND_PROPGRAPH:
16374 /* ok to change owner */
16375 break;
16376 case RELKIND_INDEX:
16377 if (!recursing)
16378 {
16379 /*
16380 * Because ALTER INDEX OWNER used to be allowed, and in fact
16381 * is generated by old versions of pg_dump, we give a warning
16382 * and do nothing rather than erroring out. Also, to avoid
16383 * unnecessary chatter while restoring those old dumps, say
16384 * nothing at all if the command would be a no-op anyway.
16385 */
16386 if (tuple_class->relowner != newOwnerId)
16389 errmsg("cannot change owner of index \"%s\"",
16390 NameStr(tuple_class->relname)),
16391 errhint("Change the ownership of the index's table instead.")));
16392 /* quick hack to exit via the no-op path */
16393 newOwnerId = tuple_class->relowner;
16394 }
16395 break;
16397 if (recursing)
16398 break;
16399 ereport(ERROR,
16401 errmsg("cannot change owner of index \"%s\"",
16402 NameStr(tuple_class->relname)),
16403 errhint("Change the ownership of the index's table instead.")));
16404 break;
16405 case RELKIND_SEQUENCE:
16406 if (!recursing &&
16407 tuple_class->relowner != newOwnerId)
16408 {
16409 /* if it's an owned sequence, disallow changing it by itself */
16410 Oid tableId;
16411 int32 colId;
16412
16413 if (sequenceIsOwned(relationOid, DEPENDENCY_AUTO, &tableId, &colId) ||
16415 ereport(ERROR,
16417 errmsg("cannot change owner of sequence \"%s\"",
16418 NameStr(tuple_class->relname)),
16419 errdetail("Sequence \"%s\" is linked to table \"%s\".",
16420 NameStr(tuple_class->relname),
16422 }
16423 break;
16425 if (recursing)
16426 break;
16427 ereport(ERROR,
16429 errmsg("\"%s\" is a composite type",
16430 NameStr(tuple_class->relname)),
16431 /* translator: %s is an SQL ALTER command */
16432 errhint("Use %s instead.",
16433 "ALTER TYPE")));
16434 break;
16435 case RELKIND_TOASTVALUE:
16436 if (recursing)
16437 break;
16439 default:
16440 ereport(ERROR,
16442 errmsg("cannot change owner of relation \"%s\"",
16443 NameStr(tuple_class->relname)),
16445 }
16446
16447 /*
16448 * If the new owner is the same as the existing owner, consider the
16449 * command to have succeeded. This is for dump restoration purposes.
16450 */
16451 if (tuple_class->relowner != newOwnerId)
16452 {
16456 Acl *newAcl;
16458 bool isNull;
16459 HeapTuple newtuple;
16460
16461 /* skip permission checks when recursing to index or toast table */
16462 if (!recursing)
16463 {
16464 /* Superusers can always do it */
16465 if (!superuser())
16466 {
16467 Oid namespaceOid = tuple_class->relnamespace;
16469
16470 /* Otherwise, must be owner of the existing object */
16471 if (!object_ownercheck(RelationRelationId, relationOid, GetUserId()))
16474
16475 /* Must be able to become new owner */
16477
16478 /* New owner must have CREATE privilege on namespace */
16480 ACL_CREATE);
16481 if (aclresult != ACLCHECK_OK)
16484 }
16485 }
16486
16487 memset(repl_null, false, sizeof(repl_null));
16488 memset(repl_repl, false, sizeof(repl_repl));
16489
16492
16493 /*
16494 * Determine the modified ACL for the new owner. This is only
16495 * necessary when the ACL is non-null.
16496 */
16499 &isNull);
16500 if (!isNull)
16501 {
16503 tuple_class->relowner, newOwnerId);
16504 repl_repl[Anum_pg_class_relacl - 1] = true;
16506 }
16507
16509
16510 CatalogTupleUpdate(class_rel, &newtuple->t_self, newtuple);
16511
16512 heap_freetuple(newtuple);
16513
16514 /*
16515 * We must similarly update any per-column ACLs to reflect the new
16516 * owner; for neatness reasons that's split out as a subroutine.
16517 */
16518 change_owner_fix_column_acls(relationOid,
16519 tuple_class->relowner,
16520 newOwnerId);
16521
16522 /*
16523 * Update owner dependency reference, if any. A composite type has
16524 * none, because it's tracked for the pg_type entry instead of here;
16525 * indexes and TOAST tables don't have their own entries either.
16526 */
16527 if (tuple_class->relkind != RELKIND_COMPOSITE_TYPE &&
16528 tuple_class->relkind != RELKIND_INDEX &&
16530 tuple_class->relkind != RELKIND_TOASTVALUE)
16532 newOwnerId);
16533
16534 /*
16535 * Also change the ownership of the table's row type, if it has one
16536 */
16537 if (OidIsValid(tuple_class->reltype))
16539
16540 /*
16541 * If we are operating on a table or materialized view, also change
16542 * the ownership of any indexes and sequences that belong to the
16543 * relation, as well as its toast table (if it has one).
16544 */
16545 if (tuple_class->relkind == RELKIND_RELATION ||
16547 tuple_class->relkind == RELKIND_MATVIEW ||
16548 tuple_class->relkind == RELKIND_TOASTVALUE)
16549 {
16551 ListCell *i;
16552
16553 /* Find all the indexes belonging to this relation */
16555
16556 /* For each index, recursively change its ownership */
16557 foreach(i, index_oid_list)
16558 ATExecChangeOwner(lfirst_oid(i), newOwnerId, true, lockmode);
16559
16561 }
16562
16563 /* If it has a toast table, recurse to change its ownership */
16564 if (tuple_class->reltoastrelid != InvalidOid)
16566 true, lockmode);
16567
16568 /* If it has dependent sequences, recurse to change them too */
16569 change_owner_recurse_to_sequences(relationOid, newOwnerId, lockmode);
16570 }
16571
16573
16574 ReleaseSysCache(tuple);
16577}
Acl * aclnewowner(const Acl *old_acl, Oid oldOwnerId, Oid newOwnerId)
Definition acl.c:1147
void check_can_set_role(Oid member, Oid role)
Definition acl.c:5371
#define DatumGetAclP(X)
Definition acl.h:120
#define pg_fallthrough
Definition c.h:161
int errhint(const char *fmt,...) pg_attribute_printf(1
#define WARNING
Definition elog.h:37
HeapTuple heap_modify_tuple(HeapTuple tuple, TupleDesc tupleDesc, const Datum *replValues, const bool *replIsnull, const bool *doReplace)
Definition heaptuple.c:1118
int i
Definition isn.c:77
void list_free(List *list)
Definition list.c:1546
@ OBJECT_SCHEMA
int errdetail_relkind_not_supported(char relkind)
Definition pg_class.c:24
void changeDependencyOnOwner(Oid classId, Oid objectId, Oid newOwnerId)
uint64_t Datum
Definition postgres.h:70
#define PointerGetDatum(X)
Definition postgres.h:354
#define RelationGetDescr(relation)
Definition rel.h:542
List * RelationGetIndexList(Relation relation)
Definition relcache.c:4827
ItemPointerData t_self
Definition htup.h:65
bool superuser(void)
Definition superuser.c:47
void ReleaseSysCache(HeapTuple tuple)
Definition syscache.c:265
HeapTuple SearchSysCache1(SysCacheIdentifier cacheId, Datum key1)
Definition syscache.c:221
Datum SysCacheGetAttr(SysCacheIdentifier cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition syscache.c:596
void ATExecChangeOwner(Oid relationOid, Oid newOwnerId, bool recursing, LOCKMODE lockmode)
static void change_owner_recurse_to_sequences(Oid relationOid, Oid newOwnerId, LOCKMODE lockmode)
static void change_owner_fix_column_acls(Oid relationOid, Oid oldOwnerId, Oid newOwnerId)
void AlterTypeOwnerInternal(Oid typeOid, Oid newOwnerId)
Definition typecmds.c:4030

References ACL_CREATE, aclcheck_error(), ACLCHECK_NOT_OWNER, ACLCHECK_OK, aclnewowner(), AlterTypeOwnerInternal(), ATExecChangeOwner(), CatalogTupleUpdate(), change_owner_fix_column_acls(), change_owner_recurse_to_sequences(), changeDependencyOnOwner(), check_can_set_role(), DatumGetAclP, DEPENDENCY_AUTO, DEPENDENCY_INTERNAL, elog, ereport, errcode(), errdetail(), errdetail_relkind_not_supported(), errhint(), errmsg, ERROR, fb(), get_namespace_name(), get_rel_name(), get_rel_relkind(), get_relkind_objtype(), GETSTRUCT(), GetUserId(), heap_freetuple(), heap_modify_tuple(), HeapTupleIsValid, i, InvalidOid, InvokeObjectPostAlterHook, lfirst_oid, list_free(), NameStr, NoLock, object_aclcheck(), object_ownercheck(), OBJECT_SCHEMA, ObjectIdGetDatum(), OidIsValid, pg_fallthrough, PointerGetDatum, relation_close(), relation_open(), RelationGetDescr, RelationGetIndexList(), RelationGetRelationName, ReleaseSysCache(), RowExclusiveLock, SearchSysCache1(), sequenceIsOwned(), superuser(), SysCacheGetAttr(), HeapTupleData::t_self, table_close(), table_open(), and WARNING.

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

◆ BuildDescForRelation()

TupleDesc BuildDescForRelation ( const List columns)
extern

Definition at line 1429 of file tablecmds.c.

1430{
1431 int natts;
1433 ListCell *l;
1434 TupleDesc desc;
1435 char *attname;
1436 Oid atttypid;
1437 int32 atttypmod;
1438 Oid attcollation;
1439 int attdim;
1440
1441 /*
1442 * allocate a new tuple descriptor
1443 */
1444 natts = list_length(columns);
1445 desc = CreateTemplateTupleDesc(natts);
1446
1447 attnum = 0;
1448
1449 foreach(l, columns)
1450 {
1451 ColumnDef *entry = lfirst(l);
1454
1455 /*
1456 * for each entry in the list, get the name and type information from
1457 * the list and have TupleDescInitEntry fill in the attribute
1458 * information we need.
1459 */
1460 attnum++;
1461
1462 attname = entry->colname;
1463 typenameTypeIdAndMod(NULL, entry->typeName, &atttypid, &atttypmod);
1464
1466 if (aclresult != ACLCHECK_OK)
1468
1469 attcollation = GetColumnDefCollation(NULL, entry, atttypid);
1471 if (attdim > PG_INT16_MAX)
1472 ereport(ERROR,
1474 errmsg("too many array dimensions"));
1475
1476 if (entry->typeName->setof)
1477 ereport(ERROR,
1479 errmsg("column \"%s\" cannot be declared SETOF",
1480 attname)));
1481
1483 atttypid, atttypmod, attdim);
1484 att = TupleDescAttr(desc, attnum - 1);
1485
1486 /* Override TupleDescInitEntry's settings as requested */
1487 TupleDescInitEntryCollation(desc, attnum, attcollation);
1488
1489 /* Fill in additional stuff not handled by TupleDescInitEntry */
1490 att->attnotnull = entry->is_not_null;
1491 att->attislocal = entry->is_local;
1492 att->attinhcount = entry->inhcount;
1493 att->attidentity = entry->identity;
1494 att->attgenerated = entry->generated;
1495 att->attcompression = GetAttributeCompression(att->atttypid, entry->compression);
1496 if (entry->storage)
1497 att->attstorage = entry->storage;
1498 else if (entry->storage_name)
1499 att->attstorage = GetAttributeStorage(att->atttypid, entry->storage_name);
1500
1502 }
1503
1504 TupleDescFinalize(desc);
1505
1506 return desc;
1507}
void aclcheck_error_type(AclResult aclerr, Oid typeOid)
Definition aclchk.c:2997
int16 AttrNumber
Definition attnum.h:21
#define PG_INT16_MAX
Definition c.h:670
void typenameTypeIdAndMod(ParseState *pstate, const TypeName *typeName, Oid *typeid_p, int32 *typmod_p)
Definition parse_type.c:310
Oid GetColumnDefCollation(ParseState *pstate, const ColumnDef *coldef, Oid typeOid)
Definition parse_type.c:540
#define ACL_USAGE
Definition parsenodes.h:84
NameData attname
int16 attnum
FormData_pg_attribute * Form_pg_attribute
static int list_length(const List *l)
Definition pg_list.h:152
bool is_not_null
Definition parsenodes.h:775
char identity
Definition parsenodes.h:781
char * storage_name
Definition parsenodes.h:778
char * colname
Definition parsenodes.h:770
TypeName * typeName
Definition parsenodes.h:771
char generated
Definition parsenodes.h:784
char storage
Definition parsenodes.h:777
bool is_local
Definition parsenodes.h:774
int16 inhcount
Definition parsenodes.h:773
char * compression
Definition parsenodes.h:772
bool setof
Definition parsenodes.h:290
List * arrayBounds
Definition parsenodes.h:294
static char GetAttributeCompression(Oid atttypid, const char *compression)
static char GetAttributeStorage(Oid atttypid, const char *storagemode)
TupleDesc CreateTemplateTupleDesc(int natts)
Definition tupdesc.c:165
void TupleDescFinalize(TupleDesc tupdesc)
Definition tupdesc.c:511
void populate_compact_attribute(TupleDesc tupdesc, int attnum)
Definition tupdesc.c:100
void TupleDescInitEntryCollation(TupleDesc desc, AttrNumber attributeNumber, Oid collationid)
Definition tupdesc.c:1084
void TupleDescInitEntry(TupleDesc desc, AttrNumber attributeNumber, const char *attributeName, Oid oidtypeid, int32 typmod, int attdim)
Definition tupdesc.c:900
static FormData_pg_attribute * TupleDescAttr(TupleDesc tupdesc, int i)
Definition tupdesc.h:178

References ACL_USAGE, aclcheck_error_type(), ACLCHECK_OK, TypeName::arrayBounds, attname, attnum, ColumnDef::colname, ColumnDef::compression, CreateTemplateTupleDesc(), ereport, errcode(), errmsg, ERROR, fb(), ColumnDef::generated, GetAttributeCompression(), GetAttributeStorage(), GetColumnDefCollation(), GetUserId(), ColumnDef::identity, ColumnDef::inhcount, ColumnDef::is_local, ColumnDef::is_not_null, lfirst, list_length(), object_aclcheck(), PG_INT16_MAX, populate_compact_attribute(), TypeName::setof, ColumnDef::storage, ColumnDef::storage_name, TupleDescAttr(), TupleDescFinalize(), TupleDescInitEntry(), TupleDescInitEntryCollation(), ColumnDef::typeName, and typenameTypeIdAndMod().

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

◆ check_of_type()

void check_of_type ( HeapTuple  typetuple)
extern

Definition at line 7233 of file tablecmds.c.

7234{
7236 bool typeOk = false;
7237
7238 if (typ->typtype == TYPTYPE_COMPOSITE)
7239 {
7241
7242 Assert(OidIsValid(typ->typrelid));
7244 typeOk = (typeRelation->rd_rel->relkind == RELKIND_COMPOSITE_TYPE);
7245
7246 /*
7247 * Close the parent rel, but keep our AccessShareLock on it until xact
7248 * commit. That will prevent someone else from deleting or ALTERing
7249 * the type before the typed table creation/conversion commits.
7250 */
7252
7253 if (!typeOk)
7254 ereport(ERROR,
7256 errmsg("type %s is the row type of another table",
7257 format_type_be(typ->oid)),
7258 errdetail("A typed table must use a stand-alone composite type created with CREATE TYPE.")));
7259 }
7260 else
7261 ereport(ERROR,
7263 errmsg("type %s is not a composite type",
7264 format_type_be(typ->oid))));
7265}
char * format_type_be(Oid type_oid)
END_CATALOG_STRUCT typedef FormData_pg_type * Form_pg_type
Definition pg_type.h:265

References AccessShareLock, Assert, ereport, errcode(), errdetail(), errmsg, ERROR, fb(), Form_pg_type, format_type_be(), GETSTRUCT(), NoLock, OidIsValid, relation_close(), and relation_open().

Referenced by ATExecAddOf(), and transformOfType().

◆ CheckRelationTableSpaceMove()

bool CheckRelationTableSpaceMove ( Relation  rel,
Oid  newTableSpaceId 
)
extern

Definition at line 3750 of file tablecmds.c.

3751{
3753
3754 /*
3755 * No work if no change in tablespace. Note that MyDatabaseTableSpace is
3756 * stored as 0.
3757 */
3758 oldTableSpaceId = rel->rd_rel->reltablespace;
3761 return false;
3762
3763 /*
3764 * We cannot support moving mapped relations into different tablespaces.
3765 * (In particular this eliminates all shared catalogs.)
3766 */
3767 if (RelationIsMapped(rel))
3768 ereport(ERROR,
3770 errmsg("cannot move system relation \"%s\"",
3772
3773 /* Cannot move a non-shared relation into pg_global */
3775 ereport(ERROR,
3777 errmsg("only shared relations can be placed in pg_global tablespace")));
3778
3779 /*
3780 * Do not allow moving temp tables of other backends ... their local
3781 * buffer manager is not going to cope.
3782 */
3783 if (RELATION_IS_OTHER_TEMP(rel))
3784 ereport(ERROR,
3786 errmsg("cannot move temporary tables of other sessions")));
3787
3788 return true;
3789}
#define RelationIsMapped(relation)
Definition rel.h:565
#define RELATION_IS_OTHER_TEMP(relation)
Definition rel.h:669

References ereport, errcode(), errmsg, ERROR, fb(), MyDatabaseTableSpace, RelationData::rd_rel, RELATION_IS_OTHER_TEMP, RelationGetRelationName, and RelationIsMapped.

Referenced by ATExecSetTableSpace(), ATExecSetTableSpaceNoStorage(), reindex_index(), and SetRelationTableSpace().

◆ CheckTableNotInUse()

void CheckTableNotInUse ( Relation  rel,
const char stmt 
)
extern

Definition at line 4473 of file tablecmds.c.

4474{
4475 int expected_refcnt;
4476
4477 expected_refcnt = rel->rd_isnailed ? 2 : 1;
4478 if (rel->rd_refcnt != expected_refcnt)
4479 ereport(ERROR,
4481 /* translator: first %s is a SQL command, eg ALTER TABLE */
4482 errmsg("cannot %s \"%s\" because it is being used by active queries in this session",
4484
4485 if (rel->rd_rel->relkind != RELKIND_INDEX &&
4486 rel->rd_rel->relkind != RELKIND_PARTITIONED_INDEX &&
4488 ereport(ERROR,
4490 /* translator: first %s is a SQL command, eg ALTER TABLE */
4491 errmsg("cannot %s \"%s\" because it has pending trigger events",
4493}
int rd_refcnt
Definition rel.h:59
bool rd_isnailed
Definition rel.h:62
bool AfterTriggerPendingOnRel(Oid relid)
Definition trigger.c:6145

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

Referenced by CheckAlterTableIsSafe(), cluster_rel(), DefineIndex(), DefineVirtualRelation(), heap_drop_with_catalog(), index_drop(), MergeAttributes(), RefreshMatViewByOid(), reindex_index(), and truncate_check_activity().

◆ DefineRelation()

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

Definition at line 810 of file tablecmds.c.

812{
813 char relname[NAMEDATALEN];
817 Relation rel;
824 List *nncols;
825 List *connames = NIL;
826 Datum reloptions;
829 bool partitioned;
830 const char *const validnsps[] = HEAP_RELOPT_NAMESPACES;
832 ObjectAddress address;
835
836 /*
837 * Truncate relname to appropriate length (probably a waste of time, as
838 * parser should have done this already).
839 */
840 strlcpy(relname, stmt->relation->relname, NAMEDATALEN);
841
842 /*
843 * Check consistency of arguments
844 */
845 if (stmt->oncommit != ONCOMMIT_NOOP
846 && stmt->relation->relpersistence != RELPERSISTENCE_TEMP)
849 errmsg("ON COMMIT can only be used on temporary tables")));
850
851 if (stmt->partspec != NULL)
852 {
853 if (relkind != RELKIND_RELATION)
854 elog(ERROR, "unexpected relkind: %d", (int) relkind);
855
857 partitioned = true;
858 }
859 else
860 partitioned = false;
861
862 if (relkind == RELKIND_PARTITIONED_TABLE &&
863 stmt->relation->relpersistence == RELPERSISTENCE_UNLOGGED)
866 errmsg("partitioned tables cannot be unlogged")));
867
868 /*
869 * Look up the namespace in which we are supposed to create the relation,
870 * check we have permission to create there, lock it against concurrent
871 * drop, and mark stmt->relation as RELPERSISTENCE_TEMP if a temporary
872 * namespace is selected.
873 */
876
877 /*
878 * Security check: disallow creating temp tables from security-restricted
879 * code. This is needed because calling code might not expect untrusted
880 * tables to appear in pg_temp at the front of its search path.
881 */
882 if (stmt->relation->relpersistence == RELPERSISTENCE_TEMP
886 errmsg("cannot create temporary table within security-restricted operation")));
887
888 /*
889 * Determine the lockmode to use when scanning parents. A self-exclusive
890 * lock is needed here.
891 *
892 * For regular inheritance, if two backends attempt to add children to the
893 * same parent simultaneously, and that parent has no pre-existing
894 * children, then both will attempt to update the parent's relhassubclass
895 * field, leading to a "tuple concurrently updated" error. Also, this
896 * interlocks against a concurrent ANALYZE on the parent table, which
897 * might otherwise be attempting to clear the parent's relhassubclass
898 * field, if its previous children were recently dropped.
899 *
900 * If the child table is a partition, then we instead grab an exclusive
901 * lock on the parent because its partition descriptor will be changed by
902 * addition of the new partition.
903 */
904 parentLockmode = (stmt->partbound != NULL ? AccessExclusiveLock :
906
907 /* Determine the list of OIDs of the parents. */
909 foreach(listptr, stmt->inhRelations)
910 {
911 RangeVar *rv = (RangeVar *) lfirst(listptr);
913
915
916 /*
917 * Reject duplications in the list of parents.
918 */
922 errmsg("relation \"%s\" would be inherited from more than once",
924
926 }
927
928 /*
929 * Select tablespace to use: an explicitly indicated one, or (in the case
930 * of a partitioned table) the parent's, if it has one.
931 */
932 if (stmt->tablespacename)
933 {
934 tablespaceId = get_tablespace_oid(stmt->tablespacename, false);
935
939 errmsg("cannot specify default tablespace for partitioned relations")));
940 }
941 else if (stmt->partbound)
942 {
945 }
946 else
948
949 /* still nothing? use the default */
951 tablespaceId = GetDefaultTablespace(stmt->relation->relpersistence,
953
954 /* Check permissions except when using database's default */
956 {
958
960 ACL_CREATE);
961 if (aclresult != ACLCHECK_OK)
964 }
965
966 /* In all cases disallow placing user relations in pg_global */
970 errmsg("only shared relations can be placed in pg_global tablespace")));
971
972 /* Identify user ID that will own the table */
973 if (!OidIsValid(ownerId))
974 ownerId = GetUserId();
975
976 /*
977 * Parse and validate reloptions, if any.
978 */
979 reloptions = transformRelOptions((Datum) 0, stmt->options, NULL, validnsps,
980 true, false);
981
982 switch (relkind)
983 {
984 case RELKIND_VIEW:
985 (void) view_reloptions(reloptions, true);
986 break;
988 (void) partitioned_table_reloptions(reloptions, true);
989 break;
990 default:
991 (void) heap_reloptions(relkind, reloptions, true);
992 }
993
994 if (stmt->ofTypename)
995 {
997
998 ofTypeId = typenameTypeId(NULL, stmt->ofTypename);
999
1001 if (aclresult != ACLCHECK_OK)
1003 }
1004 else
1006
1007 /*
1008 * Look up inheritance ancestors and generate relation schema, including
1009 * inherited attributes. (Note that stmt->tableElts is destructively
1010 * modified by MergeAttributes.)
1011 */
1012 stmt->tableElts =
1013 MergeAttributes(stmt->tableElts, inheritOids,
1014 stmt->relation->relpersistence,
1015 stmt->partbound != NULL,
1017
1018 /*
1019 * Create a tuple descriptor from the relation schema. Note that this
1020 * deals with column names, types, and in-descriptor NOT NULL flags, but
1021 * not default values, NOT NULL or CHECK constraints; we handle those
1022 * below.
1023 */
1024 descriptor = BuildDescForRelation(stmt->tableElts);
1025
1026 /*
1027 * Find columns with default values and prepare for insertion of the
1028 * defaults. Pre-cooked (that is, inherited) defaults go into a list of
1029 * CookedConstraint structs that we'll pass to heap_create_with_catalog,
1030 * while raw defaults go into a list of RawColumnDefault structs that will
1031 * be processed by AddRelationNewConstraints. (We can't deal with raw
1032 * expressions until we can do transformExpr.)
1033 */
1034 rawDefaults = NIL;
1036 attnum = 0;
1037
1038 foreach(listptr, stmt->tableElts)
1039 {
1041
1042 attnum++;
1043 if (colDef->raw_default != NULL)
1044 {
1046
1047 Assert(colDef->cooked_default == NULL);
1048
1050 rawEnt->attnum = attnum;
1051 rawEnt->raw_default = colDef->raw_default;
1052 rawEnt->generated = colDef->generated;
1054 }
1055 else if (colDef->cooked_default != NULL)
1056 {
1058
1060 cooked->contype = CONSTR_DEFAULT;
1061 cooked->conoid = InvalidOid; /* until created */
1062 cooked->name = NULL;
1063 cooked->attnum = attnum;
1064 cooked->expr = colDef->cooked_default;
1065 cooked->is_enforced = true;
1066 cooked->skip_validation = false;
1067 cooked->is_local = true; /* not used for defaults */
1068 cooked->inhcount = 0; /* ditto */
1069 cooked->is_no_inherit = false;
1071 }
1072 }
1073
1075
1076 /*
1077 * For relations with table AM and partitioned tables, select access
1078 * method to use: an explicitly indicated one, or (in the case of a
1079 * partitioned table) the parent's, if it has one.
1080 */
1081 if (stmt->accessMethod != NULL)
1082 {
1084 accessMethodId = get_table_am_oid(stmt->accessMethod, false);
1085 }
1086 else if (RELKIND_HAS_TABLE_AM(relkind) || relkind == RELKIND_PARTITIONED_TABLE)
1087 {
1088 if (stmt->partbound)
1089 {
1092 }
1093
1096 }
1097
1098 /*
1099 * Create the relation. Inherited defaults and CHECK constraints are
1100 * passed in for immediate handling --- since they don't need parsing,
1101 * they can be stored immediately.
1102 */
1106 InvalidOid,
1107 InvalidOid,
1108 ofTypeId,
1109 ownerId,
1111 descriptor,
1114 relkind,
1115 stmt->relation->relpersistence,
1116 false,
1117 false,
1118 stmt->oncommit,
1119 reloptions,
1120 true,
1122 false,
1123 InvalidOid,
1124 typaddress);
1125
1126 /*
1127 * We must bump the command counter to make the newly-created relation
1128 * tuple visible for opening.
1129 */
1131
1132 /*
1133 * Open the new relation and acquire exclusive lock on it. This isn't
1134 * really necessary for locking out other backends (since they can't see
1135 * the new rel anyway until we commit), but it keeps the lock manager from
1136 * complaining about deadlock risks.
1137 */
1139
1140 /*
1141 * Now add any newly specified column default and generation expressions
1142 * to the new relation. These are passed to us in the form of raw
1143 * parsetrees; we need to transform them to executable expression trees
1144 * before they can be added. The most convenient way to do that is to
1145 * apply the parser's transformExpr routine, but transformExpr doesn't
1146 * work unless we have a pre-existing relation. So, the transformation has
1147 * to be postponed to this final step of CREATE TABLE.
1148 *
1149 * This needs to be before processing the partitioning clauses because
1150 * those could refer to generated columns.
1151 */
1152 if (rawDefaults)
1154 true, true, false, queryString);
1155
1156 /*
1157 * Make column generation expressions visible for use by partitioning.
1158 */
1160
1161 /* Process and store partition bound, if any. */
1162 if (stmt->partbound)
1163 {
1164 PartitionBoundSpec *bound;
1165 ParseState *pstate;
1168 Relation parent,
1169 defaultRel = NULL;
1171
1172 /* Already have strong enough lock on the parent */
1173 parent = table_open(parentId, NoLock);
1174
1175 /*
1176 * We are going to try to validate the partition bound specification
1177 * against the partition key of parentRel, so it better have one.
1178 */
1179 if (parent->rd_rel->relkind != RELKIND_PARTITIONED_TABLE)
1180 ereport(ERROR,
1182 errmsg("\"%s\" is not partitioned",
1183 RelationGetRelationName(parent))));
1184
1185 /*
1186 * The partition constraint of the default partition depends on the
1187 * partition bounds of every other partition. It is possible that
1188 * another backend might be about to execute a query on the default
1189 * partition table, and that the query relies on previously cached
1190 * default partition constraints. We must therefore take a table lock
1191 * strong enough to prevent all queries on the default partition from
1192 * proceeding until we commit and send out a shared-cache-inval notice
1193 * that will make them update their index lists.
1194 *
1195 * Order of locking: The relation being added won't be visible to
1196 * other backends until it is committed, hence here in
1197 * DefineRelation() the order of locking the default partition and the
1198 * relation being added does not matter. But at all other places we
1199 * need to lock the default relation before we lock the relation being
1200 * added or removed i.e. we should take the lock in same order at all
1201 * the places such that lock parent, lock default partition and then
1202 * lock the partition so as to avoid a deadlock.
1203 */
1206 true));
1209
1210 /* Transform the bound values */
1211 pstate = make_parsestate(NULL);
1212 pstate->p_sourcetext = queryString;
1213
1214 /*
1215 * Add an nsitem containing this relation, so that transformExpr
1216 * called on partition bound expressions is able to report errors
1217 * using a proper context.
1218 */
1220 NULL, false, false);
1221 addNSItemToQuery(pstate, nsitem, false, true, true);
1222
1223 bound = transformPartitionBound(pstate, parent, stmt->partbound);
1224
1225 /*
1226 * Check first that the new partition's bound is valid and does not
1227 * overlap with any of existing partitions of the parent.
1228 */
1229 check_new_partition_bound(relname, parent, bound, pstate);
1230
1231 /*
1232 * If the default partition exists, its partition constraints will
1233 * change after the addition of this new partition such that it won't
1234 * allow any row that qualifies for this new partition. So, check that
1235 * the existing data in the default partition satisfies the constraint
1236 * as it will exist after adding this partition.
1237 */
1239 {
1241 /* Keep the lock until commit. */
1243 }
1244
1245 /* Update the pg_class entry. */
1246 StorePartitionBound(rel, parent, bound);
1247
1248 table_close(parent, NoLock);
1249 }
1250
1251 /* Store inheritance information for new rel. */
1253
1254 /*
1255 * Process the partitioning specification (if any) and store the partition
1256 * key information into the catalog.
1257 */
1258 if (partitioned)
1259 {
1260 ParseState *pstate;
1261 int partnatts;
1262 AttrNumber partattrs[PARTITION_MAX_KEYS];
1264 Oid partcollation[PARTITION_MAX_KEYS];
1265 List *partexprs = NIL;
1266
1267 pstate = make_parsestate(NULL);
1268 pstate->p_sourcetext = queryString;
1269
1270 partnatts = list_length(stmt->partspec->partParams);
1271
1272 /* Protect fixed-size arrays here and in executor */
1273 if (partnatts > PARTITION_MAX_KEYS)
1274 ereport(ERROR,
1276 errmsg("cannot partition using more than %d columns",
1278
1279 /*
1280 * We need to transform the raw parsetrees corresponding to partition
1281 * expressions into executable expression trees. Like column defaults
1282 * and CHECK constraints, we could not have done the transformation
1283 * earlier.
1284 */
1285 stmt->partspec = transformPartitionSpec(rel, stmt->partspec);
1286
1287 ComputePartitionAttrs(pstate, rel, stmt->partspec->partParams,
1288 partattrs, &partexprs, partopclass,
1289 partcollation, stmt->partspec->strategy);
1290
1291 StorePartitionKey(rel, stmt->partspec->strategy, partnatts, partattrs,
1292 partexprs,
1293 partopclass, partcollation);
1294
1295 /* make it all visible */
1297 }
1298
1299 /*
1300 * If we're creating a partition, create now all the indexes, triggers,
1301 * FKs defined in the parent.
1302 *
1303 * We can't do it earlier, because DefineIndex wants to know the partition
1304 * key which we just stored.
1305 */
1306 if (stmt->partbound)
1307 {
1309 Relation parent;
1310 List *idxlist;
1311 ListCell *cell;
1312
1313 /* Already have strong enough lock on the parent */
1314 parent = table_open(parentId, NoLock);
1315 idxlist = RelationGetIndexList(parent);
1316
1317 /*
1318 * For each index in the parent table, create one in the partition
1319 */
1320 foreach(cell, idxlist)
1321 {
1323 AttrMap *attmap;
1326
1327 if (rel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
1328 {
1329 if (idxRel->rd_index->indisunique)
1330 ereport(ERROR,
1332 errmsg("cannot create foreign partition of partitioned table \"%s\"",
1333 RelationGetRelationName(parent)),
1334 errdetail("Table \"%s\" contains indexes that are unique.",
1335 RelationGetRelationName(parent))));
1336 else
1337 {
1339 continue;
1340 }
1341 }
1342
1344 RelationGetDescr(parent),
1345 false);
1346 idxstmt =
1350 RelationGetRelid(rel),
1351 idxstmt,
1352 InvalidOid,
1355 -1,
1356 false, false, false, false, false);
1357
1359 }
1360
1362
1363 /*
1364 * If there are any row-level triggers, clone them to the new
1365 * partition.
1366 */
1367 if (parent->trigdesc != NULL)
1368 CloneRowTriggersToPartition(parent, rel);
1369
1370 /*
1371 * And foreign keys too. Note that because we're freshly creating the
1372 * table, there is no need to verify these new constraints.
1373 */
1374 CloneForeignKeyConstraints(NULL, parent, rel);
1375
1376 table_close(parent, NoLock);
1377 }
1378
1379 /*
1380 * Now add any newly specified CHECK constraints to the new relation. Same
1381 * as for defaults above, but these need to come after partitioning is set
1382 * up. We save the constraint names that were used, to avoid dupes below.
1383 */
1384 if (stmt->constraints)
1385 {
1386 List *conlist;
1387
1388 conlist = AddRelationNewConstraints(rel, NIL, stmt->constraints,
1389 true, true, false, queryString);
1391 {
1392 if (cons->name != NULL)
1393 connames = lappend(connames, cons->name);
1394 }
1395 }
1396
1397 /*
1398 * Finally, merge the not-null constraints that are declared directly with
1399 * those that come from parent relations (making sure to count inheritance
1400 * appropriately for each), create them, and set the attnotnull flag on
1401 * columns that don't yet have it.
1402 */
1403 nncols = AddRelationNotNullConstraints(rel, stmt->nnconstraints,
1405 foreach_int(attrnum, nncols)
1406 set_attnotnull(NULL, rel, attrnum, true, false);
1407
1409
1410 /*
1411 * Clean up. We keep lock on new relation (although it shouldn't be
1412 * visible to anyone else anyway, until commit).
1413 */
1414 relation_close(rel, NoLock);
1415
1416 return address;
1417}
Oid get_table_am_oid(const char *amname, bool missing_ok)
Definition amcmds.c:173
AttrMap * build_attrmap_by_name(TupleDesc indesc, TupleDesc outdesc, bool missing_ok)
Definition attmap.c:175
Oid GetDefaultTablespace(char relpersistence, bool partitioned)
#define palloc_object(type)
Definition fe_memutils.h:74
bool allowSystemTableMods
Definition globals.c:132
void StorePartitionKey(Relation rel, char strategy, int16 partnatts, AttrNumber *partattrs, List *partexprs, Oid *partopclass, Oid *partcollation)
Definition heap.c:3912
Oid heap_create_with_catalog(const char *relname, Oid relnamespace, Oid reltablespace, Oid relid, Oid reltypeid, Oid reloftypeid, Oid ownerid, Oid accessmtd, TupleDesc tupdesc, List *cooked_constraints, char relkind, char relpersistence, bool shared_relation, bool mapped_relation, OnCommitAction oncommit, Datum reloptions, bool use_user_acl, bool allow_system_table_mods, bool is_internal, Oid relrewrite, ObjectAddress *typaddress)
Definition heap.c:1136
List * AddRelationNotNullConstraints(Relation rel, List *constraints, List *old_notnulls, List *existing_constraints)
Definition heap.c:2911
void StorePartitionBound(Relation rel, Relation parent, PartitionBoundSpec *bound)
Definition heap.c:4068
List * AddRelationNewConstraints(Relation rel, List *newColDefaults, List *newConstraints, bool allow_merge, bool is_local, bool is_internal, const char *queryString)
Definition heap.c:2399
void index_close(Relation relation, LOCKMODE lockmode)
Definition indexam.c:178
Relation index_open(Oid relationId, LOCKMODE lockmode)
Definition indexam.c:134
ObjectAddress DefineIndex(ParseState *pstate, Oid tableId, const IndexStmt *stmt, Oid indexRelationId, Oid parentIndexId, Oid parentConstraintId, int total_parts, bool is_alter_table, bool check_rights, bool check_not_in_use, bool skip_build, bool quiet)
Definition indexcmds.c:545
List * list_concat(List *list1, const List *list2)
Definition list.c:561
Oid get_rel_relam(Oid relid)
Definition lsyscache.c:2293
Oid get_rel_tablespace(Oid relid)
Definition lsyscache.c:2247
bool InSecurityRestrictedOperation(void)
Definition miscinit.c:640
#define RangeVarGetRelid(relation, lockmode, missing_ok)
Definition namespace.h:98
ParseState * make_parsestate(ParseState *parentParseState)
Definition parse_node.c:39
void addNSItemToQuery(ParseState *pstate, ParseNamespaceItem *nsitem, bool addToJoinList, bool addToRelNameSpace, bool addToVarNameSpace)
ParseNamespaceItem * addRangeTableEntryForRelation(ParseState *pstate, Relation rel, LOCKMODE lockmode, Alias *alias, bool inh, bool inFromCl)
Oid typenameTypeId(ParseState *pstate, const TypeName *typeName)
Definition parse_type.c:291
PartitionBoundSpec * transformPartitionBound(ParseState *pstate, Relation parent, PartitionBoundSpec *spec)
IndexStmt * generateClonedIndexStmt(RangeVar *heapRel, Relation source_idx, const AttrMap *attmap, Oid *constraintOid)
@ CONSTR_DEFAULT
void check_new_partition_bound(char *relname, Relation parent, PartitionBoundSpec *spec, ParseState *pstate)
void check_default_partition_contents(Relation parent, Relation default_rel, PartitionBoundSpec *new_spec)
PartitionDesc RelationGetPartitionDesc(Relation rel, bool omit_detached)
Definition partdesc.c:71
Oid get_default_oid_from_partdesc(PartitionDesc partdesc)
Definition partdesc.c:501
NameData relname
Definition pg_class.h:40
#define PARTITION_MAX_KEYS
#define NAMEDATALEN
#define foreach_ptr(type, var, lst)
Definition pg_list.h:501
#define linitial_oid(l)
Definition pg_list.h:180
#define foreach_int(var, lst)
Definition pg_list.h:502
size_t strlcpy(char *dst, const char *src, size_t siz)
Definition strlcpy.c:45
@ ONCOMMIT_NOOP
Definition primnodes.h:59
bytea * view_reloptions(Datum reloptions, bool validate)
bytea * partitioned_table_reloptions(Datum reloptions, bool validate)
Datum transformRelOptions(Datum oldOptions, List *defList, const char *nameSpace, const char *const validnsps[], bool acceptOidsOff, bool isReset)
bytea * heap_reloptions(char relkind, Datum reloptions, bool validate)
#define HEAP_RELOPT_NAMESPACES
Definition reloptions.h:61
const char * p_sourcetext
Definition parse_node.h:214
TriggerDesc * trigdesc
Definition rel.h:117
char * default_table_access_method
Definition tableam.c:49
TupleDesc BuildDescForRelation(const List *columns)
Definition tablecmds.c:1429
static void ComputePartitionAttrs(ParseState *pstate, Relation rel, List *partParams, AttrNumber *partattrs, List **partexprs, Oid *partopclass, Oid *partcollation, PartitionStrategy strategy)
static void CloneRowTriggersToPartition(Relation parent, Relation partition)
static void StoreCatalogInheritance(Oid relationId, List *supers, bool child_is_partition)
Definition tablecmds.c:3578
static void CloneForeignKeyConstraints(List **wqueue, Relation parentRel, Relation partitionRel)
static PartitionSpec * transformPartitionSpec(Relation rel, PartitionSpec *partspec)
static void set_attnotnull(List **wqueue, Relation rel, AttrNumber attnum, bool is_valid, bool queue_validation)
Definition tablecmds.c:7955
static List * MergeAttributes(List *columns, const List *supers, char relpersistence, bool is_partition, List **supconstr, List **supnotnulls)
Definition tablecmds.c:2604
void CommandCounterIncrement(void)
Definition xact.c:1130

References AccessExclusiveLock, AccessShareLock, ACL_CREATE, ACL_USAGE, aclcheck_error(), aclcheck_error_type(), ACLCHECK_OK, addNSItemToQuery(), addRangeTableEntryForRelation(), AddRelationNewConstraints(), AddRelationNotNullConstraints(), allowSystemTableMods, Assert, attnum, build_attrmap_by_name(), BuildDescForRelation(), check_default_partition_contents(), check_new_partition_bound(), CloneForeignKeyConstraints(), CloneRowTriggersToPartition(), CommandCounterIncrement(), ComputePartitionAttrs(), CONSTR_DEFAULT, default_table_access_method, DefineIndex(), elog, ereport, errcode(), errdetail(), errmsg, ERROR, fb(), foreach_int, foreach_ptr, generateClonedIndexStmt(), get_default_oid_from_partdesc(), get_rel_name(), get_rel_relam(), get_rel_tablespace(), get_table_am_oid(), get_tablespace_name(), get_tablespace_oid(), GetDefaultTablespace(), GetUserId(), heap_create_with_catalog(), HEAP_RELOPT_NAMESPACES, heap_reloptions(), index_close(), index_open(), InSecurityRestrictedOperation(), InvalidOid, lappend(), lappend_oid(), lfirst, lfirst_oid, linitial_oid, list_concat(), list_free(), list_length(), list_member_oid(), make_parsestate(), MergeAttributes(), MyDatabaseTableSpace, NAMEDATALEN, NIL, NoLock, object_aclcheck(), OBJECT_TABLESPACE, ObjectAddressSet, OidIsValid, ONCOMMIT_NOOP, ParseState::p_sourcetext, palloc_object, PARTITION_MAX_KEYS, partitioned_table_reloptions(), RangeVarGetAndCheckCreationNamespace(), RangeVarGetRelid, RelationData::rd_rel, relation_close(), relation_open(), RelationGetDescr, RelationGetIndexList(), RelationGetPartitionDesc(), RelationGetRelationName, RelationGetRelid, relname, set_attnotnull(), ShareUpdateExclusiveLock, stmt, StoreCatalogInheritance(), StorePartitionBound(), StorePartitionKey(), strlcpy(), table_close(), table_open(), transformPartitionBound(), transformPartitionSpec(), transformRelOptions(), RelationData::trigdesc, TupleDescFinalize(), typenameTypeId(), and view_reloptions().

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

◆ ExecuteTruncate()

void ExecuteTruncate ( TruncateStmt stmt)
extern

Definition at line 1916 of file tablecmds.c.

1917{
1918 List *rels = NIL;
1919 List *relids = NIL;
1921 ListCell *cell;
1922
1923 /*
1924 * Open, exclusive-lock, and check all the explicitly-specified relations
1925 */
1926 foreach(cell, stmt->relations)
1927 {
1928 RangeVar *rv = lfirst(cell);
1929 Relation rel;
1930 bool recurse = rv->inh;
1931 Oid myrelid;
1932 LOCKMODE lockmode = AccessExclusiveLock;
1933
1934 myrelid = RangeVarGetRelidExtended(rv, lockmode,
1936 NULL);
1937
1938 /* don't throw error for "TRUNCATE foo, foo" */
1939 if (list_member_oid(relids, myrelid))
1940 continue;
1941
1942 /* open the relation, we already hold a lock on it */
1943 rel = table_open(myrelid, NoLock);
1944
1945 /*
1946 * RangeVarGetRelidExtended() has done most checks with its callback,
1947 * but other checks with the now-opened Relation remain.
1948 */
1950
1951 rels = lappend(rels, rel);
1952 relids = lappend_oid(relids, myrelid);
1953
1954 /* Log this relation only if needed for logical decoding */
1957
1958 if (recurse)
1959 {
1960 ListCell *child;
1961 List *children;
1962
1963 children = find_all_inheritors(myrelid, lockmode, NULL);
1964
1965 foreach(child, children)
1966 {
1967 Oid childrelid = lfirst_oid(child);
1968
1969 if (list_member_oid(relids, childrelid))
1970 continue;
1971
1972 /* find_all_inheritors already got lock */
1974
1975 /*
1976 * It is possible that the parent table has children that are
1977 * temp tables of other backends. We cannot safely access
1978 * such tables (because of buffering issues), and the best
1979 * thing to do is to silently ignore them. Note that this
1980 * check is the same as one of the checks done in
1981 * truncate_check_activity() called below, still it is kept
1982 * here for simplicity.
1983 */
1984 if (RELATION_IS_OTHER_TEMP(rel))
1985 {
1986 table_close(rel, lockmode);
1987 continue;
1988 }
1989
1990 /*
1991 * Inherited TRUNCATE commands perform access permission
1992 * checks on the parent table only. So we skip checking the
1993 * children's permissions and don't call
1994 * truncate_check_perms() here.
1995 */
1998
1999 rels = lappend(rels, rel);
2000 relids = lappend_oid(relids, childrelid);
2001
2002 /* Log this relation only if needed for logical decoding */
2005 }
2006 }
2007 else if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
2008 ereport(ERROR,
2010 errmsg("cannot truncate only a partitioned table"),
2011 errhint("Do not specify the ONLY keyword, or use TRUNCATE ONLY on the partitions directly.")));
2012 }
2013
2014 ExecuteTruncateGuts(rels, relids, relids_logged,
2015 stmt->behavior, stmt->restart_seqs, false);
2016
2017 /* And close the rels */
2018 foreach(cell, rels)
2019 {
2020 Relation rel = (Relation) lfirst(cell);
2021
2022 table_close(rel, NoLock);
2023 }
2024}
struct RelationData * Relation
Definition genam.h:30
List * find_all_inheritors(Oid parentrelId, LOCKMODE lockmode, List **numparents)
#define RelationIsLogicallyLogged(relation)
Definition rel.h:712
bool inh
Definition primnodes.h:87
static void truncate_check_activity(Relation rel)
Definition tablecmds.c:2496
static void truncate_check_rel(Oid relid, Form_pg_class reltuple)
Definition tablecmds.c:2427
static void RangeVarCallbackForTruncate(const RangeVar *relation, Oid relId, Oid oldRelId, void *arg)
void ExecuteTruncateGuts(List *explicit_rels, List *relids, List *relids_logged, DropBehavior behavior, bool restart_seqs, bool run_as_table_owner)
Definition tablecmds.c:2040

References AccessExclusiveLock, ereport, errcode(), errhint(), errmsg, ERROR, ExecuteTruncateGuts(), fb(), find_all_inheritors(), RangeVar::inh, lappend(), lappend_oid(), lfirst, lfirst_oid, list_member_oid(), NIL, NoLock, RangeVarCallbackForTruncate(), RangeVarGetRelidExtended(), RelationData::rd_rel, RELATION_IS_OTHER_TEMP, RelationGetRelid, RelationIsLogicallyLogged, stmt, table_close(), table_open(), truncate_check_activity(), and truncate_check_rel().

Referenced by standard_ProcessUtility().

◆ ExecuteTruncateGuts()

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

Definition at line 2040 of file tablecmds.c.

2045{
2046 List *rels;
2047 List *seq_relids = NIL;
2048 HTAB *ft_htab = NULL;
2049 EState *estate;
2051 ResultRelInfo *resultRelInfo;
2053 ListCell *cell;
2054 Oid *logrelids;
2055
2056 /*
2057 * Check the explicitly-specified relations.
2058 *
2059 * In CASCADE mode, suck in all referencing relations as well. This
2060 * requires multiple iterations to find indirectly-dependent relations. At
2061 * each phase, we need to exclusive-lock new rels before looking for their
2062 * dependencies, else we might miss something. Also, we check each rel as
2063 * soon as we open it, to avoid a faux pas such as holding lock for a long
2064 * time on a rel we have no permissions for.
2065 */
2066 rels = list_copy(explicit_rels);
2067 if (behavior == DROP_CASCADE)
2068 {
2069 for (;;)
2070 {
2071 List *newrelids;
2072
2074 if (newrelids == NIL)
2075 break; /* nothing else to add */
2076
2077 foreach(cell, newrelids)
2078 {
2079 Oid relid = lfirst_oid(cell);
2080 Relation rel;
2081
2082 rel = table_open(relid, AccessExclusiveLock);
2084 (errmsg("truncate cascades to table \"%s\"",
2086 truncate_check_rel(relid, rel->rd_rel);
2087 truncate_check_perms(relid, rel->rd_rel);
2089 rels = lappend(rels, rel);
2090 relids = lappend_oid(relids, relid);
2091
2092 /* Log this relation only if needed for logical decoding */
2095 }
2096 }
2097 }
2098
2099 /*
2100 * Check foreign key references. In CASCADE mode, this should be
2101 * unnecessary since we just pulled in all the references; but as a
2102 * cross-check, do it anyway if in an Assert-enabled build.
2103 */
2104#ifdef USE_ASSERT_CHECKING
2105 heap_truncate_check_FKs(rels, false);
2106#else
2107 if (behavior == DROP_RESTRICT)
2108 heap_truncate_check_FKs(rels, false);
2109#endif
2110
2111 /*
2112 * If we are asked to restart sequences, find all the sequences, lock them
2113 * (we need AccessExclusiveLock for ResetSequence), and check permissions.
2114 * We want to do this early since it's pointless to do all the truncation
2115 * work only to fail on sequence permissions.
2116 */
2117 if (restart_seqs)
2118 {
2119 foreach(cell, rels)
2120 {
2121 Relation rel = (Relation) lfirst(cell);
2124
2125 foreach(seqcell, seqlist)
2126 {
2129
2131
2132 /* This check must match AlterSequence! */
2136
2138
2140 }
2141 }
2142 }
2143
2144 /* Prepare to catch AFTER triggers. */
2146
2147 /*
2148 * To fire triggers, we'll need an EState as well as a ResultRelInfo for
2149 * each relation. We don't need to call ExecOpenIndices, though.
2150 *
2151 * We put the ResultRelInfos in the es_opened_result_relations list, even
2152 * though we don't have a range table and don't populate the
2153 * es_result_relations array. That's a bit bogus, but it's enough to make
2154 * ExecGetTriggerResultRel() find them.
2155 */
2156 estate = CreateExecutorState();
2158 palloc(list_length(rels) * sizeof(ResultRelInfo));
2159 resultRelInfo = resultRelInfos;
2160 foreach(cell, rels)
2161 {
2162 Relation rel = (Relation) lfirst(cell);
2163
2164 InitResultRelInfo(resultRelInfo,
2165 rel,
2166 0, /* dummy rangetable index */
2167 NULL,
2168 0);
2170 lappend(estate->es_opened_result_relations, resultRelInfo);
2171 resultRelInfo++;
2172 }
2173
2174 /*
2175 * Process all BEFORE STATEMENT TRUNCATE triggers before we begin
2176 * truncating (this is because one of them might throw an error). Also, if
2177 * we were to allow them to prevent statement execution, that would need
2178 * to be handled here.
2179 */
2180 resultRelInfo = resultRelInfos;
2181 foreach(cell, rels)
2182 {
2184
2186 SwitchToUntrustedUser(resultRelInfo->ri_RelationDesc->rd_rel->relowner,
2187 &ucxt);
2188 ExecBSTruncateTriggers(estate, resultRelInfo);
2191 resultRelInfo++;
2192 }
2193
2194 /*
2195 * OK, truncate each table.
2196 */
2198
2199 foreach(cell, rels)
2200 {
2201 Relation rel = (Relation) lfirst(cell);
2202
2203 /* Skip partitioned tables as there is nothing to do */
2204 if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
2205 continue;
2206
2207 /*
2208 * Build the lists of foreign tables belonging to each foreign server
2209 * and pass each list to the foreign data wrapper's callback function,
2210 * so that each server can truncate its all foreign tables in bulk.
2211 * Each list is saved as a single entry in a hash table that uses the
2212 * server OID as lookup key.
2213 */
2214 if (rel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
2215 {
2217 bool found;
2219
2220 /* First time through, initialize hashtable for foreign tables */
2221 if (!ft_htab)
2222 {
2223 HASHCTL hctl;
2224
2225 memset(&hctl, 0, sizeof(HASHCTL));
2226 hctl.keysize = sizeof(Oid);
2227 hctl.entrysize = sizeof(ForeignTruncateInfo);
2229
2230 ft_htab = hash_create("TRUNCATE for Foreign Tables",
2231 32, /* start small and extend */
2232 &hctl,
2234 }
2235
2236 /* Find or create cached entry for the foreign table */
2237 ft_info = hash_search(ft_htab, &serverid, HASH_ENTER, &found);
2238 if (!found)
2239 ft_info->rels = NIL;
2240
2241 /*
2242 * Save the foreign table in the entry of the server that the
2243 * foreign table belongs to.
2244 */
2245 ft_info->rels = lappend(ft_info->rels, rel);
2246 continue;
2247 }
2248
2249 /*
2250 * Normally, we need a transaction-safe truncation here. However, if
2251 * the table was either created in the current (sub)transaction or has
2252 * a new relfilenumber in the current (sub)transaction, then we can
2253 * just truncate it in-place, because a rollback would cause the whole
2254 * table or the current physical file to be thrown away anyway.
2255 */
2256 if (rel->rd_createSubid == mySubid ||
2258 {
2259 /* Immediate, non-rollbackable truncation is OK */
2261 }
2262 else
2263 {
2267
2268 /*
2269 * This effectively deletes all rows in the table, and may be done
2270 * in a serializable transaction. In that case we must record a
2271 * rw-conflict in to this transaction from each transaction
2272 * holding a predicate lock on the table.
2273 */
2275
2276 /*
2277 * Need the full transaction-safe pushups.
2278 *
2279 * Create a new empty storage file for the relation, and assign it
2280 * as the relfilenumber value. The old storage file is scheduled
2281 * for deletion at commit.
2282 */
2283 RelationSetNewRelfilenumber(rel, rel->rd_rel->relpersistence);
2284
2286
2287 /*
2288 * The same for the toast table, if any.
2289 */
2290 toast_relid = rel->rd_rel->reltoastrelid;
2292 {
2295
2297 toastrel->rd_rel->relpersistence);
2299 }
2300
2301 /*
2302 * Reconstruct the indexes to match, and we're done.
2303 */
2306 }
2307
2309 }
2310
2311 /* Now go through the hash table, and truncate foreign tables */
2312 if (ft_htab)
2313 {
2316
2318
2319 PG_TRY();
2320 {
2321 while ((ft_info = hash_seq_search(&seq)) != NULL)
2322 {
2323 FdwRoutine *routine = GetFdwRoutineByServerId(ft_info->serverid);
2324
2325 /* truncate_check_rel() has checked that already */
2326 Assert(routine->ExecForeignTruncate != NULL);
2327
2328 routine->ExecForeignTruncate(ft_info->rels,
2329 behavior,
2330 restart_seqs);
2331 }
2332 }
2333 PG_FINALLY();
2334 {
2336 }
2337 PG_END_TRY();
2338 }
2339
2340 /*
2341 * Restart owned sequences if we were asked to.
2342 */
2343 foreach(cell, seq_relids)
2344 {
2345 Oid seq_relid = lfirst_oid(cell);
2346
2348 }
2349
2350 /*
2351 * Write a WAL record to allow this set of actions to be logically
2352 * decoded.
2353 *
2354 * Assemble an array of relids so we can write a single WAL record for the
2355 * whole action.
2356 */
2357 if (relids_logged != NIL)
2358 {
2360 int i = 0;
2361
2362 /* should only get here if effective_wal_level is 'logical' */
2364
2366 foreach(cell, relids_logged)
2367 logrelids[i++] = lfirst_oid(cell);
2368
2369 xlrec.dbId = MyDatabaseId;
2370 xlrec.nrelids = list_length(relids_logged);
2371 xlrec.flags = 0;
2372 if (behavior == DROP_CASCADE)
2373 xlrec.flags |= XLH_TRUNCATE_CASCADE;
2374 if (restart_seqs)
2376
2380
2382
2384 }
2385
2386 /*
2387 * Process all AFTER STATEMENT TRUNCATE triggers.
2388 */
2389 resultRelInfo = resultRelInfos;
2390 foreach(cell, rels)
2391 {
2393
2395 SwitchToUntrustedUser(resultRelInfo->ri_RelationDesc->rd_rel->relowner,
2396 &ucxt);
2397 ExecASTruncateTriggers(estate, resultRelInfo);
2400 resultRelInfo++;
2401 }
2402
2403 /* Handle queued AFTER triggers */
2404 AfterTriggerEndQuery(estate);
2405
2406 /* We can clean up the EState now */
2407 FreeExecutorState(estate);
2408
2409 /*
2410 * Close any rels opened by CASCADE (can't do this while EState still
2411 * holds refs)
2412 */
2413 rels = list_difference_ptr(rels, explicit_rels);
2414 foreach(cell, rels)
2415 {
2416 Relation rel = (Relation) lfirst(cell);
2417
2418 table_close(rel, NoLock);
2419 }
2420}
uint32 SubTransactionId
Definition c.h:740
void ResetSequence(Oid seq_relid)
Definition sequence.c:255
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition dynahash.c:889
HTAB * hash_create(const char *tabname, int64 nelem, const HASHCTL *info, int flags)
Definition dynahash.c:360
void hash_destroy(HTAB *hashp)
Definition dynahash.c:802
void * hash_seq_search(HASH_SEQ_STATUS *status)
Definition dynahash.c:1352
void hash_seq_init(HASH_SEQ_STATUS *status, HTAB *hashp)
Definition dynahash.c:1317
#define PG_TRY(...)
Definition elog.h:374
#define PG_END_TRY(...)
Definition elog.h:399
#define PG_FINALLY(...)
Definition elog.h:391
void InitResultRelInfo(ResultRelInfo *resultRelInfo, Relation resultRelationDesc, Index resultRelationIndex, ResultRelInfo *partition_root_rri, int instrument_options)
Definition execMain.c:1271
void FreeExecutorState(EState *estate)
Definition execUtils.c:197
EState * CreateExecutorState(void)
Definition execUtils.c:90
FdwRoutine * GetFdwRoutineByServerId(Oid serverid)
Definition foreign.c:409
Oid GetForeignServerIdByRelId(Oid relid)
Definition foreign.c:387
Oid MyDatabaseId
Definition globals.c:96
List * heap_truncate_find_FKs(List *relationIds)
Definition heap.c:3785
void heap_truncate_check_FKs(List *relations, bool tempTables)
Definition heap.c:3690
void heap_truncate_one_rel(Relation rel)
Definition heap.c:3646
#define XLOG_HEAP_TRUNCATE
Definition heapam_xlog.h:36
#define XLH_TRUNCATE_RESTART_SEQS
#define SizeOfHeapTruncate
#define XLH_TRUNCATE_CASCADE
@ HASH_ENTER
Definition hsearch.h:109
#define HASH_CONTEXT
Definition hsearch.h:97
#define HASH_ELEM
Definition hsearch.h:90
#define HASH_BLOBS
Definition hsearch.h:92
bool reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, const ReindexParams *params)
Definition index.c:3969
#define REINDEX_REL_PROCESS_TOAST
Definition index.h:166
List * list_difference_ptr(const List *list1, const List *list2)
Definition list.c:1263
List * list_copy(const List *oldlist)
Definition list.c:1573
void * palloc(Size size)
Definition mcxt.c:1387
MemoryContext CurrentMemoryContext
Definition mcxt.c:160
@ DROP_CASCADE
@ DROP_RESTRICT
@ OBJECT_SEQUENCE
List * getOwnedSequences(Oid relid)
Definition pg_depend.c:1009
void pgstat_count_truncate(Relation rel)
void CheckTableForSerializableConflictIn(Relation relation)
Definition predicate.c:4348
void RelationSetNewRelfilenumber(Relation relation, char persistence)
Definition relcache.c:3765
List * es_opened_result_relations
Definition execnodes.h:724
ExecForeignTruncate_function ExecForeignTruncate
Definition fdwapi.h:268
Size keysize
Definition hsearch.h:69
Size entrysize
Definition hsearch.h:70
MemoryContext hcxt
Definition hsearch.h:81
SubTransactionId rd_newRelfilelocatorSubid
Definition rel.h:104
SubTransactionId rd_createSubid
Definition rel.h:103
Relation ri_RelationDesc
Definition execnodes.h:513
static void truncate_check_perms(Oid relid, Form_pg_class reltuple)
Definition tablecmds.c:2478
void ExecBSTruncateTriggers(EState *estate, ResultRelInfo *relinfo)
Definition trigger.c:3282
void ExecASTruncateTriggers(EState *estate, ResultRelInfo *relinfo)
Definition trigger.c:3329
void AfterTriggerEndQuery(EState *estate)
Definition trigger.c:5161
void AfterTriggerBeginQuery(void)
Definition trigger.c:5141
void SwitchToUntrustedUser(Oid userid, UserContext *context)
Definition usercontext.c:33
void RestoreUserContext(UserContext *context)
Definition usercontext.c:87
SubTransactionId GetCurrentSubTransactionId(void)
Definition xact.c:793
#define XLogLogicalInfoActive()
Definition xlog.h:137
#define XLOG_INCLUDE_ORIGIN
Definition xlog.h:166
XLogRecPtr XLogInsert(RmgrId rmid, uint8 info)
Definition xloginsert.c:482
void XLogRegisterData(const void *data, uint32 len)
Definition xloginsert.c:372
void XLogSetRecordFlags(uint8 flags)
Definition xloginsert.c:464
void XLogBeginInsert(void)
Definition xloginsert.c:153

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

Referenced by apply_handle_truncate(), and ExecuteTruncate().

◆ find_composite_type_dependencies()

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

Definition at line 7026 of file tablecmds.c.

7028{
7030 ScanKeyData key[2];
7033
7034 /* since this function recurses, it could be driven to stack overflow */
7036
7037 /*
7038 * We scan pg_depend to find those things that depend on the given type.
7039 * (We assume we can ignore refobjsubid for a type.)
7040 */
7042
7043 ScanKeyInit(&key[0],
7047 ScanKeyInit(&key[1],
7050 ObjectIdGetDatum(typeOid));
7051
7053 NULL, 2, key);
7054
7056 {
7058 Relation rel;
7061
7062 /* Check for directly dependent types */
7063 if (pg_depend->classid == TypeRelationId)
7064 {
7065 /*
7066 * This must be an array, domain, or range containing the given
7067 * type, so recursively check for uses of this type. Note that
7068 * any error message will mention the original type not the
7069 * container; this is intentional.
7070 */
7073 continue;
7074 }
7075
7076 /* Else, ignore dependees that aren't relations */
7077 if (pg_depend->classid != RelationRelationId)
7078 continue;
7079
7082
7083 /*
7084 * If objsubid identifies a specific column, refer to that in error
7085 * messages. Otherwise, search to see if there's a user column of the
7086 * type. (We assume system columns are never of interesting types.)
7087 * The search is needed because an index containing an expression
7088 * column of the target type will just be recorded as a whole-relation
7089 * dependency. If we do not find a column of the type, the dependency
7090 * must indicate that the type is transiently referenced in an index
7091 * expression but not stored on disk, which we assume is OK, just as
7092 * we do for references in views. (It could also be that the target
7093 * type is embedded in some container type that is stored in an index
7094 * column, but the previous recursion should catch such cases.)
7095 */
7096 if (pg_depend->objsubid > 0 && pg_depend->objsubid <= tupleDesc->natts)
7097 att = TupleDescAttr(tupleDesc, pg_depend->objsubid - 1);
7098 else
7099 {
7100 att = NULL;
7101 for (int attno = 1; attno <= tupleDesc->natts; attno++)
7102 {
7103 att = TupleDescAttr(tupleDesc, attno - 1);
7104 if (att->atttypid == typeOid && !att->attisdropped)
7105 break;
7106 att = NULL;
7107 }
7108 if (att == NULL)
7109 {
7110 /* No such column, so assume OK */
7112 continue;
7113 }
7114 }
7115
7116 /*
7117 * We definitely should reject if the relation has storage. If it's
7118 * partitioned, then perhaps we don't have to reject: if there are
7119 * partitions then we'll fail when we find one, else there is no
7120 * stored data to worry about. However, it's possible that the type
7121 * change would affect conclusions about whether the type is sortable
7122 * or hashable and thus (if it's a partitioning column) break the
7123 * partitioning rule. For now, reject for partitioned rels too.
7124 */
7125 if (RELKIND_HAS_STORAGE(rel->rd_rel->relkind) ||
7126 RELKIND_HAS_PARTITIONS(rel->rd_rel->relkind))
7127 {
7128 if (origTypeName)
7129 ereport(ERROR,
7131 errmsg("cannot alter type \"%s\" because column \"%s.%s\" uses it",
7134 NameStr(att->attname))));
7135 else if (origRelation->rd_rel->relkind == RELKIND_COMPOSITE_TYPE)
7136 ereport(ERROR,
7138 errmsg("cannot alter type \"%s\" because column \"%s.%s\" uses it",
7141 NameStr(att->attname))));
7142 else if (origRelation->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
7143 ereport(ERROR,
7145 errmsg("cannot alter foreign table \"%s\" because column \"%s.%s\" uses its row type",
7148 NameStr(att->attname))));
7149 else
7150 ereport(ERROR,
7152 errmsg("cannot alter table \"%s\" because column \"%s.%s\" uses its row type",
7155 NameStr(att->attname))));
7156 }
7157 else if (OidIsValid(rel->rd_rel->reltype))
7158 {
7159 /*
7160 * A view or composite type itself isn't a problem, but we must
7161 * recursively check for indirect dependencies via its rowtype.
7162 */
7165 }
7166
7168 }
7169
7171
7173}
void systable_endscan(SysScanDesc sysscan)
Definition genam.c:612
HeapTuple systable_getnext(SysScanDesc sysscan)
Definition genam.c:523
SysScanDesc systable_beginscan(Relation heapRelation, Oid indexId, bool indexOK, Snapshot snapshot, int nkeys, ScanKey key)
Definition genam.c:388
END_CATALOG_STRUCT typedef FormData_pg_depend * Form_pg_depend
Definition pg_depend.h:76
void check_stack_depth(void)
Definition stack_depth.c:95
void find_composite_type_dependencies(Oid typeOid, Relation origRelation, const char *origTypeName)
Definition tablecmds.c:7026

References AccessShareLock, BTEqualStrategyNumber, check_stack_depth(), ereport, errcode(), errmsg, ERROR, fb(), find_composite_type_dependencies(), Form_pg_depend, GETSTRUCT(), HeapTupleIsValid, NameStr, ObjectIdGetDatum(), OidIsValid, RelationData::rd_rel, relation_close(), relation_open(), RelationGetDescr, RelationGetRelationName, ScanKeyInit(), systable_beginscan(), systable_endscan(), systable_getnext(), table_open(), and TupleDescAttr().

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

◆ PartConstraintImpliedByRelConstraint()

bool PartConstraintImpliedByRelConstraint ( Relation  scanrel,
List partConstraint 
)
extern

Definition at line 20328 of file tablecmds.c.

20330{
20332 TupleConstr *constr = RelationGetDescr(scanrel)->constr;
20333 int i;
20334
20335 if (constr && constr->has_not_null)
20336 {
20337 int natts = scanrel->rd_att->natts;
20338
20339 for (i = 1; i <= natts; i++)
20340 {
20341 CompactAttribute *att = TupleDescCompactAttr(scanrel->rd_att, i - 1);
20342
20343 /* invalid not-null constraint must be ignored here */
20344 if (att->attnullability == ATTNULLABLE_VALID && !att->attisdropped)
20345 {
20348
20349 ntest->arg = (Expr *) makeVar(1,
20350 i,
20351 wholeatt->atttypid,
20352 wholeatt->atttypmod,
20353 wholeatt->attcollation,
20354 0);
20355 ntest->nulltesttype = IS_NOT_NULL;
20356
20357 /*
20358 * argisrow=false is correct even for a composite column,
20359 * because attnotnull does not represent a SQL-spec IS NOT
20360 * NULL test in such a case, just IS DISTINCT FROM NULL.
20361 */
20362 ntest->argisrow = false;
20363 ntest->location = -1;
20365 }
20366 }
20367 }
20368
20370}
Var * makeVar(int varno, AttrNumber varattno, Oid vartype, int32 vartypmod, Oid varcollid, Index varlevelsup)
Definition makefuncs.c:66
@ IS_NOT_NULL
Definition primnodes.h:1992
bool attisdropped
Definition tupdesc.h:78
char attnullability
Definition tupdesc.h:80
TupleDesc rd_att
Definition rel.h:112
bool has_not_null
Definition tupdesc.h:45
ParseLoc location
Definition primnodes.h:311
static bool ConstraintImpliedByRelConstraint(Relation scanrel, List *testConstraint, List *provenConstraint)
#define ATTNULLABLE_VALID
Definition tupdesc.h:86
static CompactAttribute * TupleDescCompactAttr(TupleDesc tupdesc, int i)
Definition tupdesc.h:195

References CompactAttribute::attisdropped, CompactAttribute::attnullability, ATTNULLABLE_VALID, ConstraintImpliedByRelConstraint(), fb(), TupleConstr::has_not_null, i, IS_NOT_NULL, lappend(), Var::location, makeNode, makeVar(), TupleDescData::natts, NIL, RelationData::rd_att, RelationGetDescr, TupleDescAttr(), and TupleDescCompactAttr().

Referenced by check_default_partition_contents(), and QueuePartitionConstraintValidation().

◆ PreCommit_on_commit_actions()

void PreCommit_on_commit_actions ( void  )
extern

Definition at line 19584 of file tablecmds.c.

19585{
19586 ListCell *l;
19589
19590 foreach(l, on_commits)
19591 {
19593
19594 /* Ignore entry if already dropped in this xact */
19595 if (oc->deleting_subid != InvalidSubTransactionId)
19596 continue;
19597
19598 switch (oc->oncommit)
19599 {
19600 case ONCOMMIT_NOOP:
19602 /* Do nothing (there shouldn't be such entries, actually) */
19603 break;
19605
19606 /*
19607 * If this transaction hasn't accessed any temporary
19608 * relations, we can skip truncating ON COMMIT DELETE ROWS
19609 * tables, as they must still be empty.
19610 */
19613 break;
19614 case ONCOMMIT_DROP:
19616 break;
19617 }
19618 }
19619
19620 /*
19621 * Truncate relations before dropping so that all dependencies between
19622 * relations are removed after they are worked on. Doing it like this
19623 * might be a waste as it is possible that a relation being truncated will
19624 * be dropped anyway due to its parent being dropped, but this makes the
19625 * code more robust because of not having to re-check that the relation
19626 * exists at truncation time.
19627 */
19628 if (oids_to_truncate != NIL)
19630
19631 if (oids_to_drop != NIL)
19632 {
19634
19635 foreach(l, oids_to_drop)
19636 {
19637 ObjectAddress object;
19638
19639 object.classId = RelationRelationId;
19640 object.objectId = lfirst_oid(l);
19641 object.objectSubId = 0;
19642
19644
19646 }
19647
19648 /*
19649 * Object deletion might involve toast table access (to clean up
19650 * toasted catalog entries), so ensure we have a valid snapshot.
19651 */
19653
19654 /*
19655 * Since this is an automatic drop, rather than one directly initiated
19656 * by the user, we pass the PERFORM_DELETION_INTERNAL flag.
19657 */
19660
19662
19663#ifdef USE_ASSERT_CHECKING
19664
19665 /*
19666 * Note that table deletion will call remove_on_commit_action, so the
19667 * entry should get marked as deleted.
19668 */
19669 foreach(l, on_commits)
19670 {
19672
19673 if (oc->oncommit != ONCOMMIT_DROP)
19674 continue;
19675
19676 Assert(oc->deleting_subid != InvalidSubTransactionId);
19677 }
19678#endif
19679 }
19680}
void performMultipleDeletions(const ObjectAddresses *objects, DropBehavior behavior, int flags)
Definition dependency.c:388
#define PERFORM_DELETION_QUIETLY
Definition dependency.h:94
#define PERFORM_DELETION_INTERNAL
Definition dependency.h:92
void heap_truncate(List *relids)
Definition heap.c:3605
@ ONCOMMIT_DELETE_ROWS
Definition primnodes.h:61
@ ONCOMMIT_PRESERVE_ROWS
Definition primnodes.h:60
@ ONCOMMIT_DROP
Definition primnodes.h:62
Snapshot GetTransactionSnapshot(void)
Definition snapmgr.c:272
void PushActiveSnapshot(Snapshot snapshot)
Definition snapmgr.c:682
void PopActiveSnapshot(void)
Definition snapmgr.c:775
int MyXactFlags
Definition xact.c:138
#define XACT_FLAGS_ACCESSEDTEMPNAMESPACE
Definition xact.h:103

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

Referenced by CommitTransaction(), and PrepareTransaction().

◆ RangeVarCallbackMaintainsTable()

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

Definition at line 19758 of file tablecmds.c.

19760{
19761 char relkind;
19763
19764 /* Nothing to do if the relation was not found. */
19765 if (!OidIsValid(relId))
19766 return;
19767
19768 /*
19769 * If the relation does exist, check whether it's an index. But note that
19770 * the relation might have been dropped between the time we did the name
19771 * lookup and now. In that case, there's nothing to do.
19772 */
19773 relkind = get_rel_relkind(relId);
19774 if (!relkind)
19775 return;
19776 if (relkind != RELKIND_RELATION && relkind != RELKIND_TOASTVALUE &&
19777 relkind != RELKIND_MATVIEW && relkind != RELKIND_PARTITIONED_TABLE)
19778 ereport(ERROR,
19780 errmsg("\"%s\" is not a table or materialized view", relation->relname)));
19781
19782 /* Check permissions */
19784 if (aclresult != ACLCHECK_OK)
19787 relation->relname);
19788}
AclResult pg_class_aclcheck(Oid table_oid, Oid roleid, AclMode mode)
Definition aclchk.c:4082
#define ACL_MAINTAIN
Definition parsenodes.h:90
char * relname
Definition primnodes.h:84

References ACL_MAINTAIN, aclcheck_error(), ACLCHECK_OK, ereport, errcode(), errmsg, ERROR, fb(), get_rel_relkind(), get_relkind_objtype(), GetUserId(), OidIsValid, pg_class_aclcheck(), and RangeVar::relname.

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

◆ RangeVarCallbackOwnsRelation()

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

Definition at line 19818 of file tablecmds.c.

19820{
19821 HeapTuple tuple;
19822
19823 /* Nothing to do if the relation was not found. */
19824 if (!OidIsValid(relId))
19825 return;
19826
19827 tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relId));
19828 if (!HeapTupleIsValid(tuple)) /* should not happen */
19829 elog(ERROR, "cache lookup failed for relation %u", relId);
19830
19833 relation->relname);
19834
19835 if (!allowSystemTableMods &&
19836 IsSystemClass(relId, (Form_pg_class) GETSTRUCT(tuple)))
19837 ereport(ERROR,
19839 errmsg("permission denied: \"%s\" is a system catalog",
19840 relation->relname)));
19841
19842 ReleaseSysCache(tuple);
19843}
bool IsSystemClass(Oid relid, Form_pg_class reltuple)
Definition catalog.c:86

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

Referenced by AlterPropGraph(), AlterSequence(), CreatePropGraph(), ProcessUtilitySlow(), transformPartitionCmdForMerge(), and transformPartitionCmdForSplit().

◆ register_on_commit_action()

void register_on_commit_action ( Oid  relid,
OnCommitAction  action 
)
extern

Definition at line 19525 of file tablecmds.c.

19526{
19529
19530 /*
19531 * We needn't bother registering the relation unless there is an ON COMMIT
19532 * action we need to take.
19533 */
19534 if (action == ONCOMMIT_NOOP || action == ONCOMMIT_PRESERVE_ROWS)
19535 return;
19536
19538
19540 oc->relid = relid;
19541 oc->oncommit = action;
19542 oc->creating_subid = GetCurrentSubTransactionId();
19543 oc->deleting_subid = InvalidSubTransactionId;
19544
19545 /*
19546 * We use lcons() here so that ON COMMIT actions are processed in reverse
19547 * order of registration. That might not be essential but it seems
19548 * reasonable.
19549 */
19551
19553}
List * lcons(void *datum, List *list)
Definition list.c:495
MemoryContext CacheMemoryContext
Definition mcxt.c:169
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition palloc.h:124

References CacheMemoryContext, fb(), GetCurrentSubTransactionId(), InvalidSubTransactionId, lcons(), MemoryContextSwitchTo(), on_commits, ONCOMMIT_NOOP, ONCOMMIT_PRESERVE_ROWS, and palloc_object.

Referenced by heap_create_with_catalog().

◆ remove_on_commit_action()

void remove_on_commit_action ( Oid  relid)
extern

Definition at line 19561 of file tablecmds.c.

19562{
19563 ListCell *l;
19564
19565 foreach(l, on_commits)
19566 {
19568
19569 if (oc->relid == relid)
19570 {
19572 break;
19573 }
19574 }
19575}
SubTransactionId deleting_subid
Definition tablecmds.c:132

References OnCommitItem::deleting_subid, fb(), GetCurrentSubTransactionId(), lfirst, and on_commits.

Referenced by heap_drop_with_catalog().

◆ RemoveRelations()

void RemoveRelations ( DropStmt drop)
extern

Definition at line 1589 of file tablecmds.c.

1590{
1591 ObjectAddresses *objects;
1592 char relkind;
1593 ListCell *cell;
1594 int flags = 0;
1595 LOCKMODE lockmode = AccessExclusiveLock;
1596
1597 /* DROP CONCURRENTLY uses a weaker lock, and has some restrictions */
1598 if (drop->concurrent)
1599 {
1600 /*
1601 * Note that for temporary relations this lock may get upgraded later
1602 * on, but as no other session can access a temporary relation, this
1603 * is actually fine.
1604 */
1605 lockmode = ShareUpdateExclusiveLock;
1606 Assert(drop->removeType == OBJECT_INDEX);
1607 if (list_length(drop->objects) != 1)
1608 ereport(ERROR,
1610 errmsg("DROP INDEX CONCURRENTLY does not support dropping multiple objects")));
1611 if (drop->behavior == DROP_CASCADE)
1612 ereport(ERROR,
1614 errmsg("DROP INDEX CONCURRENTLY does not support CASCADE")));
1615 }
1616
1617 /*
1618 * First we identify all the relations, then we delete them in a single
1619 * performMultipleDeletions() call. This is to avoid unwanted DROP
1620 * RESTRICT errors if one of the relations depends on another.
1621 */
1622
1623 /* Determine required relkind */
1624 switch (drop->removeType)
1625 {
1626 case OBJECT_TABLE:
1627 relkind = RELKIND_RELATION;
1628 break;
1629
1630 case OBJECT_INDEX:
1631 relkind = RELKIND_INDEX;
1632 break;
1633
1634 case OBJECT_SEQUENCE:
1635 relkind = RELKIND_SEQUENCE;
1636 break;
1637
1638 case OBJECT_VIEW:
1639 relkind = RELKIND_VIEW;
1640 break;
1641
1642 case OBJECT_MATVIEW:
1643 relkind = RELKIND_MATVIEW;
1644 break;
1645
1647 relkind = RELKIND_FOREIGN_TABLE;
1648 break;
1649
1650 case OBJECT_PROPGRAPH:
1651 relkind = RELKIND_PROPGRAPH;
1652 break;
1653
1654 default:
1655 elog(ERROR, "unrecognized drop object type: %d",
1656 (int) drop->removeType);
1657 relkind = 0; /* keep compiler quiet */
1658 break;
1659 }
1660
1661 /* Lock and validate each relation; build a list of object addresses */
1662 objects = new_object_addresses();
1663
1664 foreach(cell, drop->objects)
1665 {
1666 RangeVar *rel = makeRangeVarFromNameList((List *) lfirst(cell));
1667 Oid relOid;
1668 ObjectAddress obj;
1670
1671 /*
1672 * These next few steps are a great deal like relation_openrv, but we
1673 * don't bother building a relcache entry since we don't need it.
1674 *
1675 * Check for shared-cache-inval messages before trying to access the
1676 * relation. This is needed to cover the case where the name
1677 * identifies a rel that has been dropped and recreated since the
1678 * start of our transaction: if we don't flush the old syscache entry,
1679 * then we'll latch onto that entry and suffer an error later.
1680 */
1682
1683 /* Look up the appropriate relation using namespace search. */
1684 state.expected_relkind = relkind;
1685 state.heap_lockmode = drop->concurrent ?
1687 /* We must initialize these fields to show that no locks are held: */
1688 state.heapOid = InvalidOid;
1689 state.partParentOid = InvalidOid;
1690
1691 relOid = RangeVarGetRelidExtended(rel, lockmode, RVR_MISSING_OK,
1693 &state);
1694
1695 /* Not there? */
1696 if (!OidIsValid(relOid))
1697 {
1698 DropErrorMsgNonExistent(rel, relkind, drop->missing_ok);
1699 continue;
1700 }
1701
1702 /*
1703 * Decide if concurrent mode needs to be used here or not. The
1704 * callback retrieved the rel's persistence for us.
1705 */
1706 if (drop->concurrent &&
1707 state.actual_relpersistence != RELPERSISTENCE_TEMP)
1708 {
1709 Assert(list_length(drop->objects) == 1 &&
1710 drop->removeType == OBJECT_INDEX);
1712 }
1713
1714 /*
1715 * Concurrent index drop cannot be used with partitioned indexes,
1716 * either.
1717 */
1718 if ((flags & PERFORM_DELETION_CONCURRENTLY) != 0 &&
1719 state.actual_relkind == RELKIND_PARTITIONED_INDEX)
1720 ereport(ERROR,
1722 errmsg("cannot drop partitioned index \"%s\" concurrently",
1723 rel->relname)));
1724
1725 /*
1726 * If we're told to drop a partitioned index, we must acquire lock on
1727 * all the children of its parent partitioned table before proceeding.
1728 * Otherwise we'd try to lock the child index partitions before their
1729 * tables, leading to potential deadlock against other sessions that
1730 * will lock those objects in the other order.
1731 */
1732 if (state.actual_relkind == RELKIND_PARTITIONED_INDEX)
1733 (void) find_all_inheritors(state.heapOid,
1734 state.heap_lockmode,
1735 NULL);
1736
1737 /* OK, we're ready to delete this one */
1739 obj.objectId = relOid;
1740 obj.objectSubId = 0;
1741
1742 add_exact_object_address(&obj, objects);
1743 }
1744
1745 performMultipleDeletions(objects, drop->behavior, flags);
1746
1747 free_object_addresses(objects);
1748}
#define PERFORM_DELETION_CONCURRENTLY
Definition dependency.h:93
void AcceptInvalidationMessages(void)
Definition inval.c:930
RangeVar * makeRangeVarFromNameList(const List *names)
Definition namespace.c:3626
@ OBJECT_PROPGRAPH
@ OBJECT_FOREIGN_TABLE
@ OBJECT_VIEW
static void DropErrorMsgNonExistent(RangeVar *rel, char rightkind, bool missing_ok)
Definition tablecmds.c:1514
static void RangeVarCallbackForDropRelation(const RangeVar *rel, Oid relOid, Oid oldRelOid, void *arg)
Definition tablecmds.c:1757

References AcceptInvalidationMessages(), AccessExclusiveLock, add_exact_object_address(), Assert, ObjectAddress::classId, DROP_CASCADE, DropErrorMsgNonExistent(), elog, ereport, errcode(), errmsg, ERROR, fb(), find_all_inheritors(), free_object_addresses(), InvalidOid, lfirst, list_length(), makeRangeVarFromNameList(), new_object_addresses(), OBJECT_FOREIGN_TABLE, OBJECT_INDEX, OBJECT_MATVIEW, OBJECT_PROPGRAPH, OBJECT_SEQUENCE, OBJECT_TABLE, OBJECT_VIEW, ObjectAddress::objectId, ObjectAddress::objectSubId, OidIsValid, PERFORM_DELETION_CONCURRENTLY, performMultipleDeletions(), RangeVarCallbackForDropRelation(), RangeVarGetRelidExtended(), RangeVar::relname, RVR_MISSING_OK, and ShareUpdateExclusiveLock.

Referenced by ExecDropStmt().

◆ renameatt()

ObjectAddress renameatt ( RenameStmt stmt)
extern

Definition at line 4066 of file tablecmds.c.

4067{
4068 Oid relid;
4070 ObjectAddress address;
4071
4072 /* lock level taken here should match renameatt_internal */
4074 stmt->missing_ok ? RVR_MISSING_OK : 0,
4076 NULL);
4077
4078 if (!OidIsValid(relid))
4079 {
4081 (errmsg("relation \"%s\" does not exist, skipping",
4082 stmt->relation->relname)));
4083 return InvalidObjectAddress;
4084 }
4085
4086 attnum =
4087 renameatt_internal(relid,
4088 stmt->subname, /* old att name */
4089 stmt->newname, /* new att name */
4090 stmt->relation->inh, /* recursive? */
4091 false, /* recursing? */
4092 0, /* expected inhcount */
4093 stmt->behavior);
4094
4096
4097 return address;
4098}
#define ObjectAddressSubSet(addr, class_id, object_id, object_sub_id)
static AttrNumber renameatt_internal(Oid myrelid, const char *oldattname, const char *newattname, bool recurse, bool recursing, int expected_parents, DropBehavior behavior)
Definition tablecmds.c:3901
static void RangeVarCallbackForRenameAttribute(const RangeVar *rv, Oid relid, Oid oldrelid, void *arg)
Definition tablecmds.c:4046

References AccessExclusiveLock, attnum, ereport, errmsg, fb(), InvalidObjectAddress, NOTICE, ObjectAddressSubSet, OidIsValid, RangeVarCallbackForRenameAttribute(), RangeVarGetRelidExtended(), renameatt_internal(), RVR_MISSING_OK, and stmt.

Referenced by ExecRenameStmt().

◆ RenameConstraint()

ObjectAddress RenameConstraint ( RenameStmt stmt)
extern

Definition at line 4213 of file tablecmds.c.

4214{
4215 Oid relid = InvalidOid;
4216 Oid typid = InvalidOid;
4217
4218 if (stmt->renameType == OBJECT_DOMCONSTRAINT)
4219 {
4220 Relation rel;
4221 HeapTuple tup;
4222
4226 if (!HeapTupleIsValid(tup))
4227 elog(ERROR, "cache lookup failed for type %u", typid);
4230 table_close(rel, NoLock);
4231 }
4232 else
4233 {
4234 /* lock level taken here should match rename_constraint_internal */
4236 stmt->missing_ok ? RVR_MISSING_OK : 0,
4238 NULL);
4239 if (!OidIsValid(relid))
4240 {
4242 (errmsg("relation \"%s\" does not exist, skipping",
4243 stmt->relation->relname)));
4244 return InvalidObjectAddress;
4245 }
4246 }
4247
4248 return
4249 rename_constraint_internal(relid, typid,
4250 stmt->subname,
4251 stmt->newname,
4252 (stmt->relation &&
4253 stmt->relation->inh), /* recursive? */
4254 false, /* recursing? */
4255 0 /* expected inhcount */ );
4256}
TypeName * makeTypeNameFromNameList(List *names)
Definition makefuncs.c:531
#define castNode(_type_, nodeptr)
Definition nodes.h:182
@ OBJECT_DOMCONSTRAINT
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:4104
void checkDomainOwner(HeapTuple tup)
Definition typecmds.c:3529

References AccessExclusiveLock, castNode, checkDomainOwner(), elog, ereport, errmsg, ERROR, fb(), HeapTupleIsValid, InvalidObjectAddress, InvalidOid, makeTypeNameFromNameList(), NoLock, NOTICE, OBJECT_DOMCONSTRAINT, ObjectIdGetDatum(), OidIsValid, RangeVarCallbackForRenameAttribute(), RangeVarGetRelidExtended(), ReleaseSysCache(), rename_constraint_internal(), RowExclusiveLock, RVR_MISSING_OK, SearchSysCache1(), stmt, table_close(), table_open(), and typenameTypeId().

Referenced by ExecRenameStmt().

◆ RenameRelation()

ObjectAddress RenameRelation ( RenameStmt stmt)
extern

Definition at line 4263 of file tablecmds.c.

4264{
4265 bool is_index_stmt = stmt->renameType == OBJECT_INDEX;
4266 Oid relid;
4267 ObjectAddress address;
4268
4269 /*
4270 * Grab an exclusive lock on the target table, index, sequence, view,
4271 * materialized view, or foreign table, which we will NOT release until
4272 * end of transaction.
4273 *
4274 * Lock level used here should match RenameRelationInternal, to avoid lock
4275 * escalation. However, because ALTER INDEX can be used with any relation
4276 * type, we mustn't believe without verification.
4277 */
4278 for (;;)
4279 {
4280 LOCKMODE lockmode;
4281 char relkind;
4282 bool obj_is_index;
4283
4285
4286 relid = RangeVarGetRelidExtended(stmt->relation, lockmode,
4287 stmt->missing_ok ? RVR_MISSING_OK : 0,
4289 stmt);
4290
4291 if (!OidIsValid(relid))
4292 {
4294 (errmsg("relation \"%s\" does not exist, skipping",
4295 stmt->relation->relname)));
4296 return InvalidObjectAddress;
4297 }
4298
4299 /*
4300 * We allow mismatched statement and object types (e.g., ALTER INDEX
4301 * to rename a table), but we might've used the wrong lock level. If
4302 * that happens, retry with the correct lock level. We don't bother
4303 * if we already acquired AccessExclusiveLock with an index, however.
4304 */
4305 relkind = get_rel_relkind(relid);
4306 obj_is_index = (relkind == RELKIND_INDEX ||
4307 relkind == RELKIND_PARTITIONED_INDEX);
4309 break;
4310
4311 UnlockRelationOid(relid, lockmode);
4313 }
4314
4315 /* Do the work */
4316 RenameRelationInternal(relid, stmt->newname, false, is_index_stmt);
4317
4318 ObjectAddressSet(address, RelationRelationId, relid);
4319
4320 return address;
4321}
void UnlockRelationOid(Oid relid, LOCKMODE lockmode)
Definition lmgr.c:229
void RenameRelationInternal(Oid myrelid, const char *newrelname, bool is_internal, bool is_index)
Definition tablecmds.c:4327

References AccessExclusiveLock, ereport, errmsg, fb(), get_rel_relkind(), InvalidObjectAddress, NOTICE, OBJECT_INDEX, ObjectAddressSet, OidIsValid, RangeVarCallbackForAlterRelation(), RangeVarGetRelidExtended(), RenameRelationInternal(), RVR_MISSING_OK, ShareUpdateExclusiveLock, stmt, and UnlockRelationOid().

Referenced by ExecRenameStmt().

◆ RenameRelationInternal()

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

Definition at line 4327 of file tablecmds.c.

4328{
4330 Relation relrelation; /* for RELATION relation */
4335
4336 /*
4337 * Grab a lock on the target relation, which we will NOT release until end
4338 * of transaction. We need at least a self-exclusive lock so that
4339 * concurrent DDL doesn't overwrite the rename if they start updating
4340 * while still seeing the old version. The lock also guards against
4341 * triggering relcache reloads in concurrent sessions, which might not
4342 * handle this information changing under them. For indexes, we can use a
4343 * reduced lock level because RelationReloadIndexInfo() handles indexes
4344 * specially.
4345 */
4348
4349 /*
4350 * Find relation's pg_class tuple, and make sure newrelname isn't in use.
4351 */
4353
4355 if (!HeapTupleIsValid(reltup)) /* shouldn't happen */
4356 elog(ERROR, "cache lookup failed for relation %u", myrelid);
4357 otid = reltup->t_self;
4359
4361 ereport(ERROR,
4363 errmsg("relation \"%s\" already exists",
4364 newrelname)));
4365
4366 /*
4367 * RenameRelation is careful not to believe the caller's idea of the
4368 * relation kind being handled. We don't have to worry about this, but
4369 * let's not be totally oblivious to it. We can process an index as
4370 * not-an-index, but not the other way around.
4371 */
4372 Assert(!is_index ||
4373 is_index == (targetrelation->rd_rel->relkind == RELKIND_INDEX ||
4374 targetrelation->rd_rel->relkind == RELKIND_PARTITIONED_INDEX));
4375
4376 /*
4377 * Update pg_class tuple with new relname. (Scribbling on reltup is OK
4378 * because it's a copy...)
4379 */
4380 namestrcpy(&(relform->relname), newrelname);
4381
4384
4386 InvalidOid, is_internal);
4387
4390
4391 /*
4392 * Also rename the associated type, if any.
4393 */
4394 if (OidIsValid(targetrelation->rd_rel->reltype))
4395 RenameTypeInternal(targetrelation->rd_rel->reltype,
4397
4398 /*
4399 * Also rename the associated constraint, if any.
4400 */
4401 if (targetrelation->rd_rel->relkind == RELKIND_INDEX ||
4402 targetrelation->rd_rel->relkind == RELKIND_PARTITIONED_INDEX)
4403 {
4405
4408 }
4409
4410 /*
4411 * Close rel, but keep lock!
4412 */
4414}
void namestrcpy(Name name, const char *str)
Definition name.c:233
#define InvokeObjectPostAlterHookArg(classId, objectId, subId, auxiliaryId, is_internal)
void RenameConstraintById(Oid conId, const char *newname)
Oid get_index_constraint(Oid indexId)
Definition pg_depend.c:1061
void RenameTypeInternal(Oid typeOid, const char *newTypeName, Oid typeNamespace)
Definition pg_type.c:763

References AccessExclusiveLock, Assert, CatalogTupleUpdate(), elog, ereport, errcode(), errmsg, ERROR, fb(), get_index_constraint(), get_relname_relid(), GETSTRUCT(), heap_freetuple(), HeapTupleIsValid, InplaceUpdateTupleLock, InvalidOid, InvokeObjectPostAlterHookArg, namestrcpy(), NoLock, ObjectIdGetDatum(), OidIsValid, relation_close(), relation_open(), RelationGetNamespace, RenameConstraintById(), RenameTypeInternal(), RowExclusiveLock, SearchSysCacheLockedCopy1(), ShareUpdateExclusiveLock, table_close(), table_open(), and UnlockTuple().

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

◆ ResetRelRewrite()

void ResetRelRewrite ( Oid  myrelid)
extern

Definition at line 4420 of file tablecmds.c.

4421{
4422 Relation relrelation; /* for RELATION relation */
4425
4426 /*
4427 * Find relation's pg_class tuple.
4428 */
4430
4432 if (!HeapTupleIsValid(reltup)) /* shouldn't happen */
4433 elog(ERROR, "cache lookup failed for relation %u", myrelid);
4435
4436 /*
4437 * Update pg_class tuple.
4438 */
4439 relform->relrewrite = InvalidOid;
4440
4442
4445}
#define SearchSysCacheCopy1(cacheId, key1)
Definition syscache.h:91

References CatalogTupleUpdate(), elog, ERROR, fb(), GETSTRUCT(), heap_freetuple(), HeapTupleIsValid, InvalidOid, ObjectIdGetDatum(), RowExclusiveLock, SearchSysCacheCopy1, table_close(), and table_open().

Referenced by finish_heap_swap().

◆ SetRelationHasSubclass()

void SetRelationHasSubclass ( Oid  relationId,
bool  relhassubclass 
)
extern

Definition at line 3704 of file tablecmds.c.

3705{
3707 HeapTuple tuple;
3709
3711 ShareUpdateExclusiveLock, false) ||
3713 ShareRowExclusiveLock, true));
3714
3715 /*
3716 * Fetch a modifiable copy of the tuple, modify it, update pg_class.
3717 */
3720 if (!HeapTupleIsValid(tuple))
3721 elog(ERROR, "cache lookup failed for relation %u", relationId);
3723
3724 if (classtuple->relhassubclass != relhassubclass)
3725 {
3726 classtuple->relhassubclass = relhassubclass;
3728 }
3729 else
3730 {
3731 /* no need to change tuple, but force relcache rebuild anyway */
3733 }
3734
3735 heap_freetuple(tuple);
3737}
void CacheInvalidateRelcacheByTuple(HeapTuple classTuple)
Definition inval.c:1669
bool CheckRelationOidLockedByMe(Oid relid, LOCKMODE lockmode, bool orstronger)
Definition lmgr.c:351

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

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

◆ SetRelationTableSpace()

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

Definition at line 3807 of file tablecmds.c.

3810{
3812 HeapTuple tuple;
3814 Form_pg_class rd_rel;
3815 Oid reloid = RelationGetRelid(rel);
3816
3818
3819 /* Get a modifiable copy of the relation's pg_class row. */
3821
3823 if (!HeapTupleIsValid(tuple))
3824 elog(ERROR, "cache lookup failed for relation %u", reloid);
3825 otid = tuple->t_self;
3826 rd_rel = (Form_pg_class) GETSTRUCT(tuple);
3827
3828 /* Update the pg_class row. */
3829 rd_rel->reltablespace = (newTableSpaceId == MyDatabaseTableSpace) ?
3832 rd_rel->relfilenode = newRelFilenumber;
3835
3836 /*
3837 * Record dependency on tablespace. This is only required for relations
3838 * that have no physical storage.
3839 */
3840 if (!RELKIND_HAS_STORAGE(rel->rd_rel->relkind))
3842 rd_rel->reltablespace);
3843
3844 heap_freetuple(tuple);
3846}
void changeDependencyOnTablespace(Oid classId, Oid objectId, Oid newTablespaceId)
#define RelFileNumberIsValid(relnumber)
Definition relpath.h:27
bool CheckRelationTableSpaceMove(Relation rel, Oid newTableSpaceId)
Definition tablecmds.c:3750

References Assert, CatalogTupleUpdate(), changeDependencyOnTablespace(), CheckRelationTableSpaceMove(), elog, ERROR, fb(), GETSTRUCT(), heap_freetuple(), HeapTupleIsValid, InplaceUpdateTupleLock, InvalidOid, MyDatabaseTableSpace, ObjectIdGetDatum(), RelationData::rd_rel, RelationGetRelid, RelFileNumberIsValid, RowExclusiveLock, SearchSysCacheLockedCopy1(), HeapTupleData::t_self, table_close(), table_open(), and UnlockTuple().

Referenced by ATExecSetTableSpace(), ATExecSetTableSpaceNoStorage(), and reindex_index().