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/lock.h"
#include "utils/relcache.h"
Include dependency graph for tablecmds.h:
This graph shows which files directly or indirectly include this file:

Go to the source code of this file.

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

19292{
19296 bool already_done = false;
19297
19298 /* no rel lock for relkind=c so use LOCKTAG_TUPLE */
19301 elog(ERROR, "cache lookup failed for relation %u", relOid);
19303
19304 Assert(classForm->relnamespace == oldNspOid);
19305
19306 thisobj.classId = RelationRelationId;
19307 thisobj.objectId = relOid;
19308 thisobj.objectSubId = 0;
19309
19310 /*
19311 * If the object has already been moved, don't move it again. If it's
19312 * already in the right place, don't move it, but still fire the object
19313 * access hook.
19314 */
19316 if (!already_done && oldNspOid != newNspOid)
19317 {
19318 ItemPointerData otid = classTup->t_self;
19319
19320 /* check for duplicate name (more friendly than unique-index failure) */
19321 if (get_relname_relid(NameStr(classForm->relname),
19323 ereport(ERROR,
19325 errmsg("relation \"%s\" already exists in schema \"%s\"",
19326 NameStr(classForm->relname),
19328
19329 /* classTup is a copy, so OK to scribble on */
19330 classForm->relnamespace = newNspOid;
19331
19334
19335
19336 /* Update dependency on schema if caller said so */
19337 if (hasDependEntry &&
19339 relOid,
19341 oldNspOid,
19342 newNspOid) != 1)
19343 elog(ERROR, "could not change schema dependency for relation \"%s\"",
19344 NameStr(classForm->relname));
19345 }
19346 else
19348 if (!already_done)
19349 {
19351
19353 }
19354
19356}
#define NameStr(name)
Definition c.h:837
#define Assert(condition)
Definition c.h:945
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:874
#define ERROR
Definition elog.h:39
#define elog(elevel,...)
Definition elog.h:226
#define ereport(elevel,...)
Definition elog.h:150
void heap_freetuple(HeapTuple htup)
Definition heaptuple.c:1384
#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:3588
Oid get_relname_relid(const char *relname, Oid relnamespace)
Definition lsyscache.c:2105
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:399

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

4567{
4568 Relation rel;
4569
4570 /* Caller is required to provide an adequate lock. */
4571 rel = relation_open(context->relid, NoLock);
4572
4574
4575 ATController(stmt, rel, stmt->cmds, stmt->relation->inh, lockmode, context);
4576}
#define stmt
#define NoLock
Definition lockdefs.h:34
Relation relation_open(Oid relationId, LOCKMODE lockmode)
Definition relation.c:47
static void CheckAlterTableIsSafe(Relation rel)
Definition tablecmds.c:4480
static void ATController(AlterTableStmt *parsetree, Relation rel, List *cmds, bool recurse, LOCKMODE lockmode, AlterTableUtilityContext *context)
Definition tablecmds.c:4906

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

Referenced by ProcessUtilitySlow().

◆ AlterTableGetLockLevel()

LOCKMODE AlterTableGetLockLevel ( List cmds)
extern

Definition at line 4639 of file tablecmds.c.

4640{
4641 /*
4642 * This only works if we read catalog tables using MVCC snapshots.
4643 */
4644 ListCell *lcmd;
4646
4647 foreach(lcmd, cmds)
4648 {
4650 LOCKMODE cmd_lockmode = AccessExclusiveLock; /* default for compiler */
4651
4652 switch (cmd->subtype)
4653 {
4654 /*
4655 * These subcommands rewrite the heap, so require full locks.
4656 */
4657 case AT_AddColumn: /* may rewrite heap, in some cases and visible
4658 * to SELECT */
4659 case AT_SetAccessMethod: /* must rewrite heap */
4660 case AT_SetTableSpace: /* must rewrite heap */
4661 case AT_AlterColumnType: /* must rewrite heap */
4663 break;
4664
4665 /*
4666 * These subcommands may require addition of toast tables. If
4667 * we add a toast table to a table currently being scanned, we
4668 * might miss data added to the new toast table by concurrent
4669 * insert transactions.
4670 */
4671 case AT_SetStorage: /* may add toast tables, see
4672 * ATRewriteCatalogs() */
4674 break;
4675
4676 /*
4677 * Removing constraints can affect SELECTs that have been
4678 * optimized assuming the constraint holds true. See also
4679 * CloneFkReferenced.
4680 */
4681 case AT_DropConstraint: /* as DROP INDEX */
4682 case AT_DropNotNull: /* may change some SQL plans */
4684 break;
4685
4686 /*
4687 * Subcommands that may be visible to concurrent SELECTs
4688 */
4689 case AT_DropColumn: /* change visible to SELECT */
4690 case AT_AddColumnToView: /* CREATE VIEW */
4691 case AT_DropOids: /* used to equiv to DropColumn */
4692 case AT_EnableAlwaysRule: /* may change SELECT rules */
4693 case AT_EnableReplicaRule: /* may change SELECT rules */
4694 case AT_EnableRule: /* may change SELECT rules */
4695 case AT_DisableRule: /* may change SELECT rules */
4697 break;
4698
4699 /*
4700 * Changing owner may remove implicit SELECT privileges
4701 */
4702 case AT_ChangeOwner: /* change visible to SELECT */
4704 break;
4705
4706 /*
4707 * Changing foreign table options may affect optimization.
4708 */
4709 case AT_GenericOptions:
4712 break;
4713
4714 /*
4715 * These subcommands affect write operations only.
4716 */
4717 case AT_EnableTrig:
4720 case AT_EnableTrigAll:
4721 case AT_EnableTrigUser:
4722 case AT_DisableTrig:
4723 case AT_DisableTrigAll:
4724 case AT_DisableTrigUser:
4726 break;
4727
4728 /*
4729 * These subcommands affect write operations only. XXX
4730 * Theoretically, these could be ShareRowExclusiveLock.
4731 */
4732 case AT_ColumnDefault:
4734 case AT_AlterConstraint:
4735 case AT_AddIndex: /* from ADD CONSTRAINT */
4737 case AT_ReplicaIdentity:
4738 case AT_SetNotNull:
4743 case AT_AddIdentity:
4744 case AT_DropIdentity:
4745 case AT_SetIdentity:
4746 case AT_SetExpression:
4747 case AT_DropExpression:
4748 case AT_SetCompression:
4750 break;
4751
4752 case AT_AddConstraint:
4753 case AT_ReAddConstraint: /* becomes AT_AddConstraint */
4754 case AT_ReAddDomainConstraint: /* becomes AT_AddConstraint */
4755 if (IsA(cmd->def, Constraint))
4756 {
4757 Constraint *con = (Constraint *) cmd->def;
4758
4759 switch (con->contype)
4760 {
4761 case CONSTR_EXCLUSION:
4762 case CONSTR_PRIMARY:
4763 case CONSTR_UNIQUE:
4764
4765 /*
4766 * Cases essentially the same as CREATE INDEX. We
4767 * could reduce the lock strength to ShareLock if
4768 * we can work out how to allow concurrent catalog
4769 * updates. XXX Might be set down to
4770 * ShareRowExclusiveLock but requires further
4771 * analysis.
4772 */
4774 break;
4775 case CONSTR_FOREIGN:
4776
4777 /*
4778 * We add triggers to both tables when we add a
4779 * Foreign Key, so the lock level must be at least
4780 * as strong as CREATE TRIGGER.
4781 */
4783 break;
4784
4785 default:
4787 }
4788 }
4789 break;
4790
4791 /*
4792 * These subcommands affect inheritance behaviour. Queries
4793 * started before us will continue to see the old inheritance
4794 * behaviour, while queries started after we commit will see
4795 * new behaviour. No need to prevent reads or writes to the
4796 * subtable while we hook it up though. Changing the TupDesc
4797 * may be a problem, so keep highest lock.
4798 */
4799 case AT_AddInherit:
4800 case AT_DropInherit:
4802 break;
4803
4804 /*
4805 * These subcommands affect implicit row type conversion. They
4806 * have affects similar to CREATE/DROP CAST on queries. don't
4807 * provide for invalidating parse trees as a result of such
4808 * changes, so we keep these at AccessExclusiveLock.
4809 */
4810 case AT_AddOf:
4811 case AT_DropOf:
4813 break;
4814
4815 /*
4816 * Only used by CREATE OR REPLACE VIEW which must conflict
4817 * with an SELECTs currently using the view.
4818 */
4821 break;
4822
4823 /*
4824 * These subcommands affect general strategies for performance
4825 * and maintenance, though don't change the semantic results
4826 * from normal data reads and writes. Delaying an ALTER TABLE
4827 * behind currently active writes only delays the point where
4828 * the new strategy begins to take effect, so there is no
4829 * benefit in waiting. In this case the minimum restriction
4830 * applies: we don't currently allow concurrent catalog
4831 * updates.
4832 */
4833 case AT_SetStatistics: /* Uses MVCC in getTableAttrs() */
4834 case AT_ClusterOn: /* Uses MVCC in getIndexes() */
4835 case AT_DropCluster: /* Uses MVCC in getIndexes() */
4836 case AT_SetOptions: /* Uses MVCC in getTableAttrs() */
4837 case AT_ResetOptions: /* Uses MVCC in getTableAttrs() */
4839 break;
4840
4841 case AT_SetLogged:
4842 case AT_SetUnLogged:
4844 break;
4845
4846 case AT_ValidateConstraint: /* Uses MVCC in getConstraints() */
4848 break;
4849
4850 /*
4851 * Rel options are more complex than first appears. Options
4852 * are set here for tables, views and indexes; for historical
4853 * reasons these can all be used with ALTER TABLE, so we can't
4854 * decide between them using the basic grammar.
4855 */
4856 case AT_SetRelOptions: /* Uses MVCC in getIndexes() and
4857 * getTables() */
4858 case AT_ResetRelOptions: /* Uses MVCC in getIndexes() and
4859 * getTables() */
4861 break;
4862
4863 case AT_AttachPartition:
4865 break;
4866
4867 case AT_DetachPartition:
4868 if (((PartitionCmd *) cmd->def)->concurrent)
4870 else
4872 break;
4873
4876 break;
4877
4878 case AT_MergePartitions:
4879 case AT_SplitPartition:
4881 break;
4882
4883 default: /* oops */
4884 elog(ERROR, "unrecognized alter table type: %d",
4885 (int) cmd->subtype);
4886 break;
4887 }
4888
4889 /*
4890 * Take the greatest lockmode from any subcommand
4891 */
4892 if (cmd_lockmode > lockmode)
4893 lockmode = cmd_lockmode;
4894 }
4895
4896 return lockmode;
4897}
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 4594 of file tablecmds.c.

4595{
4596 Relation rel;
4597 LOCKMODE lockmode = AlterTableGetLockLevel(cmds);
4598
4599 rel = relation_open(relid, lockmode);
4600
4602
4603 ATController(NULL, rel, cmds, recurse, lockmode, NULL);
4604}
void EventTriggerAlterTableRelid(Oid objectId)
LOCKMODE AlterTableGetLockLevel(List *cmds)
Definition tablecmds.c:4639

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

Referenced by AlterTableMoveAll(), and DefineVirtualRelation().

◆ AlterTableLookupRelation()

Oid AlterTableLookupRelation ( AlterTableStmt stmt,
LOCKMODE  lockmode 
)
extern

Definition at line 4506 of file tablecmds.c.

4507{
4508 return RangeVarGetRelidExtended(stmt->relation, lockmode,
4509 stmt->missing_ok ? RVR_MISSING_OK : 0,
4511 stmt);
4512}
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 17228 of file tablecmds.c.

17229{
17230 List *relations = NIL;
17231 ListCell *l;
17232 ScanKeyData key[1];
17233 Relation rel;
17234 TableScanDesc scan;
17235 HeapTuple tuple;
17238 List *role_oids = roleSpecsToIds(stmt->roles);
17239
17240 /* Ensure we were not asked to move something we can't */
17241 if (stmt->objtype != OBJECT_TABLE && stmt->objtype != OBJECT_INDEX &&
17242 stmt->objtype != OBJECT_MATVIEW)
17243 ereport(ERROR,
17245 errmsg("only tables, indexes, and materialized views exist in tablespaces")));
17246
17247 /* Get the orig and new tablespace OIDs */
17248 orig_tablespaceoid = get_tablespace_oid(stmt->orig_tablespacename, false);
17249 new_tablespaceoid = get_tablespace_oid(stmt->new_tablespacename, false);
17250
17251 /* Can't move shared relations in to or out of pg_global */
17252 /* This is also checked by ATExecSetTableSpace, but nice to stop earlier */
17255 ereport(ERROR,
17257 errmsg("cannot move relations in to or out of pg_global tablespace")));
17258
17259 /*
17260 * Must have CREATE rights on the new tablespace, unless it is the
17261 * database default tablespace (which all users implicitly have CREATE
17262 * rights on).
17263 */
17265 {
17267
17269 ACL_CREATE);
17270 if (aclresult != ACLCHECK_OK)
17273 }
17274
17275 /*
17276 * Now that the checks are done, check if we should set either to
17277 * InvalidOid because it is our database's default tablespace.
17278 */
17281
17284
17285 /* no-op */
17287 return new_tablespaceoid;
17288
17289 /*
17290 * Walk the list of objects in the tablespace and move them. This will
17291 * only find objects in our database, of course.
17292 */
17293 ScanKeyInit(&key[0],
17297
17299 scan = table_beginscan_catalog(rel, 1, key);
17300 while ((tuple = heap_getnext(scan, ForwardScanDirection)) != NULL)
17301 {
17303 Oid relOid = relForm->oid;
17304
17305 /*
17306 * Do not move objects in pg_catalog as part of this, if an admin
17307 * really wishes to do so, they can issue the individual ALTER
17308 * commands directly.
17309 *
17310 * Also, explicitly avoid any shared tables, temp tables, or TOAST
17311 * (TOAST will be moved with the main table).
17312 */
17313 if (IsCatalogNamespace(relForm->relnamespace) ||
17314 relForm->relisshared ||
17315 isAnyTempNamespace(relForm->relnamespace) ||
17316 IsToastNamespace(relForm->relnamespace))
17317 continue;
17318
17319 /* Only move the object type requested */
17320 if ((stmt->objtype == OBJECT_TABLE &&
17321 relForm->relkind != RELKIND_RELATION &&
17322 relForm->relkind != RELKIND_PARTITIONED_TABLE) ||
17323 (stmt->objtype == OBJECT_INDEX &&
17324 relForm->relkind != RELKIND_INDEX &&
17325 relForm->relkind != RELKIND_PARTITIONED_INDEX) ||
17326 (stmt->objtype == OBJECT_MATVIEW &&
17327 relForm->relkind != RELKIND_MATVIEW))
17328 continue;
17329
17330 /* Check if we are only moving objects owned by certain roles */
17331 if (role_oids != NIL && !list_member_oid(role_oids, relForm->relowner))
17332 continue;
17333
17334 /*
17335 * Handle permissions-checking here since we are locking the tables
17336 * and also to avoid doing a bunch of work only to fail part-way. Note
17337 * that permissions will also be checked by AlterTableInternal().
17338 *
17339 * Caller must be considered an owner on the table to move it.
17340 */
17343 NameStr(relForm->relname));
17344
17345 if (stmt->nowait &&
17347 ereport(ERROR,
17349 errmsg("aborting because lock on relation \"%s.%s\" is not available",
17350 get_namespace_name(relForm->relnamespace),
17351 NameStr(relForm->relname))));
17352 else
17354
17355 /* Add to our list of objects to move */
17356 relations = lappend_oid(relations, relOid);
17357 }
17358
17359 table_endscan(scan);
17361
17362 if (relations == NIL)
17365 errmsg("no matching relations in tablespace \"%s\" found",
17366 orig_tablespaceoid == InvalidOid ? "(database default)" :
17368
17369 /* Everything is locked, loop through and move all of the relations. */
17370 foreach(l, relations)
17371 {
17372 List *cmds = NIL;
17374
17376 cmd->name = stmt->new_tablespacename;
17377
17378 cmds = lappend(cmds, cmd);
17379
17381 /* OID is set by AlterTableInternal */
17382 AlterTableInternal(lfirst_oid(l), cmds, false);
17384 }
17385
17386 return new_tablespaceoid;
17387}
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:860
bool IsToastNamespace(Oid namespaceId)
Definition catalog.c:261
bool IsCatalogNamespace(Oid namespaceId)
Definition catalog.c:243
#define NOTICE
Definition elog.h:35
void EventTriggerAlterTableStart(const Node *parsetree)
void EventTriggerAlterTableEnd(void)
Oid MyDatabaseTableSpace
Definition globals.c:96
HeapTuple heap_getnext(TableScanDesc sscan, ScanDirection direction)
Definition heapam.c:1420
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:2223
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:1004
void AlterTableInternal(Oid relid, List *cmds, bool recurse)
Definition tablecmds.c:4594
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 19180 of file tablecmds.c.

19181{
19182 Relation rel;
19183 Oid relid;
19184 Oid oldNspOid;
19185 Oid nspOid;
19186 RangeVar *newrv;
19189
19191 stmt->missing_ok ? RVR_MISSING_OK : 0,
19193 stmt);
19194
19195 if (!OidIsValid(relid))
19196 {
19198 (errmsg("relation \"%s\" does not exist, skipping",
19199 stmt->relation->relname)));
19200 return InvalidObjectAddress;
19201 }
19202
19203 rel = relation_open(relid, NoLock);
19204
19206
19207 /* If it's an owned sequence, disallow moving it by itself. */
19208 if (rel->rd_rel->relkind == RELKIND_SEQUENCE)
19209 {
19210 Oid tableId;
19211 int32 colId;
19212
19213 if (sequenceIsOwned(relid, DEPENDENCY_AUTO, &tableId, &colId) ||
19215 ereport(ERROR,
19217 errmsg("cannot move an owned sequence into another schema"),
19218 errdetail("Sequence \"%s\" is linked to table \"%s\".",
19221 }
19222
19223 /* Get and lock schema OID and check its permissions. */
19224 newrv = makeRangeVar(stmt->newschema, RelationGetRelationName(rel), -1);
19226
19227 /* common checks on switching namespaces */
19229
19233
19235
19236 if (oldschema)
19238
19239 /* close rel, but keep lock until commit */
19240 relation_close(rel, NoLock);
19241
19242 return myself;
19243}
int32_t int32
Definition c.h:614
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:2148
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:548
#define RelationGetNamespace(relation)
Definition rel.h:555
void relation_close(Relation relation, LOCKMODE lockmode)
Definition relation.c:205
Form_pg_class rd_rel
Definition rel.h:111
void AlterTableNamespaceInternal(Relation rel, Oid oldNspOid, Oid nspOid, ObjectAddresses *objsMoved)

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

19253{
19255
19256 Assert(objsMoved != NULL);
19257
19258 /* OK, modify the pg_class row and pg_depend entry */
19260
19262 nspOid, true, objsMoved);
19263
19264 /* Fix the table's row type too, if it has one */
19265 if (OidIsValid(rel->rd_rel->reltype))
19267 false, /* isImplicitArray */
19268 false, /* ignoreDependent */
19269 false, /* errorOnTableType */
19270 objsMoved);
19271
19272 /* Fix other dependent stuff */
19277 false, objsMoved);
19278
19280}
#define RowExclusiveLock
Definition lockdefs.h:38
void AlterConstraintNamespaces(Oid ownerId, Oid oldNspId, Oid newNspId, bool isType, ObjectAddresses *objsMoved)
#define RelationGetRelid(relation)
Definition rel.h:514
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:4197

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

19695{
19697
19698 foreach(cur_item, on_commits)
19699 {
19701
19702 if (!isCommit && oc->creating_subid == mySubid)
19703 {
19704 /* cur_item must be removed */
19706 pfree(oc);
19707 }
19708 else
19709 {
19710 /* cur_item must be preserved */
19711 if (oc->creating_subid == mySubid)
19712 oc->creating_subid = parentSubid;
19713 if (oc->deleting_subid == mySubid)
19714 oc->deleting_subid = isCommit ? parentSubid : InvalidSubTransactionId;
19715 }
19716 }
19717}
#define InvalidSubTransactionId
Definition c.h:744
void pfree(void *pointer)
Definition mcxt.c:1616
#define foreach_delete_current(lst, var_or_cell)
Definition pg_list.h:391
static List * on_commits
Definition tablecmds.c:133

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

19662{
19664
19665 foreach(cur_item, on_commits)
19666 {
19668
19669 if (isCommit ? oc->deleting_subid != InvalidSubTransactionId :
19670 oc->creating_subid != InvalidSubTransactionId)
19671 {
19672 /* cur_item must be removed */
19674 pfree(oc);
19675 }
19676 else
19677 {
19678 /* cur_item must be preserved */
19679 oc->creating_subid = InvalidSubTransactionId;
19680 oc->deleting_subid = InvalidSubTransactionId;
19681 }
19682 }
19683}

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

16315{
16318 HeapTuple tuple;
16320
16321 /*
16322 * Get exclusive lock till end of transaction on the target table. Use
16323 * relation_open so that we can work on indexes and sequences.
16324 */
16325 target_rel = relation_open(relationOid, lockmode);
16326
16327 /* Get its pg_class tuple, too */
16329
16330 tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relationOid));
16331 if (!HeapTupleIsValid(tuple))
16332 elog(ERROR, "cache lookup failed for relation %u", relationOid);
16334
16335 /* Can we change the ownership of this tuple? */
16336 switch (tuple_class->relkind)
16337 {
16338 case RELKIND_RELATION:
16339 case RELKIND_VIEW:
16340 case RELKIND_MATVIEW:
16343 case RELKIND_PROPGRAPH:
16344 /* ok to change owner */
16345 break;
16346 case RELKIND_INDEX:
16347 if (!recursing)
16348 {
16349 /*
16350 * Because ALTER INDEX OWNER used to be allowed, and in fact
16351 * is generated by old versions of pg_dump, we give a warning
16352 * and do nothing rather than erroring out. Also, to avoid
16353 * unnecessary chatter while restoring those old dumps, say
16354 * nothing at all if the command would be a no-op anyway.
16355 */
16356 if (tuple_class->relowner != newOwnerId)
16359 errmsg("cannot change owner of index \"%s\"",
16360 NameStr(tuple_class->relname)),
16361 errhint("Change the ownership of the index's table instead.")));
16362 /* quick hack to exit via the no-op path */
16363 newOwnerId = tuple_class->relowner;
16364 }
16365 break;
16367 if (recursing)
16368 break;
16369 ereport(ERROR,
16371 errmsg("cannot change owner of index \"%s\"",
16372 NameStr(tuple_class->relname)),
16373 errhint("Change the ownership of the index's table instead.")));
16374 break;
16375 case RELKIND_SEQUENCE:
16376 if (!recursing &&
16377 tuple_class->relowner != newOwnerId)
16378 {
16379 /* if it's an owned sequence, disallow changing it by itself */
16380 Oid tableId;
16381 int32 colId;
16382
16383 if (sequenceIsOwned(relationOid, DEPENDENCY_AUTO, &tableId, &colId) ||
16385 ereport(ERROR,
16387 errmsg("cannot change owner of sequence \"%s\"",
16388 NameStr(tuple_class->relname)),
16389 errdetail("Sequence \"%s\" is linked to table \"%s\".",
16390 NameStr(tuple_class->relname),
16392 }
16393 break;
16395 if (recursing)
16396 break;
16397 ereport(ERROR,
16399 errmsg("\"%s\" is a composite type",
16400 NameStr(tuple_class->relname)),
16401 /* translator: %s is an SQL ALTER command */
16402 errhint("Use %s instead.",
16403 "ALTER TYPE")));
16404 break;
16405 case RELKIND_TOASTVALUE:
16406 if (recursing)
16407 break;
16409 default:
16410 ereport(ERROR,
16412 errmsg("cannot change owner of relation \"%s\"",
16413 NameStr(tuple_class->relname)),
16415 }
16416
16417 /*
16418 * If the new owner is the same as the existing owner, consider the
16419 * command to have succeeded. This is for dump restoration purposes.
16420 */
16421 if (tuple_class->relowner != newOwnerId)
16422 {
16426 Acl *newAcl;
16428 bool isNull;
16429 HeapTuple newtuple;
16430
16431 /* skip permission checks when recursing to index or toast table */
16432 if (!recursing)
16433 {
16434 /* Superusers can always do it */
16435 if (!superuser())
16436 {
16437 Oid namespaceOid = tuple_class->relnamespace;
16439
16440 /* Otherwise, must be owner of the existing object */
16441 if (!object_ownercheck(RelationRelationId, relationOid, GetUserId()))
16444
16445 /* Must be able to become new owner */
16447
16448 /* New owner must have CREATE privilege on namespace */
16450 ACL_CREATE);
16451 if (aclresult != ACLCHECK_OK)
16454 }
16455 }
16456
16457 memset(repl_null, false, sizeof(repl_null));
16458 memset(repl_repl, false, sizeof(repl_repl));
16459
16462
16463 /*
16464 * Determine the modified ACL for the new owner. This is only
16465 * necessary when the ACL is non-null.
16466 */
16469 &isNull);
16470 if (!isNull)
16471 {
16473 tuple_class->relowner, newOwnerId);
16474 repl_repl[Anum_pg_class_relacl - 1] = true;
16476 }
16477
16479
16480 CatalogTupleUpdate(class_rel, &newtuple->t_self, newtuple);
16481
16482 heap_freetuple(newtuple);
16483
16484 /*
16485 * We must similarly update any per-column ACLs to reflect the new
16486 * owner; for neatness reasons that's split out as a subroutine.
16487 */
16488 change_owner_fix_column_acls(relationOid,
16489 tuple_class->relowner,
16490 newOwnerId);
16491
16492 /*
16493 * Update owner dependency reference, if any. A composite type has
16494 * none, because it's tracked for the pg_type entry instead of here;
16495 * indexes and TOAST tables don't have their own entries either.
16496 */
16497 if (tuple_class->relkind != RELKIND_COMPOSITE_TYPE &&
16498 tuple_class->relkind != RELKIND_INDEX &&
16500 tuple_class->relkind != RELKIND_TOASTVALUE)
16502 newOwnerId);
16503
16504 /*
16505 * Also change the ownership of the table's row type, if it has one
16506 */
16507 if (OidIsValid(tuple_class->reltype))
16509
16510 /*
16511 * If we are operating on a table or materialized view, also change
16512 * the ownership of any indexes and sequences that belong to the
16513 * relation, as well as its toast table (if it has one).
16514 */
16515 if (tuple_class->relkind == RELKIND_RELATION ||
16517 tuple_class->relkind == RELKIND_MATVIEW ||
16518 tuple_class->relkind == RELKIND_TOASTVALUE)
16519 {
16521 ListCell *i;
16522
16523 /* Find all the indexes belonging to this relation */
16525
16526 /* For each index, recursively change its ownership */
16527 foreach(i, index_oid_list)
16528 ATExecChangeOwner(lfirst_oid(i), newOwnerId, true, lockmode);
16529
16531 }
16532
16533 /* If it has a toast table, recurse to change its ownership */
16534 if (tuple_class->reltoastrelid != InvalidOid)
16536 true, lockmode);
16537
16538 /* If it has dependent sequences, recurse to change them too */
16539 change_owner_recurse_to_sequences(relationOid, newOwnerId, lockmode);
16540 }
16541
16543
16544 ReleaseSysCache(tuple);
16547}
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:152
int errhint(const char *fmt,...) pg_attribute_printf(1
#define WARNING
Definition elog.h:36
HeapTuple heap_modify_tuple(HeapTuple tuple, TupleDesc tupleDesc, const Datum *replValues, const bool *replIsnull, const bool *doReplace)
Definition heaptuple.c:1130
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)
static Datum PointerGetDatum(const void *X)
Definition postgres.h:342
uint64_t Datum
Definition postgres.h:70
#define RelationGetDescr(relation)
Definition rel.h:540
List * RelationGetIndexList(Relation relation)
Definition relcache.c:4826
ItemPointerData t_self
Definition htup.h:65
bool superuser(void)
Definition superuser.c:47
void ReleaseSysCache(HeapTuple tuple)
Definition syscache.c:264
HeapTuple SearchSysCache1(SysCacheIdentifier cacheId, Datum key1)
Definition syscache.c:220
Datum SysCacheGetAttr(SysCacheIdentifier cacheId, HeapTuple tup, AttrNumber attributeNumber, bool *isNull)
Definition syscache.c:595
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:4028

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

1404{
1405 int natts;
1407 ListCell *l;
1408 TupleDesc desc;
1409 char *attname;
1410 Oid atttypid;
1411 int32 atttypmod;
1412 Oid attcollation;
1413 int attdim;
1414
1415 /*
1416 * allocate a new tuple descriptor
1417 */
1418 natts = list_length(columns);
1419 desc = CreateTemplateTupleDesc(natts);
1420
1421 attnum = 0;
1422
1423 foreach(l, columns)
1424 {
1425 ColumnDef *entry = lfirst(l);
1428
1429 /*
1430 * for each entry in the list, get the name and type information from
1431 * the list and have TupleDescInitEntry fill in the attribute
1432 * information we need.
1433 */
1434 attnum++;
1435
1436 attname = entry->colname;
1437 typenameTypeIdAndMod(NULL, entry->typeName, &atttypid, &atttypmod);
1438
1440 if (aclresult != ACLCHECK_OK)
1442
1443 attcollation = GetColumnDefCollation(NULL, entry, atttypid);
1445 if (attdim > PG_INT16_MAX)
1446 ereport(ERROR,
1448 errmsg("too many array dimensions"));
1449
1450 if (entry->typeName->setof)
1451 ereport(ERROR,
1453 errmsg("column \"%s\" cannot be declared SETOF",
1454 attname)));
1455
1457 atttypid, atttypmod, attdim);
1458 att = TupleDescAttr(desc, attnum - 1);
1459
1460 /* Override TupleDescInitEntry's settings as requested */
1461 TupleDescInitEntryCollation(desc, attnum, attcollation);
1462
1463 /* Fill in additional stuff not handled by TupleDescInitEntry */
1464 att->attnotnull = entry->is_not_null;
1465 att->attislocal = entry->is_local;
1466 att->attinhcount = entry->inhcount;
1467 att->attidentity = entry->identity;
1468 att->attgenerated = entry->generated;
1469 att->attcompression = GetAttributeCompression(att->atttypid, entry->compression);
1470 if (entry->storage)
1471 att->attstorage = entry->storage;
1472 else if (entry->storage_name)
1473 att->attstorage = GetAttributeStorage(att->atttypid, entry->storage_name);
1474
1476 }
1477
1478 TupleDescFinalize(desc);
1479
1480 return desc;
1481}
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:672
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:772
char identity
Definition parsenodes.h:778
char * storage_name
Definition parsenodes.h:775
char * colname
Definition parsenodes.h:767
TypeName * typeName
Definition parsenodes.h:768
char generated
Definition parsenodes.h:781
char storage
Definition parsenodes.h:774
bool is_local
Definition parsenodes.h:771
int16 inhcount
Definition parsenodes.h:770
char * compression
Definition parsenodes.h:769
bool setof
Definition parsenodes.h:287
List * arrayBounds
Definition parsenodes.h:291
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:508
void populate_compact_attribute(TupleDesc tupdesc, int attnum)
Definition tupdesc.c:100
void TupleDescInitEntryCollation(TupleDesc desc, AttrNumber attributeNumber, Oid collationid)
Definition tupdesc.c:1081
void TupleDescInitEntry(TupleDesc desc, AttrNumber attributeNumber, const char *attributeName, Oid oidtypeid, int32 typmod, int attdim)
Definition tupdesc.c:897
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 7205 of file tablecmds.c.

7206{
7208 bool typeOk = false;
7209
7210 if (typ->typtype == TYPTYPE_COMPOSITE)
7211 {
7213
7214 Assert(OidIsValid(typ->typrelid));
7216 typeOk = (typeRelation->rd_rel->relkind == RELKIND_COMPOSITE_TYPE);
7217
7218 /*
7219 * Close the parent rel, but keep our AccessShareLock on it until xact
7220 * commit. That will prevent someone else from deleting or ALTERing
7221 * the type before the typed table creation/conversion commits.
7222 */
7224
7225 if (!typeOk)
7226 ereport(ERROR,
7228 errmsg("type %s is the row type of another table",
7229 format_type_be(typ->oid)),
7230 errdetail("A typed table must use a stand-alone composite type created with CREATE TYPE.")));
7231 }
7232 else
7233 ereport(ERROR,
7235 errmsg("type %s is not a composite type",
7236 format_type_be(typ->oid))));
7237}
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 3724 of file tablecmds.c.

3725{
3727
3728 /*
3729 * No work if no change in tablespace. Note that MyDatabaseTableSpace is
3730 * stored as 0.
3731 */
3732 oldTableSpaceId = rel->rd_rel->reltablespace;
3735 return false;
3736
3737 /*
3738 * We cannot support moving mapped relations into different tablespaces.
3739 * (In particular this eliminates all shared catalogs.)
3740 */
3741 if (RelationIsMapped(rel))
3742 ereport(ERROR,
3744 errmsg("cannot move system relation \"%s\"",
3746
3747 /* Cannot move a non-shared relation into pg_global */
3749 ereport(ERROR,
3751 errmsg("only shared relations can be placed in pg_global tablespace")));
3752
3753 /*
3754 * Do not allow moving temp tables of other backends ... their local
3755 * buffer manager is not going to cope.
3756 */
3757 if (RELATION_IS_OTHER_TEMP(rel))
3758 ereport(ERROR,
3760 errmsg("cannot move temporary tables of other sessions")));
3761
3762 return true;
3763}
#define RelationIsMapped(relation)
Definition rel.h:563
#define RELATION_IS_OTHER_TEMP(relation)
Definition rel.h:667

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

4448{
4449 int expected_refcnt;
4450
4451 expected_refcnt = rel->rd_isnailed ? 2 : 1;
4452 if (rel->rd_refcnt != expected_refcnt)
4453 ereport(ERROR,
4455 /* translator: first %s is a SQL command, eg ALTER TABLE */
4456 errmsg("cannot %s \"%s\" because it is being used by active queries in this session",
4458
4459 if (rel->rd_rel->relkind != RELKIND_INDEX &&
4460 rel->rd_rel->relkind != RELKIND_PARTITIONED_INDEX &&
4462 ereport(ERROR,
4464 /* translator: first %s is a SQL command, eg ALTER TABLE */
4465 errmsg("cannot %s \"%s\" because it has pending trigger events",
4467}
int rd_refcnt
Definition rel.h:59
bool rd_isnailed
Definition rel.h:62
bool AfterTriggerPendingOnRel(Oid relid)
Definition trigger.c:6083

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

786{
787 char relname[NAMEDATALEN];
791 Relation rel;
798 List *nncols;
799 List *connames = NIL;
800 Datum reloptions;
803 bool partitioned;
804 const char *const validnsps[] = HEAP_RELOPT_NAMESPACES;
806 ObjectAddress address;
809
810 /*
811 * Truncate relname to appropriate length (probably a waste of time, as
812 * parser should have done this already).
813 */
814 strlcpy(relname, stmt->relation->relname, NAMEDATALEN);
815
816 /*
817 * Check consistency of arguments
818 */
819 if (stmt->oncommit != ONCOMMIT_NOOP
820 && stmt->relation->relpersistence != RELPERSISTENCE_TEMP)
823 errmsg("ON COMMIT can only be used on temporary tables")));
824
825 if (stmt->partspec != NULL)
826 {
827 if (relkind != RELKIND_RELATION)
828 elog(ERROR, "unexpected relkind: %d", (int) relkind);
829
831 partitioned = true;
832 }
833 else
834 partitioned = false;
835
836 if (relkind == RELKIND_PARTITIONED_TABLE &&
837 stmt->relation->relpersistence == RELPERSISTENCE_UNLOGGED)
840 errmsg("partitioned tables cannot be unlogged")));
841
842 /*
843 * Look up the namespace in which we are supposed to create the relation,
844 * check we have permission to create there, lock it against concurrent
845 * drop, and mark stmt->relation as RELPERSISTENCE_TEMP if a temporary
846 * namespace is selected.
847 */
850
851 /*
852 * Security check: disallow creating temp tables from security-restricted
853 * code. This is needed because calling code might not expect untrusted
854 * tables to appear in pg_temp at the front of its search path.
855 */
856 if (stmt->relation->relpersistence == RELPERSISTENCE_TEMP
860 errmsg("cannot create temporary table within security-restricted operation")));
861
862 /*
863 * Determine the lockmode to use when scanning parents. A self-exclusive
864 * lock is needed here.
865 *
866 * For regular inheritance, if two backends attempt to add children to the
867 * same parent simultaneously, and that parent has no pre-existing
868 * children, then both will attempt to update the parent's relhassubclass
869 * field, leading to a "tuple concurrently updated" error. Also, this
870 * interlocks against a concurrent ANALYZE on the parent table, which
871 * might otherwise be attempting to clear the parent's relhassubclass
872 * field, if its previous children were recently dropped.
873 *
874 * If the child table is a partition, then we instead grab an exclusive
875 * lock on the parent because its partition descriptor will be changed by
876 * addition of the new partition.
877 */
878 parentLockmode = (stmt->partbound != NULL ? AccessExclusiveLock :
880
881 /* Determine the list of OIDs of the parents. */
883 foreach(listptr, stmt->inhRelations)
884 {
885 RangeVar *rv = (RangeVar *) lfirst(listptr);
887
889
890 /*
891 * Reject duplications in the list of parents.
892 */
896 errmsg("relation \"%s\" would be inherited from more than once",
898
900 }
901
902 /*
903 * Select tablespace to use: an explicitly indicated one, or (in the case
904 * of a partitioned table) the parent's, if it has one.
905 */
906 if (stmt->tablespacename)
907 {
908 tablespaceId = get_tablespace_oid(stmt->tablespacename, false);
909
913 errmsg("cannot specify default tablespace for partitioned relations")));
914 }
915 else if (stmt->partbound)
916 {
919 }
920 else
922
923 /* still nothing? use the default */
925 tablespaceId = GetDefaultTablespace(stmt->relation->relpersistence,
927
928 /* Check permissions except when using database's default */
930 {
932
934 ACL_CREATE);
935 if (aclresult != ACLCHECK_OK)
938 }
939
940 /* In all cases disallow placing user relations in pg_global */
944 errmsg("only shared relations can be placed in pg_global tablespace")));
945
946 /* Identify user ID that will own the table */
947 if (!OidIsValid(ownerId))
948 ownerId = GetUserId();
949
950 /*
951 * Parse and validate reloptions, if any.
952 */
953 reloptions = transformRelOptions((Datum) 0, stmt->options, NULL, validnsps,
954 true, false);
955
956 switch (relkind)
957 {
958 case RELKIND_VIEW:
959 (void) view_reloptions(reloptions, true);
960 break;
962 (void) partitioned_table_reloptions(reloptions, true);
963 break;
964 default:
965 (void) heap_reloptions(relkind, reloptions, true);
966 }
967
968 if (stmt->ofTypename)
969 {
971
972 ofTypeId = typenameTypeId(NULL, stmt->ofTypename);
973
975 if (aclresult != ACLCHECK_OK)
977 }
978 else
980
981 /*
982 * Look up inheritance ancestors and generate relation schema, including
983 * inherited attributes. (Note that stmt->tableElts is destructively
984 * modified by MergeAttributes.)
985 */
986 stmt->tableElts =
987 MergeAttributes(stmt->tableElts, inheritOids,
988 stmt->relation->relpersistence,
989 stmt->partbound != NULL,
991
992 /*
993 * Create a tuple descriptor from the relation schema. Note that this
994 * deals with column names, types, and in-descriptor NOT NULL flags, but
995 * not default values, NOT NULL or CHECK constraints; we handle those
996 * below.
997 */
999
1000 /*
1001 * Find columns with default values and prepare for insertion of the
1002 * defaults. Pre-cooked (that is, inherited) defaults go into a list of
1003 * CookedConstraint structs that we'll pass to heap_create_with_catalog,
1004 * while raw defaults go into a list of RawColumnDefault structs that will
1005 * be processed by AddRelationNewConstraints. (We can't deal with raw
1006 * expressions until we can do transformExpr.)
1007 */
1008 rawDefaults = NIL;
1010 attnum = 0;
1011
1012 foreach(listptr, stmt->tableElts)
1013 {
1015
1016 attnum++;
1017 if (colDef->raw_default != NULL)
1018 {
1020
1021 Assert(colDef->cooked_default == NULL);
1022
1024 rawEnt->attnum = attnum;
1025 rawEnt->raw_default = colDef->raw_default;
1026 rawEnt->generated = colDef->generated;
1028 }
1029 else if (colDef->cooked_default != NULL)
1030 {
1032
1034 cooked->contype = CONSTR_DEFAULT;
1035 cooked->conoid = InvalidOid; /* until created */
1036 cooked->name = NULL;
1037 cooked->attnum = attnum;
1038 cooked->expr = colDef->cooked_default;
1039 cooked->is_enforced = true;
1040 cooked->skip_validation = false;
1041 cooked->is_local = true; /* not used for defaults */
1042 cooked->inhcount = 0; /* ditto */
1043 cooked->is_no_inherit = false;
1045 }
1046 }
1047
1049
1050 /*
1051 * For relations with table AM and partitioned tables, select access
1052 * method to use: an explicitly indicated one, or (in the case of a
1053 * partitioned table) the parent's, if it has one.
1054 */
1055 if (stmt->accessMethod != NULL)
1056 {
1058 accessMethodId = get_table_am_oid(stmt->accessMethod, false);
1059 }
1060 else if (RELKIND_HAS_TABLE_AM(relkind) || relkind == RELKIND_PARTITIONED_TABLE)
1061 {
1062 if (stmt->partbound)
1063 {
1066 }
1067
1070 }
1071
1072 /*
1073 * Create the relation. Inherited defaults and CHECK constraints are
1074 * passed in for immediate handling --- since they don't need parsing,
1075 * they can be stored immediately.
1076 */
1080 InvalidOid,
1081 InvalidOid,
1082 ofTypeId,
1083 ownerId,
1085 descriptor,
1088 relkind,
1089 stmt->relation->relpersistence,
1090 false,
1091 false,
1092 stmt->oncommit,
1093 reloptions,
1094 true,
1096 false,
1097 InvalidOid,
1098 typaddress);
1099
1100 /*
1101 * We must bump the command counter to make the newly-created relation
1102 * tuple visible for opening.
1103 */
1105
1106 /*
1107 * Open the new relation and acquire exclusive lock on it. This isn't
1108 * really necessary for locking out other backends (since they can't see
1109 * the new rel anyway until we commit), but it keeps the lock manager from
1110 * complaining about deadlock risks.
1111 */
1113
1114 /*
1115 * Now add any newly specified column default and generation expressions
1116 * to the new relation. These are passed to us in the form of raw
1117 * parsetrees; we need to transform them to executable expression trees
1118 * before they can be added. The most convenient way to do that is to
1119 * apply the parser's transformExpr routine, but transformExpr doesn't
1120 * work unless we have a pre-existing relation. So, the transformation has
1121 * to be postponed to this final step of CREATE TABLE.
1122 *
1123 * This needs to be before processing the partitioning clauses because
1124 * those could refer to generated columns.
1125 */
1126 if (rawDefaults)
1128 true, true, false, queryString);
1129
1130 /*
1131 * Make column generation expressions visible for use by partitioning.
1132 */
1134
1135 /* Process and store partition bound, if any. */
1136 if (stmt->partbound)
1137 {
1138 PartitionBoundSpec *bound;
1139 ParseState *pstate;
1142 Relation parent,
1143 defaultRel = NULL;
1145
1146 /* Already have strong enough lock on the parent */
1147 parent = table_open(parentId, NoLock);
1148
1149 /*
1150 * We are going to try to validate the partition bound specification
1151 * against the partition key of parentRel, so it better have one.
1152 */
1153 if (parent->rd_rel->relkind != RELKIND_PARTITIONED_TABLE)
1154 ereport(ERROR,
1156 errmsg("\"%s\" is not partitioned",
1157 RelationGetRelationName(parent))));
1158
1159 /*
1160 * The partition constraint of the default partition depends on the
1161 * partition bounds of every other partition. It is possible that
1162 * another backend might be about to execute a query on the default
1163 * partition table, and that the query relies on previously cached
1164 * default partition constraints. We must therefore take a table lock
1165 * strong enough to prevent all queries on the default partition from
1166 * proceeding until we commit and send out a shared-cache-inval notice
1167 * that will make them update their index lists.
1168 *
1169 * Order of locking: The relation being added won't be visible to
1170 * other backends until it is committed, hence here in
1171 * DefineRelation() the order of locking the default partition and the
1172 * relation being added does not matter. But at all other places we
1173 * need to lock the default relation before we lock the relation being
1174 * added or removed i.e. we should take the lock in same order at all
1175 * the places such that lock parent, lock default partition and then
1176 * lock the partition so as to avoid a deadlock.
1177 */
1180 true));
1183
1184 /* Transform the bound values */
1185 pstate = make_parsestate(NULL);
1186 pstate->p_sourcetext = queryString;
1187
1188 /*
1189 * Add an nsitem containing this relation, so that transformExpr
1190 * called on partition bound expressions is able to report errors
1191 * using a proper context.
1192 */
1194 NULL, false, false);
1195 addNSItemToQuery(pstate, nsitem, false, true, true);
1196
1197 bound = transformPartitionBound(pstate, parent, stmt->partbound);
1198
1199 /*
1200 * Check first that the new partition's bound is valid and does not
1201 * overlap with any of existing partitions of the parent.
1202 */
1203 check_new_partition_bound(relname, parent, bound, pstate);
1204
1205 /*
1206 * If the default partition exists, its partition constraints will
1207 * change after the addition of this new partition such that it won't
1208 * allow any row that qualifies for this new partition. So, check that
1209 * the existing data in the default partition satisfies the constraint
1210 * as it will exist after adding this partition.
1211 */
1213 {
1215 /* Keep the lock until commit. */
1217 }
1218
1219 /* Update the pg_class entry. */
1220 StorePartitionBound(rel, parent, bound);
1221
1222 table_close(parent, NoLock);
1223 }
1224
1225 /* Store inheritance information for new rel. */
1227
1228 /*
1229 * Process the partitioning specification (if any) and store the partition
1230 * key information into the catalog.
1231 */
1232 if (partitioned)
1233 {
1234 ParseState *pstate;
1235 int partnatts;
1236 AttrNumber partattrs[PARTITION_MAX_KEYS];
1238 Oid partcollation[PARTITION_MAX_KEYS];
1239 List *partexprs = NIL;
1240
1241 pstate = make_parsestate(NULL);
1242 pstate->p_sourcetext = queryString;
1243
1244 partnatts = list_length(stmt->partspec->partParams);
1245
1246 /* Protect fixed-size arrays here and in executor */
1247 if (partnatts > PARTITION_MAX_KEYS)
1248 ereport(ERROR,
1250 errmsg("cannot partition using more than %d columns",
1252
1253 /*
1254 * We need to transform the raw parsetrees corresponding to partition
1255 * expressions into executable expression trees. Like column defaults
1256 * and CHECK constraints, we could not have done the transformation
1257 * earlier.
1258 */
1259 stmt->partspec = transformPartitionSpec(rel, stmt->partspec);
1260
1261 ComputePartitionAttrs(pstate, rel, stmt->partspec->partParams,
1262 partattrs, &partexprs, partopclass,
1263 partcollation, stmt->partspec->strategy);
1264
1265 StorePartitionKey(rel, stmt->partspec->strategy, partnatts, partattrs,
1266 partexprs,
1267 partopclass, partcollation);
1268
1269 /* make it all visible */
1271 }
1272
1273 /*
1274 * If we're creating a partition, create now all the indexes, triggers,
1275 * FKs defined in the parent.
1276 *
1277 * We can't do it earlier, because DefineIndex wants to know the partition
1278 * key which we just stored.
1279 */
1280 if (stmt->partbound)
1281 {
1283 Relation parent;
1284 List *idxlist;
1285 ListCell *cell;
1286
1287 /* Already have strong enough lock on the parent */
1288 parent = table_open(parentId, NoLock);
1289 idxlist = RelationGetIndexList(parent);
1290
1291 /*
1292 * For each index in the parent table, create one in the partition
1293 */
1294 foreach(cell, idxlist)
1295 {
1297 AttrMap *attmap;
1300
1301 if (rel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
1302 {
1303 if (idxRel->rd_index->indisunique)
1304 ereport(ERROR,
1306 errmsg("cannot create foreign partition of partitioned table \"%s\"",
1307 RelationGetRelationName(parent)),
1308 errdetail("Table \"%s\" contains indexes that are unique.",
1309 RelationGetRelationName(parent))));
1310 else
1311 {
1313 continue;
1314 }
1315 }
1316
1318 RelationGetDescr(parent),
1319 false);
1320 idxstmt =
1324 RelationGetRelid(rel),
1325 idxstmt,
1326 InvalidOid,
1329 -1,
1330 false, false, false, false, false);
1331
1333 }
1334
1336
1337 /*
1338 * If there are any row-level triggers, clone them to the new
1339 * partition.
1340 */
1341 if (parent->trigdesc != NULL)
1342 CloneRowTriggersToPartition(parent, rel);
1343
1344 /*
1345 * And foreign keys too. Note that because we're freshly creating the
1346 * table, there is no need to verify these new constraints.
1347 */
1348 CloneForeignKeyConstraints(NULL, parent, rel);
1349
1350 table_close(parent, NoLock);
1351 }
1352
1353 /*
1354 * Now add any newly specified CHECK constraints to the new relation. Same
1355 * as for defaults above, but these need to come after partitioning is set
1356 * up. We save the constraint names that were used, to avoid dupes below.
1357 */
1358 if (stmt->constraints)
1359 {
1360 List *conlist;
1361
1362 conlist = AddRelationNewConstraints(rel, NIL, stmt->constraints,
1363 true, true, false, queryString);
1365 {
1366 if (cons->name != NULL)
1367 connames = lappend(connames, cons->name);
1368 }
1369 }
1370
1371 /*
1372 * Finally, merge the not-null constraints that are declared directly with
1373 * those that come from parent relations (making sure to count inheritance
1374 * appropriately for each), create them, and set the attnotnull flag on
1375 * columns that don't yet have it.
1376 */
1377 nncols = AddRelationNotNullConstraints(rel, stmt->nnconstraints,
1379 foreach_int(attrnum, nncols)
1380 set_attnotnull(NULL, rel, attrnum, true, false);
1381
1383
1384 /*
1385 * Clean up. We keep lock on new relation (although it shouldn't be
1386 * visible to anyone else anyway, until commit).
1387 */
1388 relation_close(rel, NoLock);
1389
1390 return address;
1391}
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:130
void StorePartitionKey(Relation rel, char strategy, int16 partnatts, AttrNumber *partattrs, List *partexprs, Oid *partopclass, Oid *partcollation)
Definition heap.c:3897
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:1122
List * AddRelationNotNullConstraints(Relation rel, List *constraints, List *old_notnulls, List *existing_constraints)
Definition heap.c:2897
void StorePartitionBound(Relation rel, Relation parent, PartitionBoundSpec *bound)
Definition heap.c:4053
List * AddRelationNewConstraints(Relation rel, List *newColDefaults, List *newConstraints, bool allow_merge, bool is_local, bool is_internal, const char *queryString)
Definition heap.c:2385
void index_close(Relation relation, LOCKMODE lockmode)
Definition indexam.c:177
Relation index_open(Oid relationId, LOCKMODE lockmode)
Definition indexam.c:133
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:2320
Oid get_rel_tablespace(Oid relid)
Definition lsyscache.c:2274
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:469
#define linitial_oid(l)
Definition pg_list.h:180
#define foreach_int(var, lst)
Definition pg_list.h:470
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:62
const char * p_sourcetext
Definition parse_node.h:210
TriggerDesc * trigdesc
Definition rel.h:117
char * default_table_access_method
Definition tableam.c:49
TupleDesc BuildDescForRelation(const List *columns)
Definition tablecmds.c:1403
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:3552
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:7927
static List * MergeAttributes(List *columns, const List *supers, char relpersistence, bool is_partition, List **supconstr, List **supnotnulls)
Definition tablecmds.c:2578
void CommandCounterIncrement(void)
Definition xact.c:1102

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

1891{
1892 List *rels = NIL;
1893 List *relids = NIL;
1895 ListCell *cell;
1896
1897 /*
1898 * Open, exclusive-lock, and check all the explicitly-specified relations
1899 */
1900 foreach(cell, stmt->relations)
1901 {
1902 RangeVar *rv = lfirst(cell);
1903 Relation rel;
1904 bool recurse = rv->inh;
1905 Oid myrelid;
1906 LOCKMODE lockmode = AccessExclusiveLock;
1907
1908 myrelid = RangeVarGetRelidExtended(rv, lockmode,
1910 NULL);
1911
1912 /* don't throw error for "TRUNCATE foo, foo" */
1913 if (list_member_oid(relids, myrelid))
1914 continue;
1915
1916 /* open the relation, we already hold a lock on it */
1917 rel = table_open(myrelid, NoLock);
1918
1919 /*
1920 * RangeVarGetRelidExtended() has done most checks with its callback,
1921 * but other checks with the now-opened Relation remain.
1922 */
1924
1925 rels = lappend(rels, rel);
1926 relids = lappend_oid(relids, myrelid);
1927
1928 /* Log this relation only if needed for logical decoding */
1931
1932 if (recurse)
1933 {
1934 ListCell *child;
1935 List *children;
1936
1937 children = find_all_inheritors(myrelid, lockmode, NULL);
1938
1939 foreach(child, children)
1940 {
1941 Oid childrelid = lfirst_oid(child);
1942
1943 if (list_member_oid(relids, childrelid))
1944 continue;
1945
1946 /* find_all_inheritors already got lock */
1948
1949 /*
1950 * It is possible that the parent table has children that are
1951 * temp tables of other backends. We cannot safely access
1952 * such tables (because of buffering issues), and the best
1953 * thing to do is to silently ignore them. Note that this
1954 * check is the same as one of the checks done in
1955 * truncate_check_activity() called below, still it is kept
1956 * here for simplicity.
1957 */
1958 if (RELATION_IS_OTHER_TEMP(rel))
1959 {
1960 table_close(rel, lockmode);
1961 continue;
1962 }
1963
1964 /*
1965 * Inherited TRUNCATE commands perform access permission
1966 * checks on the parent table only. So we skip checking the
1967 * children's permissions and don't call
1968 * truncate_check_perms() here.
1969 */
1972
1973 rels = lappend(rels, rel);
1974 relids = lappend_oid(relids, childrelid);
1975
1976 /* Log this relation only if needed for logical decoding */
1979 }
1980 }
1981 else if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
1982 ereport(ERROR,
1984 errmsg("cannot truncate only a partitioned table"),
1985 errhint("Do not specify the ONLY keyword, or use TRUNCATE ONLY on the partitions directly.")));
1986 }
1987
1988 ExecuteTruncateGuts(rels, relids, relids_logged,
1989 stmt->behavior, stmt->restart_seqs, false);
1990
1991 /* And close the rels */
1992 foreach(cell, rels)
1993 {
1994 Relation rel = (Relation) lfirst(cell);
1995
1996 table_close(rel, NoLock);
1997 }
1998}
struct RelationData * Relation
Definition genam.h:30
List * find_all_inheritors(Oid parentrelId, LOCKMODE lockmode, List **numparents)
#define RelationIsLogicallyLogged(relation)
Definition rel.h:710
bool inh
Definition primnodes.h:87
static void truncate_check_activity(Relation rel)
Definition tablecmds.c:2470
static void truncate_check_rel(Oid relid, Form_pg_class reltuple)
Definition tablecmds.c:2401
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:2014

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

2019{
2020 List *rels;
2021 List *seq_relids = NIL;
2022 HTAB *ft_htab = NULL;
2023 EState *estate;
2025 ResultRelInfo *resultRelInfo;
2027 ListCell *cell;
2028 Oid *logrelids;
2029
2030 /*
2031 * Check the explicitly-specified relations.
2032 *
2033 * In CASCADE mode, suck in all referencing relations as well. This
2034 * requires multiple iterations to find indirectly-dependent relations. At
2035 * each phase, we need to exclusive-lock new rels before looking for their
2036 * dependencies, else we might miss something. Also, we check each rel as
2037 * soon as we open it, to avoid a faux pas such as holding lock for a long
2038 * time on a rel we have no permissions for.
2039 */
2040 rels = list_copy(explicit_rels);
2041 if (behavior == DROP_CASCADE)
2042 {
2043 for (;;)
2044 {
2045 List *newrelids;
2046
2048 if (newrelids == NIL)
2049 break; /* nothing else to add */
2050
2051 foreach(cell, newrelids)
2052 {
2053 Oid relid = lfirst_oid(cell);
2054 Relation rel;
2055
2056 rel = table_open(relid, AccessExclusiveLock);
2058 (errmsg("truncate cascades to table \"%s\"",
2060 truncate_check_rel(relid, rel->rd_rel);
2061 truncate_check_perms(relid, rel->rd_rel);
2063 rels = lappend(rels, rel);
2064 relids = lappend_oid(relids, relid);
2065
2066 /* Log this relation only if needed for logical decoding */
2069 }
2070 }
2071 }
2072
2073 /*
2074 * Check foreign key references. In CASCADE mode, this should be
2075 * unnecessary since we just pulled in all the references; but as a
2076 * cross-check, do it anyway if in an Assert-enabled build.
2077 */
2078#ifdef USE_ASSERT_CHECKING
2079 heap_truncate_check_FKs(rels, false);
2080#else
2081 if (behavior == DROP_RESTRICT)
2082 heap_truncate_check_FKs(rels, false);
2083#endif
2084
2085 /*
2086 * If we are asked to restart sequences, find all the sequences, lock them
2087 * (we need AccessExclusiveLock for ResetSequence), and check permissions.
2088 * We want to do this early since it's pointless to do all the truncation
2089 * work only to fail on sequence permissions.
2090 */
2091 if (restart_seqs)
2092 {
2093 foreach(cell, rels)
2094 {
2095 Relation rel = (Relation) lfirst(cell);
2098
2099 foreach(seqcell, seqlist)
2100 {
2103
2105
2106 /* This check must match AlterSequence! */
2110
2112
2114 }
2115 }
2116 }
2117
2118 /* Prepare to catch AFTER triggers. */
2120
2121 /*
2122 * To fire triggers, we'll need an EState as well as a ResultRelInfo for
2123 * each relation. We don't need to call ExecOpenIndices, though.
2124 *
2125 * We put the ResultRelInfos in the es_opened_result_relations list, even
2126 * though we don't have a range table and don't populate the
2127 * es_result_relations array. That's a bit bogus, but it's enough to make
2128 * ExecGetTriggerResultRel() find them.
2129 */
2130 estate = CreateExecutorState();
2132 palloc(list_length(rels) * sizeof(ResultRelInfo));
2133 resultRelInfo = resultRelInfos;
2134 foreach(cell, rels)
2135 {
2136 Relation rel = (Relation) lfirst(cell);
2137
2138 InitResultRelInfo(resultRelInfo,
2139 rel,
2140 0, /* dummy rangetable index */
2141 NULL,
2142 0);
2144 lappend(estate->es_opened_result_relations, resultRelInfo);
2145 resultRelInfo++;
2146 }
2147
2148 /*
2149 * Process all BEFORE STATEMENT TRUNCATE triggers before we begin
2150 * truncating (this is because one of them might throw an error). Also, if
2151 * we were to allow them to prevent statement execution, that would need
2152 * to be handled here.
2153 */
2154 resultRelInfo = resultRelInfos;
2155 foreach(cell, rels)
2156 {
2158
2160 SwitchToUntrustedUser(resultRelInfo->ri_RelationDesc->rd_rel->relowner,
2161 &ucxt);
2162 ExecBSTruncateTriggers(estate, resultRelInfo);
2165 resultRelInfo++;
2166 }
2167
2168 /*
2169 * OK, truncate each table.
2170 */
2172
2173 foreach(cell, rels)
2174 {
2175 Relation rel = (Relation) lfirst(cell);
2176
2177 /* Skip partitioned tables as there is nothing to do */
2178 if (rel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
2179 continue;
2180
2181 /*
2182 * Build the lists of foreign tables belonging to each foreign server
2183 * and pass each list to the foreign data wrapper's callback function,
2184 * so that each server can truncate its all foreign tables in bulk.
2185 * Each list is saved as a single entry in a hash table that uses the
2186 * server OID as lookup key.
2187 */
2188 if (rel->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
2189 {
2191 bool found;
2193
2194 /* First time through, initialize hashtable for foreign tables */
2195 if (!ft_htab)
2196 {
2197 HASHCTL hctl;
2198
2199 memset(&hctl, 0, sizeof(HASHCTL));
2200 hctl.keysize = sizeof(Oid);
2201 hctl.entrysize = sizeof(ForeignTruncateInfo);
2203
2204 ft_htab = hash_create("TRUNCATE for Foreign Tables",
2205 32, /* start small and extend */
2206 &hctl,
2208 }
2209
2210 /* Find or create cached entry for the foreign table */
2211 ft_info = hash_search(ft_htab, &serverid, HASH_ENTER, &found);
2212 if (!found)
2213 ft_info->rels = NIL;
2214
2215 /*
2216 * Save the foreign table in the entry of the server that the
2217 * foreign table belongs to.
2218 */
2219 ft_info->rels = lappend(ft_info->rels, rel);
2220 continue;
2221 }
2222
2223 /*
2224 * Normally, we need a transaction-safe truncation here. However, if
2225 * the table was either created in the current (sub)transaction or has
2226 * a new relfilenumber in the current (sub)transaction, then we can
2227 * just truncate it in-place, because a rollback would cause the whole
2228 * table or the current physical file to be thrown away anyway.
2229 */
2230 if (rel->rd_createSubid == mySubid ||
2232 {
2233 /* Immediate, non-rollbackable truncation is OK */
2235 }
2236 else
2237 {
2241
2242 /*
2243 * This effectively deletes all rows in the table, and may be done
2244 * in a serializable transaction. In that case we must record a
2245 * rw-conflict in to this transaction from each transaction
2246 * holding a predicate lock on the table.
2247 */
2249
2250 /*
2251 * Need the full transaction-safe pushups.
2252 *
2253 * Create a new empty storage file for the relation, and assign it
2254 * as the relfilenumber value. The old storage file is scheduled
2255 * for deletion at commit.
2256 */
2257 RelationSetNewRelfilenumber(rel, rel->rd_rel->relpersistence);
2258
2260
2261 /*
2262 * The same for the toast table, if any.
2263 */
2264 toast_relid = rel->rd_rel->reltoastrelid;
2266 {
2269
2271 toastrel->rd_rel->relpersistence);
2273 }
2274
2275 /*
2276 * Reconstruct the indexes to match, and we're done.
2277 */
2280 }
2281
2283 }
2284
2285 /* Now go through the hash table, and truncate foreign tables */
2286 if (ft_htab)
2287 {
2290
2292
2293 PG_TRY();
2294 {
2295 while ((ft_info = hash_seq_search(&seq)) != NULL)
2296 {
2297 FdwRoutine *routine = GetFdwRoutineByServerId(ft_info->serverid);
2298
2299 /* truncate_check_rel() has checked that already */
2300 Assert(routine->ExecForeignTruncate != NULL);
2301
2302 routine->ExecForeignTruncate(ft_info->rels,
2303 behavior,
2304 restart_seqs);
2305 }
2306 }
2307 PG_FINALLY();
2308 {
2310 }
2311 PG_END_TRY();
2312 }
2313
2314 /*
2315 * Restart owned sequences if we were asked to.
2316 */
2317 foreach(cell, seq_relids)
2318 {
2319 Oid seq_relid = lfirst_oid(cell);
2320
2322 }
2323
2324 /*
2325 * Write a WAL record to allow this set of actions to be logically
2326 * decoded.
2327 *
2328 * Assemble an array of relids so we can write a single WAL record for the
2329 * whole action.
2330 */
2331 if (relids_logged != NIL)
2332 {
2334 int i = 0;
2335
2336 /* should only get here if effective_wal_level is 'logical' */
2338
2340 foreach(cell, relids_logged)
2341 logrelids[i++] = lfirst_oid(cell);
2342
2343 xlrec.dbId = MyDatabaseId;
2344 xlrec.nrelids = list_length(relids_logged);
2345 xlrec.flags = 0;
2346 if (behavior == DROP_CASCADE)
2347 xlrec.flags |= XLH_TRUNCATE_CASCADE;
2348 if (restart_seqs)
2350
2354
2356
2358 }
2359
2360 /*
2361 * Process all AFTER STATEMENT TRUNCATE triggers.
2362 */
2363 resultRelInfo = resultRelInfos;
2364 foreach(cell, rels)
2365 {
2367
2369 SwitchToUntrustedUser(resultRelInfo->ri_RelationDesc->rd_rel->relowner,
2370 &ucxt);
2371 ExecASTruncateTriggers(estate, resultRelInfo);
2374 resultRelInfo++;
2375 }
2376
2377 /* Handle queued AFTER triggers */
2378 AfterTriggerEndQuery(estate);
2379
2380 /* We can clean up the EState now */
2381 FreeExecutorState(estate);
2382
2383 /*
2384 * Close any rels opened by CASCADE (can't do this while EState still
2385 * holds refs)
2386 */
2387 rels = list_difference_ptr(rels, explicit_rels);
2388 foreach(cell, rels)
2389 {
2390 Relation rel = (Relation) lfirst(cell);
2391
2392 table_close(rel, NoLock);
2393 }
2394}
uint32 SubTransactionId
Definition c.h:742
void ResetSequence(Oid seq_relid)
Definition sequence.c:255
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition dynahash.c:952
HTAB * hash_create(const char *tabname, int64 nelem, const HASHCTL *info, int flags)
Definition dynahash.c:358
void hash_destroy(HTAB *hashp)
Definition dynahash.c:865
void * hash_seq_search(HASH_SEQ_STATUS *status)
Definition dynahash.c:1415
void hash_seq_init(HASH_SEQ_STATUS *status, HTAB *hashp)
Definition dynahash.c:1380
#define PG_TRY(...)
Definition elog.h:372
#define PG_END_TRY(...)
Definition elog.h:397
#define PG_FINALLY(...)
Definition elog.h:389
void InitResultRelInfo(ResultRelInfo *resultRelInfo, Relation resultRelationDesc, Index resultRelationIndex, ResultRelInfo *partition_root_rri, int instrument_options)
Definition execMain.c:1262
void FreeExecutorState(EState *estate)
Definition execUtils.c:197
EState * CreateExecutorState(void)
Definition execUtils.c:90
FdwRoutine * GetFdwRoutineByServerId(Oid serverid)
Definition foreign.c:466
Oid GetForeignServerIdByRelId(Oid relid)
Definition foreign.c:444
Oid MyDatabaseId
Definition globals.c:94
List * heap_truncate_find_FKs(List *relationIds)
Definition heap.c:3770
void heap_truncate_check_FKs(List *relations, bool tempTables)
Definition heap.c:3675
void heap_truncate_one_rel(Relation rel)
Definition heap.c:3631
#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:114
#define HASH_CONTEXT
Definition hsearch.h:102
#define HASH_ELEM
Definition hsearch.h:95
#define HASH_BLOBS
Definition hsearch.h:97
bool reindex_relation(const ReindexStmt *stmt, Oid relid, int flags, const ReindexParams *params)
Definition index.c:3949
#define REINDEX_REL_PROCESS_TOAST
Definition index.h:165
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:4428
void RelationSetNewRelfilenumber(Relation relation, char persistence)
Definition relcache.c:3764
List * es_opened_result_relations
Definition execnodes.h:700
ExecForeignTruncate_function ExecForeignTruncate
Definition fdwapi.h:263
Size keysize
Definition hsearch.h:75
Size entrysize
Definition hsearch.h:76
MemoryContext hcxt
Definition hsearch.h:86
SubTransactionId rd_newRelfilelocatorSubid
Definition rel.h:104
SubTransactionId rd_createSubid
Definition rel.h:103
Relation ri_RelationDesc
Definition execnodes.h:492
static void truncate_check_perms(Oid relid, Form_pg_class reltuple)
Definition tablecmds.c:2452
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:5137
void AfterTriggerBeginQuery(void)
Definition trigger.c:5117
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:136
#define XLOG_INCLUDE_ORIGIN
Definition xlog.h:165
XLogRecPtr XLogInsert(RmgrId rmid, uint8 info)
Definition xloginsert.c:479
void XLogRegisterData(const void *data, uint32 len)
Definition xloginsert.c:369
void XLogSetRecordFlags(uint8 flags)
Definition xloginsert.c:461
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 6998 of file tablecmds.c.

7000{
7002 ScanKeyData key[2];
7005
7006 /* since this function recurses, it could be driven to stack overflow */
7008
7009 /*
7010 * We scan pg_depend to find those things that depend on the given type.
7011 * (We assume we can ignore refobjsubid for a type.)
7012 */
7014
7015 ScanKeyInit(&key[0],
7019 ScanKeyInit(&key[1],
7022 ObjectIdGetDatum(typeOid));
7023
7025 NULL, 2, key);
7026
7028 {
7030 Relation rel;
7033
7034 /* Check for directly dependent types */
7035 if (pg_depend->classid == TypeRelationId)
7036 {
7037 /*
7038 * This must be an array, domain, or range containing the given
7039 * type, so recursively check for uses of this type. Note that
7040 * any error message will mention the original type not the
7041 * container; this is intentional.
7042 */
7045 continue;
7046 }
7047
7048 /* Else, ignore dependees that aren't relations */
7049 if (pg_depend->classid != RelationRelationId)
7050 continue;
7051
7054
7055 /*
7056 * If objsubid identifies a specific column, refer to that in error
7057 * messages. Otherwise, search to see if there's a user column of the
7058 * type. (We assume system columns are never of interesting types.)
7059 * The search is needed because an index containing an expression
7060 * column of the target type will just be recorded as a whole-relation
7061 * dependency. If we do not find a column of the type, the dependency
7062 * must indicate that the type is transiently referenced in an index
7063 * expression but not stored on disk, which we assume is OK, just as
7064 * we do for references in views. (It could also be that the target
7065 * type is embedded in some container type that is stored in an index
7066 * column, but the previous recursion should catch such cases.)
7067 */
7068 if (pg_depend->objsubid > 0 && pg_depend->objsubid <= tupleDesc->natts)
7069 att = TupleDescAttr(tupleDesc, pg_depend->objsubid - 1);
7070 else
7071 {
7072 att = NULL;
7073 for (int attno = 1; attno <= tupleDesc->natts; attno++)
7074 {
7075 att = TupleDescAttr(tupleDesc, attno - 1);
7076 if (att->atttypid == typeOid && !att->attisdropped)
7077 break;
7078 att = NULL;
7079 }
7080 if (att == NULL)
7081 {
7082 /* No such column, so assume OK */
7084 continue;
7085 }
7086 }
7087
7088 /*
7089 * We definitely should reject if the relation has storage. If it's
7090 * partitioned, then perhaps we don't have to reject: if there are
7091 * partitions then we'll fail when we find one, else there is no
7092 * stored data to worry about. However, it's possible that the type
7093 * change would affect conclusions about whether the type is sortable
7094 * or hashable and thus (if it's a partitioning column) break the
7095 * partitioning rule. For now, reject for partitioned rels too.
7096 */
7097 if (RELKIND_HAS_STORAGE(rel->rd_rel->relkind) ||
7098 RELKIND_HAS_PARTITIONS(rel->rd_rel->relkind))
7099 {
7100 if (origTypeName)
7101 ereport(ERROR,
7103 errmsg("cannot alter type \"%s\" because column \"%s.%s\" uses it",
7106 NameStr(att->attname))));
7107 else if (origRelation->rd_rel->relkind == RELKIND_COMPOSITE_TYPE)
7108 ereport(ERROR,
7110 errmsg("cannot alter type \"%s\" because column \"%s.%s\" uses it",
7113 NameStr(att->attname))));
7114 else if (origRelation->rd_rel->relkind == RELKIND_FOREIGN_TABLE)
7115 ereport(ERROR,
7117 errmsg("cannot alter foreign table \"%s\" because column \"%s.%s\" uses its row type",
7120 NameStr(att->attname))));
7121 else
7122 ereport(ERROR,
7124 errmsg("cannot alter table \"%s\" because column \"%s.%s\" uses its row type",
7127 NameStr(att->attname))));
7128 }
7129 else if (OidIsValid(rel->rd_rel->reltype))
7130 {
7131 /*
7132 * A view or composite type itself isn't a problem, but we must
7133 * recursively check for indirect dependencies via its rowtype.
7134 */
7137 }
7138
7140 }
7141
7143
7145}
void systable_endscan(SysScanDesc sysscan)
Definition genam.c:603
HeapTuple systable_getnext(SysScanDesc sysscan)
Definition genam.c:514
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:6998

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

20300{
20302 TupleConstr *constr = RelationGetDescr(scanrel)->constr;
20303 int i;
20304
20305 if (constr && constr->has_not_null)
20306 {
20307 int natts = scanrel->rd_att->natts;
20308
20309 for (i = 1; i <= natts; i++)
20310 {
20312
20313 /* invalid not-null constraint must be ignored here */
20314 if (att->attnullability == ATTNULLABLE_VALID && !att->attisdropped)
20315 {
20318
20319 ntest->arg = (Expr *) makeVar(1,
20320 i,
20321 wholeatt->atttypid,
20322 wholeatt->atttypmod,
20323 wholeatt->attcollation,
20324 0);
20325 ntest->nulltesttype = IS_NOT_NULL;
20326
20327 /*
20328 * argisrow=false is correct even for a composite column,
20329 * because attnotnull does not represent a SQL-spec IS NOT
20330 * NULL test in such a case, just IS DISTINCT FROM NULL.
20331 */
20332 ntest->argisrow = false;
20333 ntest->location = -1;
20335 }
20336 }
20337 }
20338
20340}
Var * makeVar(int varno, AttrNumber varattno, Oid vartype, int32 vartypmod, Oid varcollid, Index varlevelsup)
Definition makefuncs.c:66
@ IS_NOT_NULL
Definition primnodes.h:1979
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:193

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

19555{
19556 ListCell *l;
19559
19560 foreach(l, on_commits)
19561 {
19563
19564 /* Ignore entry if already dropped in this xact */
19565 if (oc->deleting_subid != InvalidSubTransactionId)
19566 continue;
19567
19568 switch (oc->oncommit)
19569 {
19570 case ONCOMMIT_NOOP:
19572 /* Do nothing (there shouldn't be such entries, actually) */
19573 break;
19575
19576 /*
19577 * If this transaction hasn't accessed any temporary
19578 * relations, we can skip truncating ON COMMIT DELETE ROWS
19579 * tables, as they must still be empty.
19580 */
19583 break;
19584 case ONCOMMIT_DROP:
19586 break;
19587 }
19588 }
19589
19590 /*
19591 * Truncate relations before dropping so that all dependencies between
19592 * relations are removed after they are worked on. Doing it like this
19593 * might be a waste as it is possible that a relation being truncated will
19594 * be dropped anyway due to its parent being dropped, but this makes the
19595 * code more robust because of not having to re-check that the relation
19596 * exists at truncation time.
19597 */
19598 if (oids_to_truncate != NIL)
19600
19601 if (oids_to_drop != NIL)
19602 {
19604
19605 foreach(l, oids_to_drop)
19606 {
19607 ObjectAddress object;
19608
19609 object.classId = RelationRelationId;
19610 object.objectId = lfirst_oid(l);
19611 object.objectSubId = 0;
19612
19614
19616 }
19617
19618 /*
19619 * Object deletion might involve toast table access (to clean up
19620 * toasted catalog entries), so ensure we have a valid snapshot.
19621 */
19623
19624 /*
19625 * Since this is an automatic drop, rather than one directly initiated
19626 * by the user, we pass the PERFORM_DELETION_INTERNAL flag.
19627 */
19630
19632
19633#ifdef USE_ASSERT_CHECKING
19634
19635 /*
19636 * Note that table deletion will call remove_on_commit_action, so the
19637 * entry should get marked as deleted.
19638 */
19639 foreach(l, on_commits)
19640 {
19642
19643 if (oc->oncommit != ONCOMMIT_DROP)
19644 continue;
19645
19646 Assert(oc->deleting_subid != InvalidSubTransactionId);
19647 }
19648#endif
19649 }
19650}
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:3590
@ 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 19728 of file tablecmds.c.

19730{
19731 char relkind;
19733
19734 /* Nothing to do if the relation was not found. */
19735 if (!OidIsValid(relId))
19736 return;
19737
19738 /*
19739 * If the relation does exist, check whether it's an index. But note that
19740 * the relation might have been dropped between the time we did the name
19741 * lookup and now. In that case, there's nothing to do.
19742 */
19743 relkind = get_rel_relkind(relId);
19744 if (!relkind)
19745 return;
19746 if (relkind != RELKIND_RELATION && relkind != RELKIND_TOASTVALUE &&
19747 relkind != RELKIND_MATVIEW && relkind != RELKIND_PARTITIONED_TABLE)
19748 ereport(ERROR,
19750 errmsg("\"%s\" is not a table or materialized view", relation->relname)));
19751
19752 /* Check permissions */
19754 if (aclresult != ACLCHECK_OK)
19757 relation->relname);
19758}
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 19788 of file tablecmds.c.

19790{
19791 HeapTuple tuple;
19792
19793 /* Nothing to do if the relation was not found. */
19794 if (!OidIsValid(relId))
19795 return;
19796
19797 tuple = SearchSysCache1(RELOID, ObjectIdGetDatum(relId));
19798 if (!HeapTupleIsValid(tuple)) /* should not happen */
19799 elog(ERROR, "cache lookup failed for relation %u", relId);
19800
19803 relation->relname);
19804
19805 if (!allowSystemTableMods &&
19806 IsSystemClass(relId, (Form_pg_class) GETSTRUCT(tuple)))
19807 ereport(ERROR,
19809 errmsg("permission denied: \"%s\" is a system catalog",
19810 relation->relname)));
19811
19812 ReleaseSysCache(tuple);
19813}
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 19495 of file tablecmds.c.

19496{
19499
19500 /*
19501 * We needn't bother registering the relation unless there is an ON COMMIT
19502 * action we need to take.
19503 */
19504 if (action == ONCOMMIT_NOOP || action == ONCOMMIT_PRESERVE_ROWS)
19505 return;
19506
19508
19510 oc->relid = relid;
19511 oc->oncommit = action;
19512 oc->creating_subid = GetCurrentSubTransactionId();
19513 oc->deleting_subid = InvalidSubTransactionId;
19514
19515 /*
19516 * We use lcons() here so that ON COMMIT actions are processed in reverse
19517 * order of registration. That might not be essential but it seems
19518 * reasonable.
19519 */
19521
19523}
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 19531 of file tablecmds.c.

19532{
19533 ListCell *l;
19534
19535 foreach(l, on_commits)
19536 {
19538
19539 if (oc->relid == relid)
19540 {
19542 break;
19543 }
19544 }
19545}
SubTransactionId deleting_subid
Definition tablecmds.c:130

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

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

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

4041{
4042 Oid relid;
4044 ObjectAddress address;
4045
4046 /* lock level taken here should match renameatt_internal */
4048 stmt->missing_ok ? RVR_MISSING_OK : 0,
4050 NULL);
4051
4052 if (!OidIsValid(relid))
4053 {
4055 (errmsg("relation \"%s\" does not exist, skipping",
4056 stmt->relation->relname)));
4057 return InvalidObjectAddress;
4058 }
4059
4060 attnum =
4061 renameatt_internal(relid,
4062 stmt->subname, /* old att name */
4063 stmt->newname, /* new att name */
4064 stmt->relation->inh, /* recursive? */
4065 false, /* recursing? */
4066 0, /* expected inhcount */
4067 stmt->behavior);
4068
4070
4071 return address;
4072}
#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:3875
static void RangeVarCallbackForRenameAttribute(const RangeVar *rv, Oid relid, Oid oldrelid, void *arg)
Definition tablecmds.c:4020

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

4188{
4189 Oid relid = InvalidOid;
4190 Oid typid = InvalidOid;
4191
4192 if (stmt->renameType == OBJECT_DOMCONSTRAINT)
4193 {
4194 Relation rel;
4195 HeapTuple tup;
4196
4200 if (!HeapTupleIsValid(tup))
4201 elog(ERROR, "cache lookup failed for type %u", typid);
4204 table_close(rel, NoLock);
4205 }
4206 else
4207 {
4208 /* lock level taken here should match rename_constraint_internal */
4210 stmt->missing_ok ? RVR_MISSING_OK : 0,
4212 NULL);
4213 if (!OidIsValid(relid))
4214 {
4216 (errmsg("relation \"%s\" does not exist, skipping",
4217 stmt->relation->relname)));
4218 return InvalidObjectAddress;
4219 }
4220 }
4221
4222 return
4223 rename_constraint_internal(relid, typid,
4224 stmt->subname,
4225 stmt->newname,
4226 (stmt->relation &&
4227 stmt->relation->inh), /* recursive? */
4228 false, /* recursing? */
4229 0 /* expected inhcount */ );
4230}
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:4078
void checkDomainOwner(HeapTuple tup)
Definition typecmds.c:3527

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

4238{
4239 bool is_index_stmt = stmt->renameType == OBJECT_INDEX;
4240 Oid relid;
4241 ObjectAddress address;
4242
4243 /*
4244 * Grab an exclusive lock on the target table, index, sequence, view,
4245 * materialized view, or foreign table, which we will NOT release until
4246 * end of transaction.
4247 *
4248 * Lock level used here should match RenameRelationInternal, to avoid lock
4249 * escalation. However, because ALTER INDEX can be used with any relation
4250 * type, we mustn't believe without verification.
4251 */
4252 for (;;)
4253 {
4254 LOCKMODE lockmode;
4255 char relkind;
4256 bool obj_is_index;
4257
4259
4260 relid = RangeVarGetRelidExtended(stmt->relation, lockmode,
4261 stmt->missing_ok ? RVR_MISSING_OK : 0,
4263 stmt);
4264
4265 if (!OidIsValid(relid))
4266 {
4268 (errmsg("relation \"%s\" does not exist, skipping",
4269 stmt->relation->relname)));
4270 return InvalidObjectAddress;
4271 }
4272
4273 /*
4274 * We allow mismatched statement and object types (e.g., ALTER INDEX
4275 * to rename a table), but we might've used the wrong lock level. If
4276 * that happens, retry with the correct lock level. We don't bother
4277 * if we already acquired AccessExclusiveLock with an index, however.
4278 */
4279 relkind = get_rel_relkind(relid);
4280 obj_is_index = (relkind == RELKIND_INDEX ||
4281 relkind == RELKIND_PARTITIONED_INDEX);
4283 break;
4284
4285 UnlockRelationOid(relid, lockmode);
4287 }
4288
4289 /* Do the work */
4290 RenameRelationInternal(relid, stmt->newname, false, is_index_stmt);
4291
4292 ObjectAddressSet(address, RelationRelationId, relid);
4293
4294 return address;
4295}
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:4301

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

4302{
4304 Relation relrelation; /* for RELATION relation */
4309
4310 /*
4311 * Grab a lock on the target relation, which we will NOT release until end
4312 * of transaction. We need at least a self-exclusive lock so that
4313 * concurrent DDL doesn't overwrite the rename if they start updating
4314 * while still seeing the old version. The lock also guards against
4315 * triggering relcache reloads in concurrent sessions, which might not
4316 * handle this information changing under them. For indexes, we can use a
4317 * reduced lock level because RelationReloadIndexInfo() handles indexes
4318 * specially.
4319 */
4322
4323 /*
4324 * Find relation's pg_class tuple, and make sure newrelname isn't in use.
4325 */
4327
4329 if (!HeapTupleIsValid(reltup)) /* shouldn't happen */
4330 elog(ERROR, "cache lookup failed for relation %u", myrelid);
4331 otid = reltup->t_self;
4333
4335 ereport(ERROR,
4337 errmsg("relation \"%s\" already exists",
4338 newrelname)));
4339
4340 /*
4341 * RenameRelation is careful not to believe the caller's idea of the
4342 * relation kind being handled. We don't have to worry about this, but
4343 * let's not be totally oblivious to it. We can process an index as
4344 * not-an-index, but not the other way around.
4345 */
4346 Assert(!is_index ||
4347 is_index == (targetrelation->rd_rel->relkind == RELKIND_INDEX ||
4348 targetrelation->rd_rel->relkind == RELKIND_PARTITIONED_INDEX));
4349
4350 /*
4351 * Update pg_class tuple with new relname. (Scribbling on reltup is OK
4352 * because it's a copy...)
4353 */
4354 namestrcpy(&(relform->relname), newrelname);
4355
4358
4360 InvalidOid, is_internal);
4361
4364
4365 /*
4366 * Also rename the associated type, if any.
4367 */
4368 if (OidIsValid(targetrelation->rd_rel->reltype))
4369 RenameTypeInternal(targetrelation->rd_rel->reltype,
4371
4372 /*
4373 * Also rename the associated constraint, if any.
4374 */
4375 if (targetrelation->rd_rel->relkind == RELKIND_INDEX ||
4376 targetrelation->rd_rel->relkind == RELKIND_PARTITIONED_INDEX)
4377 {
4379
4382 }
4383
4384 /*
4385 * Close rel, but keep lock!
4386 */
4388}
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 4394 of file tablecmds.c.

4395{
4396 Relation relrelation; /* for RELATION relation */
4399
4400 /*
4401 * Find relation's pg_class tuple.
4402 */
4404
4406 if (!HeapTupleIsValid(reltup)) /* shouldn't happen */
4407 elog(ERROR, "cache lookup failed for relation %u", myrelid);
4409
4410 /*
4411 * Update pg_class tuple.
4412 */
4413 relform->relrewrite = InvalidOid;
4414
4416
4419}
#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 3678 of file tablecmds.c.

3679{
3681 HeapTuple tuple;
3683
3685 ShareUpdateExclusiveLock, false) ||
3687 ShareRowExclusiveLock, true));
3688
3689 /*
3690 * Fetch a modifiable copy of the tuple, modify it, update pg_class.
3691 */
3694 if (!HeapTupleIsValid(tuple))
3695 elog(ERROR, "cache lookup failed for relation %u", relationId);
3697
3698 if (classtuple->relhassubclass != relhassubclass)
3699 {
3700 classtuple->relhassubclass = relhassubclass;
3702 }
3703 else
3704 {
3705 /* no need to change tuple, but force relcache rebuild anyway */
3707 }
3708
3709 heap_freetuple(tuple);
3711}
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 3781 of file tablecmds.c.

3784{
3786 HeapTuple tuple;
3788 Form_pg_class rd_rel;
3789 Oid reloid = RelationGetRelid(rel);
3790
3792
3793 /* Get a modifiable copy of the relation's pg_class row. */
3795
3797 if (!HeapTupleIsValid(tuple))
3798 elog(ERROR, "cache lookup failed for relation %u", reloid);
3799 otid = tuple->t_self;
3800 rd_rel = (Form_pg_class) GETSTRUCT(tuple);
3801
3802 /* Update the pg_class row. */
3803 rd_rel->reltablespace = (newTableSpaceId == MyDatabaseTableSpace) ?
3806 rd_rel->relfilenode = newRelFilenumber;
3809
3810 /*
3811 * Record dependency on tablespace. This is only required for relations
3812 * that have no physical storage.
3813 */
3814 if (!RELKIND_HAS_STORAGE(rel->rd_rel->relkind))
3816 rd_rel->reltablespace);
3817
3818 heap_freetuple(tuple);
3820}
void changeDependencyOnTablespace(Oid classId, Oid objectId, Oid newTablespaceId)
#define RelFileNumberIsValid(relnumber)
Definition relpath.h:27
bool CheckRelationTableSpaceMove(Relation rel, Oid newTableSpaceId)
Definition tablecmds.c:3724

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