PostgreSQL Source Code  git master
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros
heapam.h File Reference
#include "access/sdir.h"
#include "access/skey.h"
#include "nodes/lockoptions.h"
#include "nodes/primnodes.h"
#include "storage/bufpage.h"
#include "storage/lockdefs.h"
#include "utils/relcache.h"
#include "utils/snapshot.h"
Include dependency graph for heapam.h:
This graph shows which files directly or indirectly include this file:

Go to the source code of this file.

Data Structures

struct  HeapUpdateFailureData
 

Macros

#define HEAP_INSERT_SKIP_WAL   0x0001
 
#define HEAP_INSERT_SKIP_FSM   0x0002
 
#define HEAP_INSERT_FROZEN   0x0004
 
#define HEAP_INSERT_SPECULATIVE   0x0008
 
#define MaxLockTupleMode   LockTupleExclusive
 
#define heap_close(r, l)   relation_close(r,l)
 
#define HeapScanIsValid(scan)   PointerIsValid(scan)
 

Typedefs

typedef struct
BulkInsertStateData
BulkInsertState
 
typedef enum LockTupleMode LockTupleMode
 
typedef struct
HeapUpdateFailureData 
HeapUpdateFailureData
 
typedef struct HeapScanDescDataHeapScanDesc
 
typedef struct
ParallelHeapScanDescData
ParallelHeapScanDesc
 

Enumerations

enum  LockTupleMode { LockTupleKeyShare, LockTupleShare, LockTupleNoKeyExclusive, LockTupleExclusive }
 

Functions

Relation relation_open (Oid relationId, LOCKMODE lockmode)
 
Relation try_relation_open (Oid relationId, LOCKMODE lockmode)
 
Relation relation_openrv (const RangeVar *relation, LOCKMODE lockmode)
 
Relation relation_openrv_extended (const RangeVar *relation, LOCKMODE lockmode, bool missing_ok)
 
void relation_close (Relation relation, LOCKMODE lockmode)
 
Relation heap_open (Oid relationId, LOCKMODE lockmode)
 
Relation heap_openrv (const RangeVar *relation, LOCKMODE lockmode)
 
Relation heap_openrv_extended (const RangeVar *relation, LOCKMODE lockmode, bool missing_ok)
 
HeapScanDesc heap_beginscan (Relation relation, Snapshot snapshot, int nkeys, ScanKey key)
 
HeapScanDesc heap_beginscan_catalog (Relation relation, int nkeys, ScanKey key)
 
HeapScanDesc heap_beginscan_strat (Relation relation, Snapshot snapshot, int nkeys, ScanKey key, bool allow_strat, bool allow_sync)
 
HeapScanDesc heap_beginscan_bm (Relation relation, Snapshot snapshot, int nkeys, ScanKey key)
 
HeapScanDesc heap_beginscan_sampling (Relation relation, Snapshot snapshot, int nkeys, ScanKey key, bool allow_strat, bool allow_sync, bool allow_pagemode)
 
void heap_setscanlimits (HeapScanDesc scan, BlockNumber startBlk, BlockNumber endBlk)
 
void heapgetpage (HeapScanDesc scan, BlockNumber page)
 
void heap_rescan (HeapScanDesc scan, ScanKey key)
 
void heap_rescan_set_params (HeapScanDesc scan, ScanKey key, bool allow_strat, bool allow_sync, bool allow_pagemode)
 
void heap_endscan (HeapScanDesc scan)
 
HeapTuple heap_getnext (HeapScanDesc scan, ScanDirection direction)
 
Size heap_parallelscan_estimate (Snapshot snapshot)
 
void heap_parallelscan_initialize (ParallelHeapScanDesc target, Relation relation, Snapshot snapshot)
 
HeapScanDesc heap_beginscan_parallel (Relation, ParallelHeapScanDesc)
 
bool heap_fetch (Relation relation, Snapshot snapshot, HeapTuple tuple, Buffer *userbuf, bool keep_buf, Relation stats_relation)
 
bool heap_hot_search_buffer (ItemPointer tid, Relation relation, Buffer buffer, Snapshot snapshot, HeapTuple heapTuple, bool *all_dead, bool first_call)
 
bool heap_hot_search (ItemPointer tid, Relation relation, Snapshot snapshot, bool *all_dead)
 
void heap_get_latest_tid (Relation relation, Snapshot snapshot, ItemPointer tid)
 
void setLastTid (const ItemPointer tid)
 
BulkInsertState GetBulkInsertState (void)
 
void FreeBulkInsertState (BulkInsertState)
 
void ReleaseBulkInsertStatePin (BulkInsertState bistate)
 
Oid heap_insert (Relation relation, HeapTuple tup, CommandId cid, int options, BulkInsertState bistate)
 
void heap_multi_insert (Relation relation, HeapTuple *tuples, int ntuples, CommandId cid, int options, BulkInsertState bistate)
 
HTSU_Result heap_delete (Relation relation, ItemPointer tid, CommandId cid, Snapshot crosscheck, bool wait, HeapUpdateFailureData *hufd)
 
void heap_finish_speculative (Relation relation, HeapTuple tuple)
 
void heap_abort_speculative (Relation relation, HeapTuple tuple)
 
HTSU_Result heap_update (Relation relation, ItemPointer otid, HeapTuple newtup, CommandId cid, Snapshot crosscheck, bool wait, HeapUpdateFailureData *hufd, LockTupleMode *lockmode)
 
HTSU_Result heap_lock_tuple (Relation relation, HeapTuple tuple, CommandId cid, LockTupleMode mode, LockWaitPolicy wait_policy, bool follow_update, Buffer *buffer, HeapUpdateFailureData *hufd)
 
void heap_inplace_update (Relation relation, HeapTuple tuple)
 
bool heap_freeze_tuple (HeapTupleHeader tuple, TransactionId cutoff_xid, TransactionId cutoff_multi)
 
bool heap_tuple_needs_freeze (HeapTupleHeader tuple, TransactionId cutoff_xid, MultiXactId cutoff_multi, Buffer buf)
 
bool heap_tuple_needs_eventual_freeze (HeapTupleHeader tuple)
 
Oid simple_heap_insert (Relation relation, HeapTuple tup)
 
void simple_heap_delete (Relation relation, ItemPointer tid)
 
void simple_heap_update (Relation relation, ItemPointer otid, HeapTuple tup)
 
void heap_sync (Relation relation)
 
void heap_update_snapshot (HeapScanDesc scan, Snapshot snapshot)
 
void heap_page_prune_opt (Relation relation, Buffer buffer)
 
int heap_page_prune (Relation relation, Buffer buffer, TransactionId OldestXmin, bool report_stats, TransactionId *latestRemovedXid)
 
void heap_page_prune_execute (Buffer buffer, OffsetNumber *redirected, int nredirected, OffsetNumber *nowdead, int ndead, OffsetNumber *nowunused, int nunused)
 
void heap_get_root_tuples (Page page, OffsetNumber *root_offsets)
 
void ss_report_location (Relation rel, BlockNumber location)
 
BlockNumber ss_get_location (Relation rel, BlockNumber relnblocks)
 
void SyncScanShmemInit (void)
 
Size SyncScanShmemSize (void)
 

Macro Definition Documentation

#define heap_close (   r,
 
)    relation_close(r,l)

Definition at line 97 of file heapam.h.

Referenced by acquire_inherited_sample_rows(), AcquireRewriteLocks(), AddEnumLabel(), AddNewAttributeTuples(), addRangeTableEntry(), AddRoleMems(), afterTriggerInvokeEvents(), AfterTriggerSetState(), AggregateCreate(), AlterCollation(), AlterConstraintNamespaces(), AlterDatabase(), AlterDatabaseOwner(), AlterDomainAddConstraint(), AlterDomainDefault(), AlterDomainDropConstraint(), AlterDomainNotNull(), AlterDomainValidateConstraint(), AlterEventTrigger(), AlterEventTriggerOwner(), AlterEventTriggerOwner_oid(), AlterExtensionNamespace(), AlterForeignDataWrapper(), AlterForeignDataWrapperOwner(), AlterForeignDataWrapperOwner_oid(), AlterForeignServer(), AlterForeignServerOwner(), AlterForeignServerOwner_oid(), AlterFunction(), AlterObjectNamespace_oid(), AlterOperator(), AlterPolicy(), AlterPublication(), AlterPublicationOwner(), AlterPublicationOwner_oid(), AlterRole(), AlterSchemaOwner(), AlterSchemaOwner_oid(), AlterSequence(), AlterSetting(), AlterSubscription(), AlterSubscriptionOwner(), AlterSubscriptionOwner_oid(), AlterTableMoveAll(), AlterTableNamespaceInternal(), AlterTableSpaceOptions(), AlterTSConfiguration(), AlterTSDictionary(), AlterTypeNamespaceInternal(), AlterTypeOwner(), AlterTypeOwner_oid(), AlterTypeOwnerInternal(), AlterUserMapping(), AppendAttributeTuples(), ApplyExtensionUpdates(), AssignTypeArrayOid(), ATAddCheckConstraint(), ATAddForeignKeyConstraint(), ATExecAddColumn(), ATExecAddInherit(), ATExecAddOf(), ATExecAlterColumnGenericOptions(), ATExecAlterColumnType(), ATExecAlterConstraint(), ATExecAttachPartition(), ATExecChangeOwner(), ATExecDetachPartition(), ATExecDisableRowSecurity(), ATExecDropColumn(), ATExecDropConstraint(), ATExecDropInherit(), ATExecDropNotNull(), ATExecDropOf(), ATExecEnableRowSecurity(), ATExecForceNoForceRowSecurity(), ATExecGenericOptions(), ATExecSetNotNull(), ATExecSetOptions(), ATExecSetRelOptions(), ATExecSetStatistics(), ATExecSetStorage(), ATExecSetTableSpace(), ATExecValidateConstraint(), ATPrepChangePersistence(), ATRewriteTable(), ATRewriteTables(), AttrDefaultFetch(), boot_openrel(), BootstrapToastTable(), bringetbitmap(), brinvacuumcleanup(), bt_index_check_internal(), build_indices(), build_physical_tlist(), BuildRelationExtStatistics(), CatalogCacheInitializeCache(), change_owner_fix_column_acls(), changeDependencyFor(), changeDependencyOnOwner(), check_db_file_conflict(), check_selective_binary_conversion(), CheckAndCreateToastTable(), CheckConstraintFetch(), checkSharedDependencies(), ChooseConstraintName(), close_lo_relation(), closerel(), CloseTableList(), cluster(), CollationCreate(), ConstraintNameIsUsed(), ConversionCreate(), copy_heap_data(), CopyFrom(), copyTemplateDependencies(), CountDBSubscriptions(), create_proc_lang(), create_toast_table(), CreateAccessMethod(), CreateCast(), CreateComments(), CreateConstraintEntry(), createdb(), CreateForeignDataWrapper(), CreateForeignServer(), CreateForeignTable(), CreateInheritance(), CreateOpFamily(), CreatePolicy(), CreatePublication(), CreateRole(), CreateSharedComments(), CreateStatistics(), CreateSubscription(), CreateTableSpace(), CreateTransform(), CreateTrigger(), CreateUserMapping(), currtid_byrelname(), currtid_byreloid(), currtid_for_view(), database_to_xmlschema_internal(), DefineIndex(), DefineOpClass(), DefineQueryRewrite(), DefineRelation(), DefineSequence(), DefineTSConfiguration(), DefineTSDictionary(), DefineTSParser(), DefineTSTemplate(), DeleteAttributeTuples(), DeleteComments(), deleteDependencyRecordsFor(), deleteDependencyRecordsForClass(), DeleteInitPrivs(), deleteOneObject(), DeleteRelationTuple(), DeleteSecurityLabel(), DeleteSequenceTuple(), DeleteSharedComments(), deleteSharedDependencyRecordsFor(), DeleteSharedSecurityLabel(), DeleteSystemAttributeTuples(), DelRoleMems(), deparseColumnRef(), deparseFromExprForRel(), deparseSelectSql(), do_autovacuum(), DoCopy(), drop_parent_dependency(), DropCastById(), dropDatabaseDependencies(), dropdb(), DropProceduralLanguageById(), DropRole(), DropSetting(), DropSubscription(), DropTableSpace(), DropTransformById(), EnableDisableRule(), EnableDisableTrigger(), enum_endpoint(), enum_range_internal(), EnumValuesCreate(), EnumValuesDelete(), EvalPlanQualEnd(), EventTriggerSQLDropAddObject(), exec_object_restorecon(), ExecAlterExtensionStmt(), ExecAlterObjectDependsStmt(), ExecAlterObjectSchemaStmt(), ExecAlterOwnerStmt(), ExecCloseScanRelation(), ExecEndModifyTable(), ExecEndPlan(), ExecGrant_Database(), ExecGrant_Fdw(), ExecGrant_ForeignServer(), ExecGrant_Function(), ExecGrant_Language(), ExecGrant_Largeobject(), ExecGrant_Namespace(), ExecGrant_Relation(), ExecGrant_Tablespace(), ExecGrant_Type(), ExecInitModifyTable(), ExecRefreshMatView(), ExecRenameStmt(), ExecuteTruncate(), expand_inherited_rtentry(), expand_targetlist(), extension_config_remove(), find_inheritance_children(), find_language_template(), find_typed_table_dependencies(), finish_heap_swap(), fireRIRrules(), free_parsestate(), generate_partition_qual(), get_actual_variable_range(), get_constraint_index(), get_database_list(), get_database_oid(), get_db_info(), get_domain_constraint_oid(), get_extension_name(), get_extension_oid(), get_extension_schema(), get_file_fdw_attribute_options(), get_index_constraint(), get_object_address_relobject(), get_partition_parent(), get_pkey_attnames(), get_primary_key_attnos(), get_rel_oids(), get_relation_constraint_oid(), get_relation_constraints(), get_relation_data_width(), get_relation_info(), get_relation_policy_oid(), get_row_security_policies(), get_subscription_list(), get_tablespace_name(), get_tablespace_oid(), get_trigger_oid(), GetAllTablesPublicationRelations(), GetAllTablesPublications(), GetComment(), getConstraintTypeDescription(), GetDatabaseTuple(), GetDatabaseTupleByOid(), GetDefaultOpClass(), getExtensionOfObject(), getObjectDescription(), getObjectIdentityParts(), getOwnedSequences(), GetPublicationRelations(), getRelationsInNamespace(), GetSecurityLabel(), GetSharedSecurityLabel(), GetSubscriptionNotReadyRelations(), GetSubscriptionRelations(), GetSubscriptionRelState(), gettype(), GrantRole(), has_row_triggers(), heap_create_with_catalog(), heap_drop_with_catalog(), heap_sync(), heap_truncate(), heap_truncate_find_FKs(), heap_truncate_one_rel(), index_build(), index_constraint_create(), index_create(), index_drop(), index_set_state_flags(), index_update_stats(), infer_arbiter_indexes(), insert_event_trigger_tuple(), InsertExtensionTuple(), InsertRule(), intorel_shutdown(), isQueryUsingTempRelation_walker(), LargeObjectCreate(), LargeObjectDrop(), LargeObjectExists(), load_domaintype_info(), load_enum_cache_data(), logicalrep_rel_close(), LogicalRepSyncTableStart(), lookup_ts_config_cache(), LookupOpclassInfo(), make_new_heap(), make_viewdef(), makeArrayTypeName(), mark_index_clustered(), MergeAttributes(), MergeAttributesIntoExisting(), MergeConstraintsIntoExisting(), MergeWithExistingConstraint(), movedb(), myLargeObjectExists(), NamespaceCreate(), objectsInSchemaToOids(), OpenTableList(), OperatorCreate(), OperatorShellMake(), OperatorUpd(), performDeletion(), performMultipleDeletions(), pg_event_trigger_ddl_commands(), pg_extension_config_dump(), pg_extension_ownercheck(), pg_get_constraintdef_worker(), pg_get_replica_identity_index(), pg_get_serial_sequence(), pg_get_triggerdef_worker(), pg_identify_object(), pg_largeobject_aclmask_snapshot(), pg_largeobject_ownercheck(), pgrowlocks(), pgstat_collect_oids(), postgresPlanDirectModify(), postgresPlanForeignModify(), ProcedureCreate(), process_settings(), publication_add_relation(), RangeCreate(), RangeDelete(), rebuild_relation(), recordExtensionInitPrivWorker(), recordMultipleDependencies(), recordSharedDependencyOn(), refresh_by_match_merge(), regclassin(), regoperin(), regprocin(), regtypein(), reindex_index(), reindex_relation(), ReindexMultipleTables(), relation_has_policies(), relation_mark_replica_identity(), RelationBuildRowSecurity(), RelationBuildRuleLock(), RelationBuildTriggers(), RelationBuildTupleDesc(), RelationGetExclusionInfo(), RelationGetFKeyList(), RelationGetIndexList(), RelationGetPartitionDispatchInfo(), RelationGetStatExtList(), RelationRemoveInheritance(), RelationSetNewRelfilenode(), RelidByRelfilenode(), remove_dbtablespaces(), RemoveAccessMethodById(), RemoveAmOpEntryById(), RemoveAmProcEntryById(), RemoveAttrDefault(), RemoveAttrDefaultById(), RemoveAttributeById(), RemoveCollationById(), RemoveConstraintById(), RemoveConversionById(), RemoveDefaultACLById(), RemoveEventTriggerById(), RemoveExtensionById(), RemoveForeignDataWrapperById(), RemoveForeignServerById(), RemoveFunctionById(), RemoveInheritance(), RemoveObjects(), RemoveOpClassById(), RemoveOperatorById(), RemoveOpFamilyById(), RemovePartitionKeyByRelId(), RemovePolicyById(), RemovePublicationById(), RemovePublicationRelById(), RemoveRewriteRuleById(), RemoveRoleFromObjectACL(), RemoveRoleFromObjectPolicy(), RemoveSchemaById(), RemoveStatistics(), RemoveStatisticsById(), RemoveStatisticsExt(), RemoveSubscriptionRel(), RemoveTriggerById(), RemoveTSConfigurationById(), RemoveTSDictionaryById(), RemoveTSParserById(), RemoveTSTemplateById(), RemoveTypeById(), RemoveUserMappingById(), rename_policy(), renameatt_internal(), RenameConstraint(), RenameConstraintById(), RenameDatabase(), RenameEnumLabel(), RenameRelationInternal(), RenameRewriteRule(), RenameRole(), RenameSchema(), RenameTableSpace(), renametrig(), RenameType(), RenameTypeInternal(), replorigin_create(), replorigin_drop(), RewriteQuery(), rewriteTargetView(), RI_FKey_cascade_del(), RI_FKey_cascade_upd(), RI_FKey_check(), RI_FKey_setdefault_del(), RI_FKey_setdefault_upd(), RI_FKey_setnull_del(), RI_FKey_setnull_upd(), ri_restrict_del(), ri_restrict_upd(), ScanPgRelation(), schema_to_xmlschema_internal(), SearchCatCache(), SearchCatCacheList(), sepgsql_attribute_post_create(), sepgsql_database_post_create(), sepgsql_index_modify(), sepgsql_proc_post_create(), sepgsql_proc_setattr(), sepgsql_relation_post_create(), sepgsql_relation_setattr(), sepgsql_schema_post_create(), sequenceIsOwned(), SetDefaultACL(), SetFunctionArgType(), SetFunctionReturnType(), SetMatViewPopulatedState(), SetRelationHasSubclass(), SetRelationNumChecks(), SetRelationRuleStatus(), SetSecurityLabel(), SetSharedSecurityLabel(), SetSubscriptionRelState(), setTargetTable(), shdepDropOwned(), shdepReassignOwned(), StoreAttrDefault(), StoreCatalogInheritance(), storeOperators(), StorePartitionBound(), StorePartitionKey(), storeProcedures(), swap_relation_files(), table_to_xml_and_xmlschema(), table_to_xmlschema(), ThereIsAtLeastOneRole(), toast_delete_datum(), toast_fetch_datum(), toast_fetch_datum_slice(), toast_get_valid_index(), toast_save_datum(), toastid_valueid_exists(), transformIndexConstraint(), transformIndexStmt(), transformRuleStmt(), transformTableLikeClause(), transientrel_shutdown(), TypeCreate(), typeInheritsFrom(), TypeShellMake(), update_attstats(), updateAclDependencies(), UpdateIndexRelation(), vac_truncate_clog(), vac_update_datfrozenxid(), vac_update_relstats(), validate_index(), and validateDomainConstraint().

#define HEAP_INSERT_FROZEN   0x0004

Definition at line 30 of file heapam.h.

Referenced by CopyFrom(), heap_prepare_insert(), and transientrel_startup().

#define HEAP_INSERT_SKIP_FSM   0x0002
#define HEAP_INSERT_SPECULATIVE   0x0008

Definition at line 31 of file heapam.h.

Referenced by ExecInsert(), heap_insert(), and toast_insert_or_update().

#define HeapScanIsValid (   scan)    PointerIsValid(scan)

Definition at line 107 of file heapam.h.

#define MaxLockTupleMode   LockTupleExclusive

Definition at line 50 of file heapam.h.

Typedef Documentation

Definition at line 33 of file heapam.h.

Definition at line 100 of file heapam.h.

Definition at line 101 of file heapam.h.

Enumeration Type Documentation

Enumerator
LockTupleKeyShare 
LockTupleShare 
LockTupleNoKeyExclusive 
LockTupleExclusive 

Definition at line 38 of file heapam.h.

39 {
40  /* SELECT FOR KEY SHARE */
42  /* SELECT FOR SHARE */
44  /* SELECT FOR NO KEY UPDATE, and UPDATEs that don't modify key columns */
46  /* SELECT FOR UPDATE, UPDATEs that modify key columns, and DELETE */
LockTupleMode
Definition: heapam.h:38

Function Documentation

void FreeBulkInsertState ( BulkInsertState  )

Definition at line 2336 of file heapam.c.

References BulkInsertStateData::current_buf, FreeAccessStrategy(), InvalidBuffer, pfree(), ReleaseBuffer(), and BulkInsertStateData::strategy.

Referenced by ATRewriteTable(), CopyFrom(), intorel_shutdown(), and transientrel_shutdown().

2337 {
2338  if (bistate->current_buf != InvalidBuffer)
2339  ReleaseBuffer(bistate->current_buf);
2340  FreeAccessStrategy(bistate->strategy);
2341  pfree(bistate);
2342 }
#define InvalidBuffer
Definition: buf.h:25
void ReleaseBuffer(Buffer buffer)
Definition: bufmgr.c:3309
void pfree(void *pointer)
Definition: mcxt.c:950
void FreeAccessStrategy(BufferAccessStrategy strategy)
Definition: freelist.c:580
BulkInsertState GetBulkInsertState ( void  )

Definition at line 2322 of file heapam.c.

References BAS_BULKWRITE, BulkInsertStateData::current_buf, GetAccessStrategy(), InvalidBuffer, palloc(), and BulkInsertStateData::strategy.

Referenced by ATRewriteTable(), CopyFrom(), intorel_startup(), and transientrel_startup().

2323 {
2324  BulkInsertState bistate;
2325 
2326  bistate = (BulkInsertState) palloc(sizeof(BulkInsertStateData));
2328  bistate->current_buf = InvalidBuffer;
2329  return bistate;
2330 }
BufferAccessStrategy GetAccessStrategy(BufferAccessStrategyType btype)
Definition: freelist.c:525
#define InvalidBuffer
Definition: buf.h:25
struct BulkInsertStateData * BulkInsertState
Definition: heapam.h:33
BufferAccessStrategy strategy
Definition: hio.h:33
void * palloc(Size size)
Definition: mcxt.c:849
Buffer current_buf
Definition: hio.h:34
void heap_abort_speculative ( Relation  relation,
HeapTuple  tuple 
)

Definition at line 6108 of file heapam.c.

References Assert, buffer, BUFFER_LOCK_EXCLUSIVE, BUFFER_LOCK_UNLOCK, BufferGetPage, compute_infobits(), elog, END_CRIT_SECTION, ERROR, xl_heap_delete::flags, GetCurrentTransactionId(), HEAP_KEYS_UPDATED, HEAP_MOVED, HEAP_XMAX_BITS, HeapTupleHasExternal, HeapTupleHeaderIsHeapOnly, HeapTupleHeaderIsSpeculative, HeapTupleHeaderSetXmin, xl_heap_delete::infobits_set, InvalidTransactionId, IsToastRelation(), ItemIdGetLength, ItemIdIsNormal, ItemPointerGetBlockNumber, ItemPointerGetOffsetNumber, ItemPointerIsValid, LockBuffer(), MarkBufferDirty(), xl_heap_delete::offnum, PageGetItem, PageGetItemId, PageIsAllVisible, PageSetLSN, PageSetPrunable, pgstat_count_heap_delete(), ReadBuffer(), RecentGlobalXmin, REGBUF_STANDARD, RelationGetRelid, RelationNeedsWAL, ReleaseBuffer(), SizeOfHeapDelete, START_CRIT_SECTION, HeapTupleHeaderData::t_choice, HeapTupleHeaderData::t_ctid, HeapTupleData::t_data, HeapTupleHeaderData::t_heap, HeapTupleHeaderData::t_infomask, HeapTupleHeaderData::t_infomask2, HeapTupleData::t_len, HeapTupleData::t_self, HeapTupleData::t_tableOid, HeapTupleFields::t_xmin, toast_delete(), TransactionIdIsValid, XLH_DELETE_IS_SUPER, XLOG_HEAP_DELETE, XLogBeginInsert(), XLogInsert(), XLogRegisterBuffer(), XLogRegisterData(), and xl_heap_delete::xmax.

Referenced by ExecInsert(), and toast_delete_datum().

6109 {
6111  ItemPointer tid = &(tuple->t_self);
6112  ItemId lp;
6113  HeapTupleData tp;
6114  Page page;
6115  BlockNumber block;
6116  Buffer buffer;
6117 
6118  Assert(ItemPointerIsValid(tid));
6119 
6120  block = ItemPointerGetBlockNumber(tid);
6121  buffer = ReadBuffer(relation, block);
6122  page = BufferGetPage(buffer);
6123 
6125 
6126  /*
6127  * Page can't be all visible, we just inserted into it, and are still
6128  * running.
6129  */
6130  Assert(!PageIsAllVisible(page));
6131 
6132  lp = PageGetItemId(page, ItemPointerGetOffsetNumber(tid));
6133  Assert(ItemIdIsNormal(lp));
6134 
6135  tp.t_tableOid = RelationGetRelid(relation);
6136  tp.t_data = (HeapTupleHeader) PageGetItem(page, lp);
6137  tp.t_len = ItemIdGetLength(lp);
6138  tp.t_self = *tid;
6139 
6140  /*
6141  * Sanity check that the tuple really is a speculatively inserted tuple,
6142  * inserted by us.
6143  */
6144  if (tp.t_data->t_choice.t_heap.t_xmin != xid)
6145  elog(ERROR, "attempted to kill a tuple inserted by another transaction");
6146  if (!(IsToastRelation(relation) || HeapTupleHeaderIsSpeculative(tp.t_data)))
6147  elog(ERROR, "attempted to kill a non-speculative tuple");
6149 
6150  /*
6151  * No need to check for serializable conflicts here. There is never a
6152  * need for a combocid, either. No need to extract replica identity, or
6153  * do anything special with infomask bits.
6154  */
6155 
6157 
6158  /*
6159  * The tuple will become DEAD immediately. Flag that this page
6160  * immediately is a candidate for pruning by setting xmin to
6161  * RecentGlobalXmin. That's not pretty, but it doesn't seem worth
6162  * inventing a nicer API for this.
6163  */
6166 
6167  /* store transaction information of xact deleting the tuple */
6170 
6171  /*
6172  * Set the tuple header xmin to InvalidTransactionId. This makes the
6173  * tuple immediately invisible everyone. (In particular, to any
6174  * transactions waiting on the speculative token, woken up later.)
6175  */
6177 
6178  /* Clear the speculative insertion token too */
6179  tp.t_data->t_ctid = tp.t_self;
6180 
6181  MarkBufferDirty(buffer);
6182 
6183  /*
6184  * XLOG stuff
6185  *
6186  * The WAL records generated here match heap_delete(). The same recovery
6187  * routines are used.
6188  */
6189  if (RelationNeedsWAL(relation))
6190  {
6191  xl_heap_delete xlrec;
6192  XLogRecPtr recptr;
6193 
6194  xlrec.flags = XLH_DELETE_IS_SUPER;
6196  tp.t_data->t_infomask2);
6198  xlrec.xmax = xid;
6199 
6200  XLogBeginInsert();
6201  XLogRegisterData((char *) &xlrec, SizeOfHeapDelete);
6202  XLogRegisterBuffer(0, buffer, REGBUF_STANDARD);
6203 
6204  /* No replica identity & replication origin logged */
6205 
6206  recptr = XLogInsert(RM_HEAP_ID, XLOG_HEAP_DELETE);
6207 
6208  PageSetLSN(page, recptr);
6209  }
6210 
6211  END_CRIT_SECTION();
6212 
6213  LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
6214 
6215  if (HeapTupleHasExternal(&tp))
6216  {
6217  Assert(!IsToastRelation(relation));
6218  toast_delete(relation, &tp, true);
6219  }
6220 
6221  /*
6222  * Never need to mark tuple for invalidation, since catalogs don't support
6223  * speculative insertion
6224  */
6225 
6226  /* Now we can release the buffer */
6227  ReleaseBuffer(buffer);
6228 
6229  /* count deletion, as we counted the insertion too */
6230  pgstat_count_heap_delete(relation);
6231 }
#define ItemPointerIsValid(pointer)
Definition: itemptr.h:59
#define BUFFER_LOCK_UNLOCK
Definition: bufmgr.h:87
bool IsToastRelation(Relation relation)
Definition: catalog.c:135
#define HEAP_XMAX_BITS
Definition: htup_details.h:256
#define XLH_DELETE_IS_SUPER
Definition: heapam_xlog.h:95
static uint8 compute_infobits(uint16 infomask, uint16 infomask2)
Definition: heapam.c:2955
HeapTupleFields t_heap
Definition: htup_details.h:146
#define PageIsAllVisible(page)
Definition: bufpage.h:382
uint32 TransactionId
Definition: c.h:397
void MarkBufferDirty(Buffer buffer)
Definition: bufmgr.c:1450
void XLogRegisterBuffer(uint8 block_id, Buffer buffer, uint8 flags)
Definition: xloginsert.c:213
HeapTupleHeaderData * HeapTupleHeader
Definition: htup.h:23
#define END_CRIT_SECTION()
Definition: miscadmin.h:132
#define HeapTupleHeaderIsSpeculative(tup)
Definition: htup_details.h:423
#define PageSetPrunable(page, xid)
Definition: bufpage.h:395
#define START_CRIT_SECTION()
Definition: miscadmin.h:130
uint32 BlockNumber
Definition: block.h:31
void ReleaseBuffer(Buffer buffer)
Definition: bufmgr.c:3309
#define BUFFER_LOCK_EXCLUSIVE
Definition: bufmgr.h:89
OffsetNumber offnum
Definition: heapam_xlog.h:105
HeapTupleHeader t_data
Definition: htup.h:67
#define HeapTupleHeaderIsHeapOnly(tup)
Definition: htup_details.h:502
#define ItemIdGetLength(itemId)
Definition: itemid.h:58
#define ERROR
Definition: elog.h:43
ItemPointerData t_ctid
Definition: htup_details.h:150
ItemPointerData t_self
Definition: htup.h:65
TransactionId xmax
Definition: heapam_xlog.h:104
TransactionId GetCurrentTransactionId(void)
Definition: xact.c:417
uint32 t_len
Definition: htup.h:64
#define SizeOfHeapDelete
Definition: heapam_xlog.h:110
TransactionId RecentGlobalXmin
Definition: snapmgr.c:166
#define REGBUF_STANDARD
Definition: xloginsert.h:35
#define InvalidTransactionId
Definition: transam.h:31
Oid t_tableOid
Definition: htup.h:66
#define BufferGetPage(buffer)
Definition: bufmgr.h:160
TransactionId t_xmin
Definition: htup_details.h:118
#define PageGetItemId(page, offsetNumber)
Definition: bufpage.h:232
void XLogRegisterData(char *data, int len)
Definition: xloginsert.c:323
XLogRecPtr XLogInsert(RmgrId rmid, uint8 info)
Definition: xloginsert.c:415
void LockBuffer(Buffer buffer, int mode)
Definition: bufmgr.c:3546
#define HEAP_KEYS_UPDATED
Definition: htup_details.h:264
union HeapTupleHeaderData::@39 t_choice
#define HEAP_MOVED
Definition: htup_details.h:202
uint64 XLogRecPtr
Definition: xlogdefs.h:21
#define Assert(condition)
Definition: c.h:675
uint8 infobits_set
Definition: heapam_xlog.h:106
#define ItemIdIsNormal(itemId)
Definition: itemid.h:98
WalTimeSample buffer[LAG_TRACKER_BUFFER_SIZE]
Definition: walsender.c:207
Buffer ReadBuffer(Relation reln, BlockNumber blockNum)
Definition: bufmgr.c:594
#define ItemPointerGetOffsetNumber(pointer)
Definition: itemptr.h:76
#define RelationNeedsWAL(relation)
Definition: rel.h:506
void pgstat_count_heap_delete(Relation rel)
Definition: pgstat.c:1852
#define HeapTupleHasExternal(tuple)
Definition: htup_details.h:674
void toast_delete(Relation rel, HeapTuple oldtup, bool is_speculative)
Definition: tuptoaster.c:464
#define elog
Definition: elog.h:219
#define ItemPointerGetBlockNumber(pointer)
Definition: itemptr.h:66
#define TransactionIdIsValid(xid)
Definition: transam.h:41
void XLogBeginInsert(void)
Definition: xloginsert.c:120
#define PageSetLSN(page, lsn)
Definition: bufpage.h:365
int Buffer
Definition: buf.h:23
#define XLOG_HEAP_DELETE
Definition: heapam_xlog.h:33
#define RelationGetRelid(relation)
Definition: rel.h:417
#define PageGetItem(page, itemId)
Definition: bufpage.h:337
Pointer Page
Definition: bufpage.h:74
#define HeapTupleHeaderSetXmin(tup, xid)
Definition: htup_details.h:313
HeapScanDesc heap_beginscan ( Relation  relation,
Snapshot  snapshot,
int  nkeys,
ScanKey  key 
)

Definition at line 1394 of file heapam.c.

References heap_beginscan_internal().

Referenced by AlterDomainNotNull(), ATRewriteTable(), copy_heap_data(), CopyTo(), DefineQueryRewrite(), pgrowlocks(), pgstat_collect_oids(), RelationFindReplTupleSeq(), SeqNext(), validateCheckConstraint(), validateDomainConstraint(), and validateForeignKeyConstraint().

1396 {
1397  return heap_beginscan_internal(relation, snapshot, nkeys, key, NULL,
1398  true, true, true, false, false, false);
1399 }
static HeapScanDesc heap_beginscan_internal(Relation relation, Snapshot snapshot, int nkeys, ScanKey key, ParallelHeapScanDesc parallel_scan, bool allow_strat, bool allow_sync, bool allow_pagemode, bool is_bitmapscan, bool is_samplescan, bool temp_snap)
Definition: heapam.c:1440
#define NULL
Definition: c.h:229
HeapScanDesc heap_beginscan_bm ( Relation  relation,
Snapshot  snapshot,
int  nkeys,
ScanKey  key 
)

Definition at line 1422 of file heapam.c.

References heap_beginscan_internal().

Referenced by ExecInitBitmapHeapScan().

1424 {
1425  return heap_beginscan_internal(relation, snapshot, nkeys, key, NULL,
1426  false, false, true, true, false, false);
1427 }
static HeapScanDesc heap_beginscan_internal(Relation relation, Snapshot snapshot, int nkeys, ScanKey key, ParallelHeapScanDesc parallel_scan, bool allow_strat, bool allow_sync, bool allow_pagemode, bool is_bitmapscan, bool is_samplescan, bool temp_snap)
Definition: heapam.c:1440
#define NULL
Definition: c.h:229
HeapScanDesc heap_beginscan_catalog ( Relation  relation,
int  nkeys,
ScanKey  key 
)

Definition at line 1402 of file heapam.c.

References GetCatalogSnapshot(), heap_beginscan_internal(), RegisterSnapshot(), and RelationGetRelid.

Referenced by AlterTableMoveAll(), AlterTableSpaceOptions(), boot_openrel(), check_db_file_conflict(), createdb(), do_autovacuum(), DropSetting(), DropTableSpace(), find_typed_table_dependencies(), get_database_list(), get_rel_oids(), get_subscription_list(), get_tables_to_cluster(), get_tablespace_name(), get_tablespace_oid(), GetAllTablesPublicationRelations(), getRelationsInNamespace(), gettype(), index_update_stats(), objectsInSchemaToOids(), ReindexMultipleTables(), remove_dbtablespaces(), RemoveConversionById(), RemoveSubscriptionRel(), RenameTableSpace(), ThereIsAtLeastOneRole(), and vac_truncate_clog().

1403 {
1404  Oid relid = RelationGetRelid(relation);
1405  Snapshot snapshot = RegisterSnapshot(GetCatalogSnapshot(relid));
1406 
1407  return heap_beginscan_internal(relation, snapshot, nkeys, key, NULL,
1408  true, true, true, false, false, true);
1409 }
Snapshot RegisterSnapshot(Snapshot snapshot)
Definition: snapmgr.c:858
Snapshot GetCatalogSnapshot(Oid relid)
Definition: snapmgr.c:436
unsigned int Oid
Definition: postgres_ext.h:31
static HeapScanDesc heap_beginscan_internal(Relation relation, Snapshot snapshot, int nkeys, ScanKey key, ParallelHeapScanDesc parallel_scan, bool allow_strat, bool allow_sync, bool allow_pagemode, bool is_bitmapscan, bool is_samplescan, bool temp_snap)
Definition: heapam.c:1440
#define NULL
Definition: c.h:229
#define RelationGetRelid(relation)
Definition: rel.h:417
HeapScanDesc heap_beginscan_parallel ( Relation  ,
ParallelHeapScanDesc   
)

Definition at line 1653 of file heapam.c.

References Assert, heap_beginscan_internal(), ParallelHeapScanDescData::phs_relid, ParallelHeapScanDescData::phs_snapshot_data, RegisterSnapshot(), RelationGetRelid, and RestoreSnapshot().

Referenced by ExecSeqScanInitializeDSM(), and ExecSeqScanInitializeWorker().

1654 {
1655  Snapshot snapshot;
1656 
1657  Assert(RelationGetRelid(relation) == parallel_scan->phs_relid);
1658  snapshot = RestoreSnapshot(parallel_scan->phs_snapshot_data);
1659  RegisterSnapshot(snapshot);
1660 
1661  return heap_beginscan_internal(relation, snapshot, 0, NULL, parallel_scan,
1662  true, true, true, false, false, true);
1663 }
Snapshot RestoreSnapshot(char *start_address)
Definition: snapmgr.c:2075
Snapshot RegisterSnapshot(Snapshot snapshot)
Definition: snapmgr.c:858
static HeapScanDesc heap_beginscan_internal(Relation relation, Snapshot snapshot, int nkeys, ScanKey key, ParallelHeapScanDesc parallel_scan, bool allow_strat, bool allow_sync, bool allow_pagemode, bool is_bitmapscan, bool is_samplescan, bool temp_snap)
Definition: heapam.c:1440
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:675
#define RelationGetRelid(relation)
Definition: rel.h:417
HeapScanDesc heap_beginscan_sampling ( Relation  relation,
Snapshot  snapshot,
int  nkeys,
ScanKey  key,
bool  allow_strat,
bool  allow_sync,
bool  allow_pagemode 
)

Definition at line 1430 of file heapam.c.

References heap_beginscan_internal().

Referenced by tablesample_init().

1433 {
1434  return heap_beginscan_internal(relation, snapshot, nkeys, key, NULL,
1435  allow_strat, allow_sync, allow_pagemode,
1436  false, true, false);
1437 }
static HeapScanDesc heap_beginscan_internal(Relation relation, Snapshot snapshot, int nkeys, ScanKey key, ParallelHeapScanDesc parallel_scan, bool allow_strat, bool allow_sync, bool allow_pagemode, bool is_bitmapscan, bool is_samplescan, bool temp_snap)
Definition: heapam.c:1440
#define NULL
Definition: c.h:229
HeapScanDesc heap_beginscan_strat ( Relation  relation,
Snapshot  snapshot,
int  nkeys,
ScanKey  key,
bool  allow_strat,
bool  allow_sync 
)

Definition at line 1412 of file heapam.c.

References heap_beginscan_internal().

Referenced by IndexBuildHeapRangeScan(), IndexCheckExclusion(), pgstat_heap(), systable_beginscan(), and validate_index_heapscan().

1415 {
1416  return heap_beginscan_internal(relation, snapshot, nkeys, key, NULL,
1417  allow_strat, allow_sync, true,
1418  false, false, false);
1419 }
static HeapScanDesc heap_beginscan_internal(Relation relation, Snapshot snapshot, int nkeys, ScanKey key, ParallelHeapScanDesc parallel_scan, bool allow_strat, bool allow_sync, bool allow_pagemode, bool is_bitmapscan, bool is_samplescan, bool temp_snap)
Definition: heapam.c:1440
#define NULL
Definition: c.h:229
HTSU_Result heap_delete ( Relation  relation,
ItemPointer  tid,
CommandId  cid,
Snapshot  crosscheck,
bool  wait,
HeapUpdateFailureData hufd 
)

Definition at line 3014 of file heapam.c.

References Assert, buffer, BUFFER_LOCK_EXCLUSIVE, BUFFER_LOCK_UNLOCK, BufferGetBlockNumber(), BufferGetPage, CacheInvalidateHeapTuple(), CheckForSerializableConflictIn(), HeapUpdateFailureData::cmax, compute_infobits(), compute_new_xmax_infomask(), HeapUpdateFailureData::ctid, DoesMultiXactIdConflict(), END_CRIT_SECTION, ereport, errcode(), errmsg(), ERROR, ExtractReplicaIdentity(), xl_heap_delete::flags, GetCurrentTransactionId(), heap_acquire_tuplock(), heap_freetuple(), HEAP_KEYS_UPDATED, HEAP_MOVED, HEAP_XMAX_BITS, HEAP_XMAX_INVALID, HEAP_XMAX_IS_LOCKED_ONLY, HEAP_XMAX_IS_MULTI, HeapTupleBeingUpdated, HeapTupleHasExternal, HeapTupleHeaderAdjustCmax(), HeapTupleHeaderClearHotUpdated, HeapTupleHeaderGetCmax(), HeapTupleHeaderGetRawXmax, HeapTupleHeaderGetUpdateXid, HeapTupleHeaderIsOnlyLocked(), HeapTupleHeaderSetCmax, HeapTupleHeaderSetXmax, HeapTupleInvisible, HeapTupleMayBeUpdated, HeapTupleSatisfiesUpdate(), HeapTupleSatisfiesVisibility, HeapTupleSelfUpdated, HeapTupleUpdated, xl_heap_delete::infobits_set, InvalidBuffer, InvalidCommandId, InvalidSnapshot, IsInParallelMode(), ItemIdGetLength, ItemIdIsNormal, ItemPointerGetBlockNumber, ItemPointerGetOffsetNumber, ItemPointerIsValid, LockBuffer(), LockTupleExclusive, LockWaitBlock, log_heap_new_cid(), MarkBufferDirty(), MultiXactIdSetOldestMember(), MultiXactIdWait(), MultiXactStatusUpdate, NULL, xl_heap_delete::offnum, PageClearAllVisible, PageGetItem, PageGetItemId, PageIsAllVisible, PageSetLSN, PageSetPrunable, pgstat_count_heap_delete(), RelationData::rd_rel, ReadBuffer(), REGBUF_STANDARD, RelationGetRelid, RelationIsAccessibleInLogicalDecoding, RelationNeedsWAL, ReleaseBuffer(), RELKIND_MATVIEW, RELKIND_RELATION, REPLICA_IDENTITY_FULL, result, SizeOfHeapDelete, SizeOfHeapHeader, SizeofHeapTupleHeader, START_CRIT_SECTION, HeapTupleHeaderData::t_ctid, HeapTupleData::t_data, xl_heap_header::t_hoff, HeapTupleHeaderData::t_hoff, xl_heap_header::t_infomask, HeapTupleHeaderData::t_infomask, xl_heap_header::t_infomask2, HeapTupleHeaderData::t_infomask2, HeapTupleData::t_len, HeapTupleData::t_self, HeapTupleData::t_tableOid, toast_delete(), TransactionIdEquals, TransactionIdIsCurrentTransactionId(), UnlockReleaseBuffer(), UnlockTupleTuplock, UpdateXmaxHintBits(), visibilitymap_clear(), visibilitymap_pin(), VISIBILITYMAP_VALID_BITS, XactLockTableWait(), XLH_DELETE_ALL_VISIBLE_CLEARED, XLH_DELETE_CONTAINS_OLD_KEY, XLH_DELETE_CONTAINS_OLD_TUPLE, XLOG_HEAP_DELETE, XLOG_INCLUDE_ORIGIN, XLogBeginInsert(), XLogInsert(), XLogRegisterBuffer(), XLogRegisterData(), XLogSetRecordFlags(), XLTW_Delete, HeapUpdateFailureData::xmax, xl_heap_delete::xmax, and xmax_infomask_changed().

Referenced by ExecDelete(), and simple_heap_delete().

3017 {
3020  ItemId lp;
3021  HeapTupleData tp;
3022  Page page;
3023  BlockNumber block;
3024  Buffer buffer;
3025  Buffer vmbuffer = InvalidBuffer;
3026  TransactionId new_xmax;
3027  uint16 new_infomask,
3028  new_infomask2;
3029  bool have_tuple_lock = false;
3030  bool iscombo;
3031  bool all_visible_cleared = false;
3032  HeapTuple old_key_tuple = NULL; /* replica identity of the tuple */
3033  bool old_key_copied = false;
3034 
3035  Assert(ItemPointerIsValid(tid));
3036 
3037  /*
3038  * Forbid this during a parallel operation, lest it allocate a combocid.
3039  * Other workers might need that combocid for visibility checks, and we
3040  * have no provision for broadcasting it to them.
3041  */
3042  if (IsInParallelMode())
3043  ereport(ERROR,
3044  (errcode(ERRCODE_INVALID_TRANSACTION_STATE),
3045  errmsg("cannot delete tuples during a parallel operation")));
3046 
3047  block = ItemPointerGetBlockNumber(tid);
3048  buffer = ReadBuffer(relation, block);
3049  page = BufferGetPage(buffer);
3050 
3051  /*
3052  * Before locking the buffer, pin the visibility map page if it appears to
3053  * be necessary. Since we haven't got the lock yet, someone else might be
3054  * in the middle of changing this, so we'll need to recheck after we have
3055  * the lock.
3056  */
3057  if (PageIsAllVisible(page))
3058  visibilitymap_pin(relation, block, &vmbuffer);
3059 
3061 
3062  /*
3063  * If we didn't pin the visibility map page and the page has become all
3064  * visible while we were busy locking the buffer, we'll have to unlock and
3065  * re-lock, to avoid holding the buffer lock across an I/O. That's a bit
3066  * unfortunate, but hopefully shouldn't happen often.
3067  */
3068  if (vmbuffer == InvalidBuffer && PageIsAllVisible(page))
3069  {
3070  LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
3071  visibilitymap_pin(relation, block, &vmbuffer);
3073  }
3074 
3075  lp = PageGetItemId(page, ItemPointerGetOffsetNumber(tid));
3076  Assert(ItemIdIsNormal(lp));
3077 
3078  tp.t_tableOid = RelationGetRelid(relation);
3079  tp.t_data = (HeapTupleHeader) PageGetItem(page, lp);
3080  tp.t_len = ItemIdGetLength(lp);
3081  tp.t_self = *tid;
3082 
3083 l1:
3084  result = HeapTupleSatisfiesUpdate(&tp, cid, buffer);
3085 
3086  if (result == HeapTupleInvisible)
3087  {
3088  UnlockReleaseBuffer(buffer);
3089  ereport(ERROR,
3090  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
3091  errmsg("attempted to delete invisible tuple")));
3092  }
3093  else if (result == HeapTupleBeingUpdated && wait)
3094  {
3095  TransactionId xwait;
3096  uint16 infomask;
3097 
3098  /* must copy state data before unlocking buffer */
3099  xwait = HeapTupleHeaderGetRawXmax(tp.t_data);
3100  infomask = tp.t_data->t_infomask;
3101 
3102  /*
3103  * Sleep until concurrent transaction ends -- except when there's a
3104  * single locker and it's our own transaction. Note we don't care
3105  * which lock mode the locker has, because we need the strongest one.
3106  *
3107  * Before sleeping, we need to acquire tuple lock to establish our
3108  * priority for the tuple (see heap_lock_tuple). LockTuple will
3109  * release us when we are next-in-line for the tuple.
3110  *
3111  * If we are forced to "start over" below, we keep the tuple lock;
3112  * this arranges that we stay at the head of the line while rechecking
3113  * tuple state.
3114  */
3115  if (infomask & HEAP_XMAX_IS_MULTI)
3116  {
3117  /* wait for multixact */
3118  if (DoesMultiXactIdConflict((MultiXactId) xwait, infomask,
3120  {
3121  LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
3122 
3123  /* acquire tuple lock, if necessary */
3125  LockWaitBlock, &have_tuple_lock);
3126 
3127  /* wait for multixact */
3129  relation, &(tp.t_self), XLTW_Delete,
3130  NULL);
3132 
3133  /*
3134  * If xwait had just locked the tuple then some other xact
3135  * could update this tuple before we get to this point. Check
3136  * for xmax change, and start over if so.
3137  */
3138  if (xmax_infomask_changed(tp.t_data->t_infomask, infomask) ||
3140  xwait))
3141  goto l1;
3142  }
3143 
3144  /*
3145  * You might think the multixact is necessarily done here, but not
3146  * so: it could have surviving members, namely our own xact or
3147  * other subxacts of this backend. It is legal for us to delete
3148  * the tuple in either case, however (the latter case is
3149  * essentially a situation of upgrading our former shared lock to
3150  * exclusive). We don't bother changing the on-disk hint bits
3151  * since we are about to overwrite the xmax altogether.
3152  */
3153  }
3154  else if (!TransactionIdIsCurrentTransactionId(xwait))
3155  {
3156  /*
3157  * Wait for regular transaction to end; but first, acquire tuple
3158  * lock.
3159  */
3160  LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
3162  LockWaitBlock, &have_tuple_lock);
3163  XactLockTableWait(xwait, relation, &(tp.t_self), XLTW_Delete);
3165 
3166  /*
3167  * xwait is done, but if xwait had just locked the tuple then some
3168  * other xact could update this tuple before we get to this point.
3169  * Check for xmax change, and start over if so.
3170  */
3171  if (xmax_infomask_changed(tp.t_data->t_infomask, infomask) ||
3173  xwait))
3174  goto l1;
3175 
3176  /* Otherwise check if it committed or aborted */
3177  UpdateXmaxHintBits(tp.t_data, buffer, xwait);
3178  }
3179 
3180  /*
3181  * We may overwrite if previous xmax aborted, or if it committed but
3182  * only locked the tuple without updating it.
3183  */
3184  if ((tp.t_data->t_infomask & HEAP_XMAX_INVALID) ||
3187  result = HeapTupleMayBeUpdated;
3188  else
3189  result = HeapTupleUpdated;
3190  }
3191 
3192  if (crosscheck != InvalidSnapshot && result == HeapTupleMayBeUpdated)
3193  {
3194  /* Perform additional check for transaction-snapshot mode RI updates */
3195  if (!HeapTupleSatisfiesVisibility(&tp, crosscheck, buffer))
3196  result = HeapTupleUpdated;
3197  }
3198 
3199  if (result != HeapTupleMayBeUpdated)
3200  {
3201  Assert(result == HeapTupleSelfUpdated ||
3202  result == HeapTupleUpdated ||
3203  result == HeapTupleBeingUpdated);
3205  hufd->ctid = tp.t_data->t_ctid;
3207  if (result == HeapTupleSelfUpdated)
3208  hufd->cmax = HeapTupleHeaderGetCmax(tp.t_data);
3209  else
3210  hufd->cmax = InvalidCommandId;
3211  UnlockReleaseBuffer(buffer);
3212  if (have_tuple_lock)
3213  UnlockTupleTuplock(relation, &(tp.t_self), LockTupleExclusive);
3214  if (vmbuffer != InvalidBuffer)
3215  ReleaseBuffer(vmbuffer);
3216  return result;
3217  }
3218 
3219  /*
3220  * We're about to do the actual delete -- check for conflict first, to
3221  * avoid possibly having to roll back work we've just done.
3222  *
3223  * This is safe without a recheck as long as there is no possibility of
3224  * another process scanning the page between this check and the delete
3225  * being visible to the scan (i.e., an exclusive buffer content lock is
3226  * continuously held from this point until the tuple delete is visible).
3227  */
3228  CheckForSerializableConflictIn(relation, &tp, buffer);
3229 
3230  /* replace cid with a combo cid if necessary */
3231  HeapTupleHeaderAdjustCmax(tp.t_data, &cid, &iscombo);
3232 
3233  /*
3234  * Compute replica identity tuple before entering the critical section so
3235  * we don't PANIC upon a memory allocation failure.
3236  */
3237  old_key_tuple = ExtractReplicaIdentity(relation, &tp, true, &old_key_copied);
3238 
3239  /*
3240  * If this is the first possibly-multixact-able operation in the current
3241  * transaction, set my per-backend OldestMemberMXactId setting. We can be
3242  * certain that the transaction will never become a member of any older
3243  * MultiXactIds than that. (We have to do this even if we end up just
3244  * using our own TransactionId below, since some other backend could
3245  * incorporate our XID into a MultiXact immediately afterwards.)
3246  */
3248 
3251  xid, LockTupleExclusive, true,
3252  &new_xmax, &new_infomask, &new_infomask2);
3253 
3255 
3256  /*
3257  * If this transaction commits, the tuple will become DEAD sooner or
3258  * later. Set flag that this page is a candidate for pruning once our xid
3259  * falls below the OldestXmin horizon. If the transaction finally aborts,
3260  * the subsequent page pruning will be a no-op and the hint will be
3261  * cleared.
3262  */
3263  PageSetPrunable(page, xid);
3264 
3265  if (PageIsAllVisible(page))
3266  {
3267  all_visible_cleared = true;
3268  PageClearAllVisible(page);
3269  visibilitymap_clear(relation, BufferGetBlockNumber(buffer),
3270  vmbuffer, VISIBILITYMAP_VALID_BITS);
3271  }
3272 
3273  /* store transaction information of xact deleting the tuple */
3276  tp.t_data->t_infomask |= new_infomask;
3277  tp.t_data->t_infomask2 |= new_infomask2;
3279  HeapTupleHeaderSetXmax(tp.t_data, new_xmax);
3280  HeapTupleHeaderSetCmax(tp.t_data, cid, iscombo);
3281  /* Make sure there is no forward chain link in t_ctid */
3282  tp.t_data->t_ctid = tp.t_self;
3283 
3284  MarkBufferDirty(buffer);
3285 
3286  /*
3287  * XLOG stuff
3288  *
3289  * NB: heap_abort_speculative() uses the same xlog record and replay
3290  * routines.
3291  */
3292  if (RelationNeedsWAL(relation))
3293  {
3294  xl_heap_delete xlrec;
3295  XLogRecPtr recptr;
3296 
3297  /* For logical decode we need combocids to properly decode the catalog */
3299  log_heap_new_cid(relation, &tp);
3300 
3301  xlrec.flags = all_visible_cleared ? XLH_DELETE_ALL_VISIBLE_CLEARED : 0;
3303  tp.t_data->t_infomask2);
3305  xlrec.xmax = new_xmax;
3306 
3307  if (old_key_tuple != NULL)
3308  {
3309  if (relation->rd_rel->relreplident == REPLICA_IDENTITY_FULL)
3311  else
3313  }
3314 
3315  XLogBeginInsert();
3316  XLogRegisterData((char *) &xlrec, SizeOfHeapDelete);
3317 
3318  XLogRegisterBuffer(0, buffer, REGBUF_STANDARD);
3319 
3320  /*
3321  * Log replica identity of the deleted tuple if there is one
3322  */
3323  if (old_key_tuple != NULL)
3324  {
3325  xl_heap_header xlhdr;
3326 
3327  xlhdr.t_infomask2 = old_key_tuple->t_data->t_infomask2;
3328  xlhdr.t_infomask = old_key_tuple->t_data->t_infomask;
3329  xlhdr.t_hoff = old_key_tuple->t_data->t_hoff;
3330 
3331  XLogRegisterData((char *) &xlhdr, SizeOfHeapHeader);
3332  XLogRegisterData((char *) old_key_tuple->t_data
3334  old_key_tuple->t_len
3336  }
3337 
3338  /* filtering by origin on a row level is much more efficient */
3340 
3341  recptr = XLogInsert(RM_HEAP_ID, XLOG_HEAP_DELETE);
3342 
3343  PageSetLSN(page, recptr);
3344  }
3345 
3346  END_CRIT_SECTION();
3347 
3348  LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
3349 
3350  if (vmbuffer != InvalidBuffer)
3351  ReleaseBuffer(vmbuffer);
3352 
3353  /*
3354  * If the tuple has toasted out-of-line attributes, we need to delete
3355  * those items too. We have to do this before releasing the buffer
3356  * because we need to look at the contents of the tuple, but it's OK to
3357  * release the content lock on the buffer first.
3358  */
3359  if (relation->rd_rel->relkind != RELKIND_RELATION &&
3360  relation->rd_rel->relkind != RELKIND_MATVIEW)
3361  {
3362  /* toast table entries should never be recursively toasted */
3364  }
3365  else if (HeapTupleHasExternal(&tp))
3366  toast_delete(relation, &tp, false);
3367 
3368  /*
3369  * Mark tuple for invalidation from system caches at next command
3370  * boundary. We have to do this before releasing the buffer because we
3371  * need to look at the contents of the tuple.
3372  */
3373  CacheInvalidateHeapTuple(relation, &tp, NULL);
3374 
3375  /* Now we can release the buffer */
3376  ReleaseBuffer(buffer);
3377 
3378  /*
3379  * Release the lmgr tuple lock, if we had it.
3380  */
3381  if (have_tuple_lock)
3382  UnlockTupleTuplock(relation, &(tp.t_self), LockTupleExclusive);
3383 
3384  pgstat_count_heap_delete(relation);
3385 
3386  if (old_key_tuple != NULL && old_key_copied)
3387  heap_freetuple(old_key_tuple);
3388 
3389  return HeapTupleMayBeUpdated;
3390 }
#define HeapTupleHeaderGetUpdateXid(tup)
Definition: htup_details.h:359
bool HeapTupleHeaderIsOnlyLocked(HeapTupleHeader tuple)
Definition: tqual.c:1585
#define ItemPointerIsValid(pointer)
Definition: itemptr.h:59
#define BUFFER_LOCK_UNLOCK
Definition: bufmgr.h:87
#define SizeofHeapTupleHeader
Definition: htup_details.h:170
static XLogRecPtr log_heap_new_cid(Relation relation, HeapTuple tup)
Definition: heapam.c:7748
#define HEAP_XMAX_BITS
Definition: htup_details.h:256
static uint8 compute_infobits(uint16 infomask, uint16 infomask2)
Definition: heapam.c:2955
void CacheInvalidateHeapTuple(Relation relation, HeapTuple tuple, HeapTuple newtuple)
Definition: inval.c:1087
#define TransactionIdEquals(id1, id2)
Definition: transam.h:43
#define PageIsAllVisible(page)
Definition: bufpage.h:382
uint32 TransactionId
Definition: c.h:397
HTSU_Result HeapTupleSatisfiesUpdate(HeapTuple htup, CommandId curcid, Buffer buffer)
Definition: tqual.c:460
bool TransactionIdIsCurrentTransactionId(TransactionId xid)
Definition: xact.c:773
void visibilitymap_pin(Relation rel, BlockNumber heapBlk, Buffer *buf)
void MarkBufferDirty(Buffer buffer)
Definition: bufmgr.c:1450
void XLogRegisterBuffer(uint8 block_id, Buffer buffer, uint8 flags)
Definition: xloginsert.c:213
HeapTupleHeaderData * HeapTupleHeader
Definition: htup.h:23
static bool xmax_infomask_changed(uint16 new_infomask, uint16 old_infomask)
Definition: heapam.c:2977
#define HeapTupleHeaderClearHotUpdated(tup)
Definition: htup_details.h:497
#define END_CRIT_SECTION()
Definition: miscadmin.h:132
#define RELKIND_MATVIEW
Definition: pg_class.h:165
#define InvalidBuffer
Definition: buf.h:25
uint16 t_infomask2
Definition: heapam_xlog.h:122
#define PageSetPrunable(page, xid)
Definition: bufpage.h:395
#define START_CRIT_SECTION()
Definition: miscadmin.h:130
int errcode(int sqlerrcode)
Definition: elog.c:575
#define XLOG_INCLUDE_ORIGIN
Definition: xlog.h:192
return result
Definition: formatting.c:1618
uint32 BlockNumber
Definition: block.h:31
void ReleaseBuffer(Buffer buffer)
Definition: bufmgr.c:3309
#define BUFFER_LOCK_EXCLUSIVE
Definition: bufmgr.h:89
Form_pg_class rd_rel
Definition: rel.h:114
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1374
void CheckForSerializableConflictIn(Relation relation, HeapTuple tuple, Buffer buffer)
Definition: predicate.c:4243
#define UnlockTupleTuplock(rel, tup, mode)
Definition: heapam.c:184
#define HeapTupleSatisfiesVisibility(tuple, snapshot, buffer)
Definition: tqual.h:45
OffsetNumber offnum
Definition: heapam_xlog.h:105
void MultiXactIdSetOldestMember(void)
Definition: multixact.c:623
#define VISIBILITYMAP_VALID_BITS
Definition: visibilitymap.h:28
HeapTupleHeader t_data
Definition: htup.h:67
#define HeapTupleHeaderGetRawXmax(tup)
Definition: htup_details.h:369
unsigned short uint16
Definition: c.h:267
#define ItemIdGetLength(itemId)
Definition: itemid.h:58
bool IsInParallelMode(void)
Definition: xact.c:913
bool visibilitymap_clear(Relation rel, BlockNumber heapBlk, Buffer buf, uint8 flags)
void UnlockReleaseBuffer(Buffer buffer)
Definition: bufmgr.c:3332
#define REPLICA_IDENTITY_FULL
Definition: pg_class.h:179
#define ERROR
Definition: elog.h:43
#define HEAP_XMAX_INVALID
Definition: htup_details.h:193
ItemPointerData t_ctid
Definition: htup_details.h:150
ItemPointerData t_self
Definition: htup.h:65
TransactionId xmax
Definition: heapam_xlog.h:104
static void MultiXactIdWait(MultiXactId multi, MultiXactStatus status, uint16 infomask, Relation rel, ItemPointer ctid, XLTW_Oper oper, int *remaining)
Definition: heapam.c:7164
TransactionId GetCurrentTransactionId(void)
Definition: xact.c:417
uint32 t_len
Definition: htup.h:64
#define SizeOfHeapDelete
Definition: heapam_xlog.h:110
#define REGBUF_STANDARD
Definition: xloginsert.h:35
#define XLH_DELETE_CONTAINS_OLD_KEY
Definition: heapam_xlog.h:94
CommandId cmax
Definition: heapam.h:72
#define HeapTupleHeaderSetXmax(tup, xid)
Definition: htup_details.h:374
HTSU_Result
Definition: snapshot.h:119
Oid t_tableOid
Definition: htup.h:66
void XLogSetRecordFlags(uint8 flags)
Definition: xloginsert.c:397
#define HeapTupleHeaderSetCmax(tup, cid, iscombo)
Definition: htup_details.h:399
#define BufferGetPage(buffer)
Definition: bufmgr.h:160
#define ereport(elevel, rest)
Definition: elog.h:122
static void compute_new_xmax_infomask(TransactionId xmax, uint16 old_infomask, uint16 old_infomask2, TransactionId add_to_xmax, LockTupleMode mode, bool is_update, TransactionId *result_xmax, uint16 *result_infomask, uint16 *result_infomask2)
Definition: heapam.c:5309
TransactionId xmax
Definition: heapam.h:71
#define PageGetItemId(page, offsetNumber)
Definition: bufpage.h:232
#define InvalidSnapshot
Definition: snapshot.h:25
void XLogRegisterData(char *data, int len)
Definition: xloginsert.c:323
XLogRecPtr XLogInsert(RmgrId rmid, uint8 info)
Definition: xloginsert.c:415
#define RelationIsAccessibleInLogicalDecoding(relation)
Definition: rel.h:560
#define InvalidCommandId
Definition: c.h:414
#define HEAP_XMAX_IS_LOCKED_ONLY(infomask)
Definition: htup_details.h:216
void LockBuffer(Buffer buffer, int mode)
Definition: bufmgr.c:3546
#define HEAP_KEYS_UPDATED
Definition: htup_details.h:264
#define HEAP_XMAX_IS_MULTI
Definition: htup_details.h:194
static void UpdateXmaxHintBits(HeapTupleHeader tuple, Buffer buffer, TransactionId xid)
Definition: heapam.c:2300
#define HEAP_MOVED
Definition: htup_details.h:202
static bool heap_acquire_tuplock(Relation relation, ItemPointer tid, LockTupleMode mode, LockWaitPolicy wait_policy, bool *have_tuple_lock)
Definition: heapam.c:5260
TransactionId MultiXactId
Definition: c.h:407
#define PageClearAllVisible(page)
Definition: bufpage.h:386
void XactLockTableWait(TransactionId xid, Relation rel, ItemPointer ctid, XLTW_Oper oper)
Definition: lmgr.c:554
#define NULL
Definition: c.h:229
uint64 XLogRecPtr
Definition: xlogdefs.h:21
#define Assert(condition)
Definition: c.h:675
uint8 infobits_set
Definition: heapam_xlog.h:106
static HeapTuple ExtractReplicaIdentity(Relation rel, HeapTuple tup, bool key_modified, bool *copy)
Definition: heapam.c:7824
CommandId HeapTupleHeaderGetCmax(HeapTupleHeader tup)
Definition: combocid.c:119
static bool DoesMultiXactIdConflict(MultiXactId multi, uint16 infomask, LockTupleMode lockmode)
Definition: heapam.c:6997
#define ItemIdIsNormal(itemId)
Definition: itemid.h:98
WalTimeSample buffer[LAG_TRACKER_BUFFER_SIZE]
Definition: walsender.c:207
Buffer ReadBuffer(Relation reln, BlockNumber blockNum)
Definition: bufmgr.c:594
uint16 t_infomask
Definition: heapam_xlog.h:123
#define ItemPointerGetOffsetNumber(pointer)
Definition: itemptr.h:76
#define RelationNeedsWAL(relation)
Definition: rel.h:506
void pgstat_count_heap_delete(Relation rel)
Definition: pgstat.c:1852
void HeapTupleHeaderAdjustCmax(HeapTupleHeader tup, CommandId *cmax, bool *iscombo)
Definition: combocid.c:154
BlockNumber BufferGetBlockNumber(Buffer buffer)
Definition: bufmgr.c:2605
#define HeapTupleHasExternal(tuple)
Definition: htup_details.h:674
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define XLH_DELETE_ALL_VISIBLE_CLEARED
Definition: heapam_xlog.h:92
void toast_delete(Relation rel, HeapTuple oldtup, bool is_speculative)
Definition: tuptoaster.c:464
ItemPointerData ctid
Definition: heapam.h:70
#define ItemPointerGetBlockNumber(pointer)
Definition: itemptr.h:66
#define RELKIND_RELATION
Definition: pg_class.h:160
void XLogBeginInsert(void)
Definition: xloginsert.c:120
#define PageSetLSN(page, lsn)
Definition: bufpage.h:365
int Buffer
Definition: buf.h:23
#define XLOG_HEAP_DELETE
Definition: heapam_xlog.h:33
#define RelationGetRelid(relation)
Definition: rel.h:417
#define PageGetItem(page, itemId)
Definition: bufpage.h:337
#define SizeOfHeapHeader
Definition: heapam_xlog.h:127
Pointer Page
Definition: bufpage.h:74
#define XLH_DELETE_CONTAINS_OLD_TUPLE
Definition: heapam_xlog.h:93
void heap_endscan ( HeapScanDesc  scan)

Definition at line 1581 of file heapam.c.

References BufferIsValid, FreeAccessStrategy(), pfree(), RelationDecrementReferenceCount(), ReleaseBuffer(), HeapScanDescData::rs_cbuf, HeapScanDescData::rs_key, HeapScanDescData::rs_rd, HeapScanDescData::rs_snapshot, HeapScanDescData::rs_strategy, HeapScanDescData::rs_temp_snap, and UnregisterSnapshot().

Referenced by AlterDomainNotNull(), AlterTableMoveAll(), AlterTableSpaceOptions(), ATRewriteTable(), boot_openrel(), check_db_file_conflict(), copy_heap_data(), CopyTo(), createdb(), DefineQueryRewrite(), do_autovacuum(), DropSetting(), DropTableSpace(), ExecEndBitmapHeapScan(), ExecEndSampleScan(), ExecEndSeqScan(), find_typed_table_dependencies(), get_database_list(), get_rel_oids(), get_subscription_list(), get_tables_to_cluster(), get_tablespace_name(), get_tablespace_oid(), GetAllTablesPublicationRelations(), getRelationsInNamespace(), gettype(), index_update_stats(), IndexBuildHeapRangeScan(), IndexCheckExclusion(), objectsInSchemaToOids(), pgrowlocks(), pgstat_collect_oids(), pgstat_heap(), ReindexMultipleTables(), RelationFindReplTupleSeq(), remove_dbtablespaces(), RemoveConversionById(), RemoveSubscriptionRel(), RenameTableSpace(), systable_endscan(), ThereIsAtLeastOneRole(), vac_truncate_clog(), validate_index_heapscan(), validateCheckConstraint(), validateDomainConstraint(), and validateForeignKeyConstraint().

1582 {
1583  /* Note: no locking manipulations needed */
1584 
1585  /*
1586  * unpin scan buffers
1587  */
1588  if (BufferIsValid(scan->rs_cbuf))
1589  ReleaseBuffer(scan->rs_cbuf);
1590 
1591  /*
1592  * decrement relation reference count and free scan descriptor storage
1593  */
1595 
1596  if (scan->rs_key)
1597  pfree(scan->rs_key);
1598 
1599  if (scan->rs_strategy != NULL)
1601 
1602  if (scan->rs_temp_snap)
1604 
1605  pfree(scan);
1606 }
void ReleaseBuffer(Buffer buffer)
Definition: bufmgr.c:3309
void pfree(void *pointer)
Definition: mcxt.c:950
void RelationDecrementReferenceCount(Relation rel)
Definition: relcache.c:2136
Snapshot rs_snapshot
Definition: relscan.h:48
void UnregisterSnapshot(Snapshot snapshot)
Definition: snapmgr.c:900
bool rs_temp_snap
Definition: relscan.h:56
BufferAccessStrategy rs_strategy
Definition: relscan.h:63
Relation rs_rd
Definition: relscan.h:47
Buffer rs_cbuf
Definition: relscan.h:70
void FreeAccessStrategy(BufferAccessStrategy strategy)
Definition: freelist.c:580
#define NULL
Definition: c.h:229
#define BufferIsValid(bufnum)
Definition: bufmgr.h:114
ScanKey rs_key
Definition: relscan.h:50
bool heap_fetch ( Relation  relation,
Snapshot  snapshot,
HeapTuple  tuple,
Buffer userbuf,
bool  keep_buf,
Relation  stats_relation 
)

Definition at line 1865 of file heapam.c.

References buffer, BUFFER_LOCK_SHARE, BUFFER_LOCK_UNLOCK, BufferGetPage, CheckForSerializableConflictOut(), HeapTupleSatisfiesVisibility, InvalidBuffer, ItemIdGetLength, ItemIdIsNormal, ItemPointerGetBlockNumber, ItemPointerGetOffsetNumber, LockBuffer(), NULL, PageGetItem, PageGetItemId, PageGetMaxOffsetNumber, pgstat_count_heap_fetch, PredicateLockTuple(), ReadBuffer(), RelationGetRelid, ReleaseBuffer(), HeapTupleData::t_data, HeapTupleData::t_len, HeapTupleData::t_self, HeapTupleData::t_tableOid, and TestForOldSnapshot().

Referenced by AfterTriggerExecute(), EvalPlanQualFetch(), EvalPlanQualFetchRowMarks(), ExecCheckTIDVisible(), ExecDelete(), ExecLockRows(), heap_lock_updated_tuple_rec(), and TidNext().

1871 {
1872  ItemPointer tid = &(tuple->t_self);
1873  ItemId lp;
1874  Buffer buffer;
1875  Page page;
1876  OffsetNumber offnum;
1877  bool valid;
1878 
1879  /*
1880  * Fetch and pin the appropriate page of the relation.
1881  */
1882  buffer = ReadBuffer(relation, ItemPointerGetBlockNumber(tid));
1883 
1884  /*
1885  * Need share lock on buffer to examine tuple commit status.
1886  */
1887  LockBuffer(buffer, BUFFER_LOCK_SHARE);
1888  page = BufferGetPage(buffer);
1889  TestForOldSnapshot(snapshot, relation, page);
1890 
1891  /*
1892  * We'd better check for out-of-range offnum in case of VACUUM since the
1893  * TID was obtained.
1894  */
1895  offnum = ItemPointerGetOffsetNumber(tid);
1896  if (offnum < FirstOffsetNumber || offnum > PageGetMaxOffsetNumber(page))
1897  {
1898  LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
1899  if (keep_buf)
1900  *userbuf = buffer;
1901  else
1902  {
1903  ReleaseBuffer(buffer);
1904  *userbuf = InvalidBuffer;
1905  }
1906  tuple->t_data = NULL;
1907  return false;
1908  }
1909 
1910  /*
1911  * get the item line pointer corresponding to the requested tid
1912  */
1913  lp = PageGetItemId(page, offnum);
1914 
1915  /*
1916  * Must check for deleted tuple.
1917  */
1918  if (!ItemIdIsNormal(lp))
1919  {
1920  LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
1921  if (keep_buf)
1922  *userbuf = buffer;
1923  else
1924  {
1925  ReleaseBuffer(buffer);
1926  *userbuf = InvalidBuffer;
1927  }
1928  tuple->t_data = NULL;
1929  return false;
1930  }
1931 
1932  /*
1933  * fill in *tuple fields
1934  */
1935  tuple->t_data = (HeapTupleHeader) PageGetItem(page, lp);
1936  tuple->t_len = ItemIdGetLength(lp);
1937  tuple->t_tableOid = RelationGetRelid(relation);
1938 
1939  /*
1940  * check time qualification of tuple, then release lock
1941  */
1942  valid = HeapTupleSatisfiesVisibility(tuple, snapshot, buffer);
1943 
1944  if (valid)
1945  PredicateLockTuple(relation, tuple, snapshot);
1946 
1947  CheckForSerializableConflictOut(valid, relation, tuple, buffer, snapshot);
1948 
1949  LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
1950 
1951  if (valid)
1952  {
1953  /*
1954  * All checks passed, so return the tuple as valid. Caller is now
1955  * responsible for releasing the buffer.
1956  */
1957  *userbuf = buffer;
1958 
1959  /* Count the successful fetch against appropriate rel, if any */
1960  if (stats_relation != NULL)
1961  pgstat_count_heap_fetch(stats_relation);
1962 
1963  return true;
1964  }
1965 
1966  /* Tuple failed time qual, but maybe caller wants to see it anyway. */
1967  if (keep_buf)
1968  *userbuf = buffer;
1969  else
1970  {
1971  ReleaseBuffer(buffer);
1972  *userbuf = InvalidBuffer;
1973  }
1974 
1975  return false;
1976 }
#define BUFFER_LOCK_UNLOCK
Definition: bufmgr.h:87
static void TestForOldSnapshot(Snapshot snapshot, Relation relation, Page page)
Definition: bufmgr.h:265
HeapTupleHeaderData * HeapTupleHeader
Definition: htup.h:23
#define InvalidBuffer
Definition: buf.h:25
void ReleaseBuffer(Buffer buffer)
Definition: bufmgr.c:3309
#define PageGetMaxOffsetNumber(page)
Definition: bufpage.h:354
void CheckForSerializableConflictOut(bool visible, Relation relation, HeapTuple tuple, Buffer buffer, Snapshot snapshot)
Definition: predicate.c:3862
#define HeapTupleSatisfiesVisibility(tuple, snapshot, buffer)
Definition: tqual.h:45
uint16 OffsetNumber
Definition: off.h:24
HeapTupleHeader t_data
Definition: htup.h:67
#define ItemIdGetLength(itemId)
Definition: itemid.h:58
ItemPointerData t_self
Definition: htup.h:65
#define pgstat_count_heap_fetch(rel)
Definition: pgstat.h:1231
uint32 t_len
Definition: htup.h:64
Oid t_tableOid
Definition: htup.h:66
#define BufferGetPage(buffer)
Definition: bufmgr.h:160
#define PageGetItemId(page, offsetNumber)
Definition: bufpage.h:232
void LockBuffer(Buffer buffer, int mode)
Definition: bufmgr.c:3546
#define NULL
Definition: c.h:229
#define ItemIdIsNormal(itemId)
Definition: itemid.h:98
WalTimeSample buffer[LAG_TRACKER_BUFFER_SIZE]
Definition: walsender.c:207
Buffer ReadBuffer(Relation reln, BlockNumber blockNum)
Definition: bufmgr.c:594
#define ItemPointerGetOffsetNumber(pointer)
Definition: itemptr.h:76
void PredicateLockTuple(Relation relation, HeapTuple tuple, Snapshot snapshot)
Definition: predicate.c:2460
#define BUFFER_LOCK_SHARE
Definition: bufmgr.h:88
#define ItemPointerGetBlockNumber(pointer)
Definition: itemptr.h:66
int Buffer
Definition: buf.h:23
#define RelationGetRelid(relation)
Definition: rel.h:417
#define PageGetItem(page, itemId)
Definition: bufpage.h:337
Pointer Page
Definition: bufpage.h:74
void heap_finish_speculative ( Relation  relation,
HeapTuple  tuple 
)

Definition at line 6017 of file heapam.c.

References Assert, buffer, BUFFER_LOCK_EXCLUSIVE, BufferGetPage, elog, END_CRIT_SECTION, ERROR, HeapTupleHeaderIsSpeculative, ItemIdIsNormal, ItemPointerGetBlockNumber, ItemPointerGetOffsetNumber, LockBuffer(), MarkBufferDirty(), MaxOffsetNumber, NULL, xl_heap_confirm::offnum, PageGetItem, PageGetItemId, PageGetMaxOffsetNumber, PageSetLSN, ReadBuffer(), REGBUF_STANDARD, RelationNeedsWAL, SizeOfHeapConfirm, SpecTokenOffsetNumber, START_CRIT_SECTION, StaticAssertStmt, HeapTupleHeaderData::t_ctid, HeapTupleData::t_data, HeapTupleData::t_self, UnlockReleaseBuffer(), XLOG_HEAP_CONFIRM, XLOG_INCLUDE_ORIGIN, XLogBeginInsert(), XLogInsert(), XLogRegisterBuffer(), XLogRegisterData(), and XLogSetRecordFlags().

Referenced by ExecInsert().

6018 {
6019  Buffer buffer;
6020  Page page;
6021  OffsetNumber offnum;
6022  ItemId lp = NULL;
6023  HeapTupleHeader htup;
6024 
6025  buffer = ReadBuffer(relation, ItemPointerGetBlockNumber(&(tuple->t_self)));
6027  page = (Page) BufferGetPage(buffer);
6028 
6029  offnum = ItemPointerGetOffsetNumber(&(tuple->t_self));
6030  if (PageGetMaxOffsetNumber(page) >= offnum)
6031  lp = PageGetItemId(page, offnum);
6032 
6033  if (PageGetMaxOffsetNumber(page) < offnum || !ItemIdIsNormal(lp))
6034  elog(ERROR, "invalid lp");
6035 
6036  htup = (HeapTupleHeader) PageGetItem(page, lp);
6037 
6038  /* SpecTokenOffsetNumber should be distinguishable from any real offset */
6040  "invalid speculative token constant");
6041 
6042  /* NO EREPORT(ERROR) from here till changes are logged */
6044 
6046 
6047  MarkBufferDirty(buffer);
6048 
6049  /*
6050  * Replace the speculative insertion token with a real t_ctid, pointing to
6051  * itself like it does on regular tuples.
6052  */
6053  htup->t_ctid = tuple->t_self;
6054 
6055  /* XLOG stuff */
6056  if (RelationNeedsWAL(relation))
6057  {
6058  xl_heap_confirm xlrec;
6059  XLogRecPtr recptr;
6060 
6061  xlrec.offnum = ItemPointerGetOffsetNumber(&tuple->t_self);
6062 
6063  XLogBeginInsert();
6064 
6065  /* We want the same filtering on this as on a plain insert */
6067 
6068  XLogRegisterData((char *) &xlrec, SizeOfHeapConfirm);
6069  XLogRegisterBuffer(0, buffer, REGBUF_STANDARD);
6070 
6071  recptr = XLogInsert(RM_HEAP_ID, XLOG_HEAP_CONFIRM);
6072 
6073  PageSetLSN(page, recptr);
6074  }
6075 
6076  END_CRIT_SECTION();
6077 
6078  UnlockReleaseBuffer(buffer);
6079 }
OffsetNumber offnum
Definition: heapam_xlog.h:274
void MarkBufferDirty(Buffer buffer)
Definition: bufmgr.c:1450
void XLogRegisterBuffer(uint8 block_id, Buffer buffer, uint8 flags)
Definition: xloginsert.c:213
HeapTupleHeaderData * HeapTupleHeader
Definition: htup.h:23
#define MaxOffsetNumber
Definition: off.h:28
#define END_CRIT_SECTION()
Definition: miscadmin.h:132
#define HeapTupleHeaderIsSpeculative(tup)
Definition: htup_details.h:423
#define START_CRIT_SECTION()
Definition: miscadmin.h:130
#define XLOG_INCLUDE_ORIGIN
Definition: xlog.h:192
#define BUFFER_LOCK_EXCLUSIVE
Definition: bufmgr.h:89
#define PageGetMaxOffsetNumber(page)
Definition: bufpage.h:354
uint16 OffsetNumber
Definition: off.h:24
HeapTupleHeader t_data
Definition: htup.h:67
#define StaticAssertStmt(condition, errmessage)
Definition: c.h:757
#define SpecTokenOffsetNumber
Definition: htup_details.h:285
void UnlockReleaseBuffer(Buffer buffer)
Definition: bufmgr.c:3332
#define ERROR
Definition: elog.h:43
ItemPointerData t_ctid
Definition: htup_details.h:150
ItemPointerData t_self
Definition: htup.h:65
#define REGBUF_STANDARD
Definition: xloginsert.h:35
void XLogSetRecordFlags(uint8 flags)
Definition: xloginsert.c:397
#define BufferGetPage(buffer)
Definition: bufmgr.h:160
#define SizeOfHeapConfirm
Definition: heapam_xlog.h:277
#define PageGetItemId(page, offsetNumber)
Definition: bufpage.h:232
void XLogRegisterData(char *data, int len)
Definition: xloginsert.c:323
XLogRecPtr XLogInsert(RmgrId rmid, uint8 info)
Definition: xloginsert.c:415
void LockBuffer(Buffer buffer, int mode)
Definition: bufmgr.c:3546
#define NULL
Definition: c.h:229
uint64 XLogRecPtr
Definition: xlogdefs.h:21
#define Assert(condition)
Definition: c.h:675
#define ItemIdIsNormal(itemId)
Definition: itemid.h:98
WalTimeSample buffer[LAG_TRACKER_BUFFER_SIZE]
Definition: walsender.c:207
Buffer ReadBuffer(Relation reln, BlockNumber blockNum)
Definition: bufmgr.c:594
#define ItemPointerGetOffsetNumber(pointer)
Definition: itemptr.h:76
#define RelationNeedsWAL(relation)
Definition: rel.h:506
#define elog
Definition: elog.h:219
#define ItemPointerGetBlockNumber(pointer)
Definition: itemptr.h:66
void XLogBeginInsert(void)
Definition: xloginsert.c:120
#define PageSetLSN(page, lsn)
Definition: bufpage.h:365
int Buffer
Definition: buf.h:23
#define PageGetItem(page, itemId)
Definition: bufpage.h:337
Pointer Page
Definition: bufpage.h:74
#define XLOG_HEAP_CONFIRM
Definition: heapam_xlog.h:37
bool heap_freeze_tuple ( HeapTupleHeader  tuple,
TransactionId  cutoff_xid,
TransactionId  cutoff_multi 
)

Definition at line 6823 of file heapam.c.

References heap_execute_freeze_tuple(), and heap_prepare_freeze_tuple().

Referenced by rewrite_heap_tuple().

6825 {
6827  bool do_freeze;
6828  bool tuple_totally_frozen;
6829 
6830  do_freeze = heap_prepare_freeze_tuple(tuple, cutoff_xid, cutoff_multi,
6831  &frz, &tuple_totally_frozen);
6832 
6833  /*
6834  * Note that because this is not a WAL-logged operation, we don't need to
6835  * fill in the offset in the freeze record.
6836  */
6837 
6838  if (do_freeze)
6839  heap_execute_freeze_tuple(tuple, &frz);
6840  return do_freeze;
6841 }
void heap_execute_freeze_tuple(HeapTupleHeader tuple, xl_heap_freeze_tuple *frz)
Definition: heapam.c:6802
bool heap_prepare_freeze_tuple(HeapTupleHeader tuple, TransactionId cutoff_xid, TransactionId cutoff_multi, xl_heap_freeze_tuple *frz, bool *totally_frozen_p)
Definition: heapam.c:6624
void heap_get_latest_tid ( Relation  relation,
Snapshot  snapshot,
ItemPointer  tid 
)

Definition at line 2170 of file heapam.c.

References buffer, BUFFER_LOCK_SHARE, BufferGetPage, CheckForSerializableConflictOut(), elog, ERROR, HEAP_XMAX_INVALID, HeapTupleHeaderGetUpdateXid, HeapTupleHeaderGetXmin, HeapTupleHeaderIsOnlyLocked(), HeapTupleSatisfiesVisibility, InvalidTransactionId, ItemIdGetLength, ItemIdIsNormal, ItemPointerEquals(), ItemPointerGetBlockNumber, ItemPointerGetOffsetNumber, ItemPointerIsValid, LockBuffer(), PageGetItem, PageGetItemId, PageGetMaxOffsetNumber, ReadBuffer(), RelationGetNumberOfBlocks, RelationGetRelationName, RelationGetRelid, HeapTupleHeaderData::t_ctid, HeapTupleData::t_data, HeapTupleHeaderData::t_infomask, HeapTupleData::t_len, HeapTupleData::t_self, HeapTupleData::t_tableOid, TestForOldSnapshot(), TransactionIdEquals, TransactionIdIsValid, and UnlockReleaseBuffer().

Referenced by currtid_byrelname(), currtid_byreloid(), and TidNext().

2173 {
2174  BlockNumber blk;
2175  ItemPointerData ctid;
2176  TransactionId priorXmax;
2177 
2178  /* this is to avoid Assert failures on bad input */
2179  if (!ItemPointerIsValid(tid))
2180  return;
2181 
2182  /*
2183  * Since this can be called with user-supplied TID, don't trust the input
2184  * too much. (RelationGetNumberOfBlocks is an expensive check, so we
2185  * don't check t_ctid links again this way. Note that it would not do to
2186  * call it just once and save the result, either.)
2187  */
2188  blk = ItemPointerGetBlockNumber(tid);
2189  if (blk >= RelationGetNumberOfBlocks(relation))
2190  elog(ERROR, "block number %u is out of range for relation \"%s\"",
2191  blk, RelationGetRelationName(relation));
2192 
2193  /*
2194  * Loop to chase down t_ctid links. At top of loop, ctid is the tuple we
2195  * need to examine, and *tid is the TID we will return if ctid turns out
2196  * to be bogus.
2197  *
2198  * Note that we will loop until we reach the end of the t_ctid chain.
2199  * Depending on the snapshot passed, there might be at most one visible
2200  * version of the row, but we don't try to optimize for that.
2201  */
2202  ctid = *tid;
2203  priorXmax = InvalidTransactionId; /* cannot check first XMIN */
2204  for (;;)
2205  {
2206  Buffer buffer;
2207  Page page;
2208  OffsetNumber offnum;
2209  ItemId lp;
2210  HeapTupleData tp;
2211  bool valid;
2212 
2213  /*
2214  * Read, pin, and lock the page.
2215  */
2216  buffer = ReadBuffer(relation, ItemPointerGetBlockNumber(&ctid));
2217  LockBuffer(buffer, BUFFER_LOCK_SHARE);
2218  page = BufferGetPage(buffer);
2219  TestForOldSnapshot(snapshot, relation, page);
2220 
2221  /*
2222  * Check for bogus item number. This is not treated as an error
2223  * condition because it can happen while following a t_ctid link. We
2224  * just assume that the prior tid is OK and return it unchanged.
2225  */
2226  offnum = ItemPointerGetOffsetNumber(&ctid);
2227  if (offnum < FirstOffsetNumber || offnum > PageGetMaxOffsetNumber(page))
2228  {
2229  UnlockReleaseBuffer(buffer);
2230  break;
2231  }
2232  lp = PageGetItemId(page, offnum);
2233  if (!ItemIdIsNormal(lp))
2234  {
2235  UnlockReleaseBuffer(buffer);
2236  break;
2237  }
2238 
2239  /* OK to access the tuple */
2240  tp.t_self = ctid;
2241  tp.t_data = (HeapTupleHeader) PageGetItem(page, lp);
2242  tp.t_len = ItemIdGetLength(lp);
2243  tp.t_tableOid = RelationGetRelid(relation);
2244 
2245  /*
2246  * After following a t_ctid link, we might arrive at an unrelated
2247  * tuple. Check for XMIN match.
2248  */
2249  if (TransactionIdIsValid(priorXmax) &&
2251  {
2252  UnlockReleaseBuffer(buffer);
2253  break;
2254  }
2255 
2256  /*
2257  * Check time qualification of tuple; if visible, set it as the new
2258  * result candidate.
2259  */
2260  valid = HeapTupleSatisfiesVisibility(&tp, snapshot, buffer);
2261  CheckForSerializableConflictOut(valid, relation, &tp, buffer, snapshot);
2262  if (valid)
2263  *tid = ctid;
2264 
2265  /*
2266  * If there's a valid t_ctid link, follow it, else we're done.
2267  */
2268  if ((tp.t_data->t_infomask & HEAP_XMAX_INVALID) ||
2271  {
2272  UnlockReleaseBuffer(buffer);
2273  break;
2274  }
2275 
2276  ctid = tp.t_data->t_ctid;
2277  priorXmax = HeapTupleHeaderGetUpdateXid(tp.t_data);
2278  UnlockReleaseBuffer(buffer);
2279  } /* end of loop */
2280 }
#define HeapTupleHeaderGetUpdateXid(tup)
Definition: htup_details.h:359
bool HeapTupleHeaderIsOnlyLocked(HeapTupleHeader tuple)
Definition: tqual.c:1585
#define ItemPointerIsValid(pointer)
Definition: itemptr.h:59
static void TestForOldSnapshot(Snapshot snapshot, Relation relation, Page page)
Definition: bufmgr.h:265
#define TransactionIdEquals(id1, id2)
Definition: transam.h:43
uint32 TransactionId
Definition: c.h:397
HeapTupleHeaderData * HeapTupleHeader
Definition: htup.h:23
uint32 BlockNumber
Definition: block.h:31
#define PageGetMaxOffsetNumber(page)
Definition: bufpage.h:354
void CheckForSerializableConflictOut(bool visible, Relation relation, HeapTuple tuple, Buffer buffer, Snapshot snapshot)
Definition: predicate.c:3862
#define HeapTupleSatisfiesVisibility(tuple, snapshot, buffer)
Definition: tqual.h:45
uint16 OffsetNumber
Definition: off.h:24
HeapTupleHeader t_data
Definition: htup.h:67
#define ItemIdGetLength(itemId)
Definition: itemid.h:58
void UnlockReleaseBuffer(Buffer buffer)
Definition: bufmgr.c:3332
#define ERROR
Definition: elog.h:43
#define HEAP_XMAX_INVALID
Definition: htup_details.h:193
ItemPointerData t_ctid
Definition: htup_details.h:150
ItemPointerData t_self
Definition: htup.h:65
uint32 t_len
Definition: htup.h:64
#define InvalidTransactionId
Definition: transam.h:31
#define RelationGetRelationName(relation)
Definition: rel.h:437
Oid t_tableOid
Definition: htup.h:66
#define BufferGetPage(buffer)
Definition: bufmgr.h:160
#define PageGetItemId(page, offsetNumber)
Definition: bufpage.h:232
void LockBuffer(Buffer buffer, int mode)
Definition: bufmgr.c:3546
#define RelationGetNumberOfBlocks(reln)
Definition: bufmgr.h:199
#define ItemIdIsNormal(itemId)
Definition: itemid.h:98
WalTimeSample buffer[LAG_TRACKER_BUFFER_SIZE]
Definition: walsender.c:207
#define HeapTupleHeaderGetXmin(tup)
Definition: htup_details.h:307
Buffer ReadBuffer(Relation reln, BlockNumber blockNum)
Definition: bufmgr.c:594
#define ItemPointerGetOffsetNumber(pointer)
Definition: itemptr.h:76
bool ItemPointerEquals(ItemPointer pointer1, ItemPointer pointer2)
Definition: itemptr.c:29
#define BUFFER_LOCK_SHARE
Definition: bufmgr.h:88
#define elog
Definition: elog.h:219
#define ItemPointerGetBlockNumber(pointer)
Definition: itemptr.h:66
#define TransactionIdIsValid(xid)
Definition: transam.h:41
int Buffer
Definition: buf.h:23
#define RelationGetRelid(relation)
Definition: rel.h:417
#define PageGetItem(page, itemId)
Definition: bufpage.h:337
Pointer Page
Definition: bufpage.h:74
void heap_get_root_tuples ( Page  page,
OffsetNumber root_offsets 
)

Definition at line 744 of file pruneheap.c.

References Assert, FirstOffsetNumber, HeapTupleHeaderGetUpdateXid, HeapTupleHeaderGetXmin, HeapTupleHeaderIsHeapOnly, HeapTupleHeaderIsHotUpdated, InvalidTransactionId, ItemIdGetRedirect, ItemIdIsDead, ItemIdIsNormal, ItemIdIsRedirected, ItemIdIsUsed, ItemPointerGetOffsetNumber, MaxHeapTuplesPerPage, MemSet, OffsetNumberNext, PageGetItem, PageGetItemId, PageGetMaxOffsetNumber, HeapTupleHeaderData::t_ctid, TransactionIdEquals, and TransactionIdIsValid.

Referenced by IndexBuildHeapRangeScan(), and validate_index_heapscan().

745 {
746  OffsetNumber offnum,
747  maxoff;
748 
749  MemSet(root_offsets, 0, MaxHeapTuplesPerPage * sizeof(OffsetNumber));
750 
751  maxoff = PageGetMaxOffsetNumber(page);
752  for (offnum = FirstOffsetNumber; offnum <= maxoff; offnum = OffsetNumberNext(offnum))
753  {
754  ItemId lp = PageGetItemId(page, offnum);
755  HeapTupleHeader htup;
756  OffsetNumber nextoffnum;
757  TransactionId priorXmax;
758 
759  /* skip unused and dead items */
760  if (!ItemIdIsUsed(lp) || ItemIdIsDead(lp))
761  continue;
762 
763  if (ItemIdIsNormal(lp))
764  {
765  htup = (HeapTupleHeader) PageGetItem(page, lp);
766 
767  /*
768  * Check if this tuple is part of a HOT-chain rooted at some other
769  * tuple. If so, skip it for now; we'll process it when we find
770  * its root.
771  */
772  if (HeapTupleHeaderIsHeapOnly(htup))
773  continue;
774 
775  /*
776  * This is either a plain tuple or the root of a HOT-chain.
777  * Remember it in the mapping.
778  */
779  root_offsets[offnum - 1] = offnum;
780 
781  /* If it's not the start of a HOT-chain, we're done with it */
782  if (!HeapTupleHeaderIsHotUpdated(htup))
783  continue;
784 
785  /* Set up to scan the HOT-chain */
786  nextoffnum = ItemPointerGetOffsetNumber(&htup->t_ctid);
787  priorXmax = HeapTupleHeaderGetUpdateXid(htup);
788  }
789  else
790  {
791  /* Must be a redirect item. We do not set its root_offsets entry */
793  /* Set up to scan the HOT-chain */
794  nextoffnum = ItemIdGetRedirect(lp);
795  priorXmax = InvalidTransactionId;
796  }
797 
798  /*
799  * Now follow the HOT-chain and collect other tuples in the chain.
800  *
801  * Note: Even though this is a nested loop, the complexity of the
802  * function is O(N) because a tuple in the page should be visited not
803  * more than twice, once in the outer loop and once in HOT-chain
804  * chases.
805  */
806  for (;;)
807  {
808  lp = PageGetItemId(page, nextoffnum);
809 
810  /* Check for broken chains */
811  if (!ItemIdIsNormal(lp))
812  break;
813 
814  htup = (HeapTupleHeader) PageGetItem(page, lp);
815 
816  if (TransactionIdIsValid(priorXmax) &&
817  !TransactionIdEquals(priorXmax, HeapTupleHeaderGetXmin(htup)))
818  break;
819 
820  /* Remember the root line pointer for this item */
821  root_offsets[nextoffnum - 1] = offnum;
822 
823  /* Advance to next chain member, if any */
824  if (!HeapTupleHeaderIsHotUpdated(htup))
825  break;
826 
827  nextoffnum = ItemPointerGetOffsetNumber(&htup->t_ctid);
828  priorXmax = HeapTupleHeaderGetUpdateXid(htup);
829  }
830  }
831 }
#define HeapTupleHeaderGetUpdateXid(tup)
Definition: htup_details.h:359
#define ItemIdIsRedirected(itemId)
Definition: itemid.h:105
#define TransactionIdEquals(id1, id2)
Definition: transam.h:43
uint32 TransactionId
Definition: c.h:397
HeapTupleHeaderData * HeapTupleHeader
Definition: htup.h:23
#define ItemIdGetRedirect(itemId)
Definition: itemid.h:77
#define ItemIdIsUsed(itemId)
Definition: itemid.h:91
#define MaxHeapTuplesPerPage
Definition: htup_details.h:575
#define MemSet(start, val, len)
Definition: c.h:857
#define ItemIdIsDead(itemId)
Definition: itemid.h:112
#define PageGetMaxOffsetNumber(page)
Definition: bufpage.h:354
uint16 OffsetNumber
Definition: off.h:24
#define HeapTupleHeaderIsHeapOnly(tup)
Definition: htup_details.h:502
ItemPointerData t_ctid
Definition: htup_details.h:150
#define FirstOffsetNumber
Definition: off.h:27
#define InvalidTransactionId
Definition: transam.h:31
#define HeapTupleHeaderIsHotUpdated(tup)
Definition: htup_details.h:485
#define PageGetItemId(page, offsetNumber)
Definition: bufpage.h:232
#define Assert(condition)
Definition: c.h:675
#define ItemIdIsNormal(itemId)
Definition: itemid.h:98
#define HeapTupleHeaderGetXmin(tup)
Definition: htup_details.h:307
#define OffsetNumberNext(offsetNumber)
Definition: off.h:53
#define ItemPointerGetOffsetNumber(pointer)
Definition: itemptr.h:76
#define TransactionIdIsValid(xid)
Definition: transam.h:41
#define PageGetItem(page, itemId)
Definition: bufpage.h:337
HeapTuple heap_getnext ( HeapScanDesc  scan,
ScanDirection  direction 
)

Definition at line 1797 of file heapam.c.

References HEAPDEBUG_1, HEAPDEBUG_2, HEAPDEBUG_3, heapgettup(), heapgettup_pagemode(), NULL, pgstat_count_heap_getnext, HeapScanDescData::rs_ctup, HeapScanDescData::rs_key, HeapScanDescData::rs_nkeys, HeapScanDescData::rs_pageatatime, HeapScanDescData::rs_rd, and HeapTupleData::t_data.

Referenced by AlterDomainNotNull(), AlterTableMoveAll(), AlterTableSpaceOptions(), ATRewriteTable(), boot_openrel(), check_db_file_conflict(), copy_heap_data(), CopyTo(), createdb(), DefineQueryRewrite(), do_autovacuum(), DropSetting(), DropTableSpace(), find_typed_table_dependencies(), get_database_list(), get_rel_oids(), get_subscription_list(), get_tables_to_cluster(), get_tablespace_name(), get_tablespace_oid(), GetAllTablesPublicationRelations(), getRelationsInNamespace(), gettype(), index_update_stats(), IndexBuildHeapRangeScan(), IndexCheckExclusion(), objectsInSchemaToOids(), pgrowlocks(), pgstat_collect_oids(), pgstat_heap(), ReindexMultipleTables(), RelationFindReplTupleSeq(), remove_dbtablespaces(), RemoveConversionById(), RemoveSubscriptionRel(), RenameTableSpace(), SeqNext(), systable_getnext(), ThereIsAtLeastOneRole(), vac_truncate_clog(), validate_index_heapscan(), validateCheckConstraint(), validateDomainConstraint(), and validateForeignKeyConstraint().

1798 {
1799  /* Note: no locking manipulations needed */
1800 
1801  HEAPDEBUG_1; /* heap_getnext( info ) */
1802 
1803  if (scan->rs_pageatatime)
1804  heapgettup_pagemode(scan, direction,
1805  scan->rs_nkeys, scan->rs_key);
1806  else
1807  heapgettup(scan, direction, scan->rs_nkeys, scan->rs_key);
1808 
1809  if (scan->rs_ctup.t_data == NULL)
1810  {
1811  HEAPDEBUG_2; /* heap_getnext returning EOS */
1812  return NULL;
1813  }
1814 
1815  /*
1816  * if we get here it means we have a new current scan tuple, so point to
1817  * the proper return buffer and return the tuple.
1818  */
1819  HEAPDEBUG_3; /* heap_getnext returning tuple */
1820 
1822 
1823  return &(scan->rs_ctup);
1824 }
#define HEAPDEBUG_2
Definition: heapam.c:1791
HeapTupleData rs_ctup
Definition: relscan.h:68
HeapTupleHeader t_data
Definition: htup.h:67
bool rs_pageatatime
Definition: relscan.h:53
#define HEAPDEBUG_1
Definition: heapam.c:1790
static void heapgettup(HeapScanDesc scan, ScanDirection dir, int nkeys, ScanKey key)
Definition: heapam.c:482
Relation rs_rd
Definition: relscan.h:47
#define NULL
Definition: c.h:229
#define HEAPDEBUG_3
Definition: heapam.c:1792
#define pgstat_count_heap_getnext(rel)
Definition: pgstat.h:1226
static void heapgettup_pagemode(HeapScanDesc scan, ScanDirection dir, int nkeys, ScanKey key)
Definition: heapam.c:784
ScanKey rs_key
Definition: relscan.h:50
bool heap_hot_search ( ItemPointer  tid,
Relation  relation,
Snapshot  snapshot,
bool all_dead 
)

Definition at line 2142 of file heapam.c.

References buffer, BUFFER_LOCK_SHARE, BUFFER_LOCK_UNLOCK, heap_hot_search_buffer(), ItemPointerGetBlockNumber, LockBuffer(), ReadBuffer(), ReleaseBuffer(), and result.

Referenced by _bt_check_unique(), and unique_key_recheck().

2144 {
2145  bool result;
2146  Buffer buffer;
2147  HeapTupleData heapTuple;
2148 
2149  buffer = ReadBuffer(relation, ItemPointerGetBlockNumber(tid));
2150  LockBuffer(buffer, BUFFER_LOCK_SHARE);
2151  result = heap_hot_search_buffer(tid, relation, buffer, snapshot,
2152  &heapTuple, all_dead, true);
2153  LockBuffer(buffer, BUFFER_LOCK_UNLOCK);
2154  ReleaseBuffer(buffer);
2155  return result;
2156 }
#define BUFFER_LOCK_UNLOCK
Definition: bufmgr.h:87
return result
Definition: formatting.c:1618
void ReleaseBuffer(Buffer buffer)
Definition: bufmgr.c:3309
bool heap_hot_search_buffer(ItemPointer tid, Relation relation, Buffer buffer, Snapshot snapshot, HeapTuple heapTuple, bool *all_dead, bool first_call)
Definition: heapam.c:2000
void LockBuffer(Buffer buffer, int mode)
Definition: bufmgr.c:3546
WalTimeSample buffer[LAG_TRACKER_BUFFER_SIZE]
Definition: walsender.c:207
Buffer ReadBuffer(Relation reln, BlockNumber blockNum)
Definition: bufmgr.c:594
#define BUFFER_LOCK_SHARE
Definition: bufmgr.h:88
#define ItemPointerGetBlockNumber(pointer)
Definition: itemptr.h:66
int Buffer
Definition: buf.h:23
bool heap_hot_search_buffer ( ItemPointer  tid,
Relation  relation,
Buffer  buffer,
Snapshot  snapshot,
HeapTuple  heapTuple,
bool all_dead,
bool  first_call 
)

Definition at line 2000 of file heapam.c.

References Assert, BufferGetBlockNumber(), BufferGetPage, CheckForSerializableConflictOut(), HeapTupleHeaderGetUpdateXid, HeapTupleHeaderGetXmin, HeapTupleIsHeapOnly, HeapTupleIsHotUpdated, HeapTupleIsSurelyDead(), HeapTupleSatisfiesVisibility, InvalidTransactionId, ItemIdGetLength, ItemIdGetRedirect, ItemIdIsNormal, ItemIdIsRedirected, ItemPointerGetBlockNumber, ItemPointerGetOffsetNumber, ItemPointerSet, ItemPointerSetOffsetNumber, PageGetItem, PageGetItemId, PageGetMaxOffsetNumber, PredicateLockTuple(), RecentGlobalXmin, RelationGetRelid, skip(), HeapTupleHeaderData::t_ctid, HeapTupleData::t_data, HeapTupleData::t_len, HeapTupleData::t_self, HeapTupleData::t_tableOid, TransactionIdEquals, and TransactionIdIsValid.

Referenced by bitgetpage(), heap_hot_search(), and index_fetch_heap().

2003 {
2004  Page dp = (Page) BufferGetPage(buffer);
2005  TransactionId prev_xmax = InvalidTransactionId;
2006  OffsetNumber offnum;
2007  bool at_chain_start;
2008  bool valid;
2009  bool skip;
2010 
2011  /* If this is not the first call, previous call returned a (live!) tuple */
2012  if (all_dead)
2013  *all_dead = first_call;
2014 
2016 
2018  offnum = ItemPointerGetOffsetNumber(tid);
2019  at_chain_start = first_call;
2020  skip = !first_call;
2021 
2022  heapTuple->t_self = *tid;
2023 
2024  /* Scan through possible multiple members of HOT-chain */
2025  for (;;)
2026  {
2027  ItemId lp;
2028 
2029  /* check for bogus TID */
2030  if (offnum < FirstOffsetNumber || offnum > PageGetMaxOffsetNumber(dp))
2031  break;
2032 
2033  lp = PageGetItemId(dp, offnum);
2034 
2035  /* check for unused, dead, or redirected items */
2036  if (!ItemIdIsNormal(lp))
2037  {
2038  /* We should only see a redirect at start of chain */
2039  if (ItemIdIsRedirected(lp) && at_chain_start)
2040  {
2041  /* Follow the redirect */
2042  offnum = ItemIdGetRedirect(lp);
2043  at_chain_start = false;
2044  continue;
2045  }
2046  /* else must be end of chain */
2047  break;
2048  }
2049 
2050  heapTuple->t_data = (HeapTupleHeader) PageGetItem(dp, lp);
2051  heapTuple->t_len = ItemIdGetLength(lp);
2052  heapTuple->t_tableOid = RelationGetRelid(relation);
2053  ItemPointerSetOffsetNumber(&heapTuple->t_self, offnum);
2054 
2055  /*
2056  * Shouldn't see a HEAP_ONLY tuple at chain start.
2057  */
2058  if (at_chain_start && HeapTupleIsHeapOnly(heapTuple))
2059  break;
2060 
2061  /*
2062  * The xmin should match the previous xmax value, else chain is
2063  * broken.
2064  */
2065  if (TransactionIdIsValid(prev_xmax) &&
2066  !TransactionIdEquals(prev_xmax,
2067  HeapTupleHeaderGetXmin(heapTuple->t_data)))
2068  break;
2069 
2070  /*
2071  * When first_call is true (and thus, skip is initially false) we'll
2072  * return the first tuple we find. But on later passes, heapTuple
2073  * will initially be pointing to the tuple we returned last time.
2074  * Returning it again would be incorrect (and would loop forever), so
2075  * we skip it and return the next match we find.
2076  */
2077  if (!skip)
2078  {
2079  /*
2080  * For the benefit of logical decoding, have t_self point at the
2081  * element of the HOT chain we're currently investigating instead
2082  * of the root tuple of the HOT chain. This is important because
2083  * the *Satisfies routine for historical mvcc snapshots needs the
2084  * correct tid to decide about the visibility in some cases.
2085  */
2086  ItemPointerSet(&(heapTuple->t_self), BufferGetBlockNumber(buffer), offnum);
2087 
2088  /* If it's visible per the snapshot, we must return it */
2089  valid = HeapTupleSatisfiesVisibility(heapTuple, snapshot, buffer);
2090  CheckForSerializableConflictOut(valid, relation, heapTuple,
2091  buffer, snapshot);
2092  /* reset to original, non-redirected, tid */
2093  heapTuple->t_self = *tid;
2094 
2095  if (valid)
2096  {
2097  ItemPointerSetOffsetNumber(tid, offnum);
2098  PredicateLockTuple(relation, heapTuple, snapshot);
2099  if (all_dead)
2100  *all_dead = false;
2101  return true;
2102  }
2103  }
2104  skip = false;
2105 
2106  /*
2107  * If we can't see it, maybe no one else can either. At caller
2108  * request, check whether all chain members are dead to all
2109  * transactions.
2110  */
2111  if (all_dead && *all_dead &&
2113  *all_dead = false;
2114 
2115  /*
2116  * Check to see if HOT chain continues past this tuple; if so fetch
2117  * the next offnum and loop around.
2118  */
2119  if (HeapTupleIsHotUpdated(heapTuple))
2120  {
2123  offnum = ItemPointerGetOffsetNumber(&heapTuple->t_data->t_ctid);
2124  at_chain_start = false;
2125  prev_xmax = HeapTupleHeaderGetUpdateXid(heapTuple->t_data);
2126  }
2127  else
2128  break; /* end of chain */
2129  }
2130 
2131  return false;
2132 }
#define HeapTupleHeaderGetUpdateXid(tup)
Definition: htup_details.h:359
static void skip(struct vars *v)
Definition: regc_lex.c:1109
#define ItemIdIsRedirected(itemId)
Definition: itemid.h:105
#define TransactionIdEquals(id1, id2)
Definition: transam.h:43
uint32 TransactionId
Definition: c.h:397
HeapTupleHeaderData * HeapTupleHeader
Definition: htup.h:23
#define ItemIdGetRedirect(itemId)
Definition: itemid.h:77
#define PageGetMaxOffsetNumber(page)
Definition: bufpage.h:354
void CheckForSerializableConflictOut(bool visible, Relation relation, HeapTuple tuple, Buffer buffer, Snapshot snapshot)
Definition: predicate.c:3862
bool HeapTupleIsSurelyDead(HeapTuple htup, TransactionId OldestXmin)
Definition: tqual.c:1409
#define HeapTupleSatisfiesVisibility(tuple, snapshot, buffer)
Definition: tqual.h:45
uint16 OffsetNumber
Definition: off.h:24
HeapTupleHeader t_data
Definition: htup.h:67
#define HeapTupleIsHotUpdated(tuple)
Definition: htup_details.h:677
#define ItemIdGetLength(itemId)
Definition: itemid.h:58
ItemPointerData t_ctid
Definition: htup_details.h:150
ItemPointerData t_self
Definition: htup.h:65
uint32 t_len
Definition: htup.h:64
TransactionId RecentGlobalXmin
Definition: snapmgr.c:166
#define InvalidTransactionId
Definition: transam.h:31
Oid t_tableOid
Definition: htup.h:66
#define BufferGetPage(buffer)
Definition: bufmgr.h:160
#define PageGetItemId(page, offsetNumber)
Definition: bufpage.h:232
#define HeapTupleIsHeapOnly(tuple)
Definition: htup_details.h:686
#define Assert(condition)
Definition: c.h:675
#define ItemIdIsNormal(itemId)
Definition: itemid.h:98
WalTimeSample buffer[LAG_TRACKER_BUFFER_SIZE]
Definition: walsender.c:207
#define HeapTupleHeaderGetXmin(tup)
Definition: htup_details.h:307
#define ItemPointerGetOffsetNumber(pointer)
Definition: itemptr.h:76
void PredicateLockTuple(Relation relation, HeapTuple tuple, Snapshot snapshot)
Definition: predicate.c:2460
#define ItemPointerSetOffsetNumber(pointer, offsetNumber)
Definition: itemptr.h:107
BlockNumber BufferGetBlockNumber(Buffer buffer)
Definition: bufmgr.c:2605
#define ItemPointerGetBlockNumber(pointer)
Definition: itemptr.h:66
#define TransactionIdIsValid(xid)
Definition: transam.h:41
#define RelationGetRelid(relation)
Definition: rel.h:417
#define PageGetItem(page, itemId)
Definition: bufpage.h:337
Pointer Page
Definition: bufpage.h:74
#define ItemPointerSet(pointer, blockNumber, offNum)
Definition: itemptr.h:86
void heap_inplace_update ( Relation  relation,
HeapTuple  tuple 
)

Definition at line 6249 of file heapam.c.

References buffer, BUFFER_LOCK_EXCLUSIVE, BufferGetPage, CacheInvalidateHeapTuple(), elog, END_CRIT_SECTION, ereport, errcode(), errmsg(), ERROR, IsBootstrapProcessingMode, IsInParallelMode(), ItemIdGetLength, ItemIdIsNormal, ItemPointerGetBlockNumber, ItemPointerGetOffsetNumber, LockBuffer(), MarkBufferDirty(), NULL, xl_heap_inplace::offnum, PageGetItem, PageGetItemId, PageGetMaxOffsetNumber, PageSetLSN, ReadBuffer(), REGBUF_STANDARD, RelationNeedsWAL, SizeOfHeapInplace, START_CRIT_SECTION, HeapTupleData::t_data, HeapTupleHeaderData::t_hoff, HeapTupleData::t_len, HeapTupleData::t_self, UnlockReleaseBuffer(), XLOG_HEAP_INPLACE, XLogBeginInsert(), XLogInsert(), XLogRegisterBufData(), XLogRegisterBuffer(), and XLogRegisterData().

Referenced by create_toast_table(), index_set_state_flags(), index_update_stats(), vac_update_datfrozenxid(), and vac_update_relstats().

6250 {
6251  Buffer buffer;
6252  Page page;
6253  OffsetNumber offnum;
6254  ItemId lp = NULL;
6255  HeapTupleHeader htup;
6256  uint32 oldlen;
6257  uint32 newlen;
6258 
6259  /*
6260  * For now, parallel operations are required to be strictly read-only.
6261  * Unlike a regular update, this should never create a combo CID, so it
6262  * might be possible to relax this restriction, but not without more
6263  * thought and testing. It's not clear that it would be useful, anyway.
6264  */
6265  if (IsInParallelMode())
6266  ereport(ERROR,
6267  (errcode(ERRCODE_INVALID_TRANSACTION_STATE),
6268  errmsg("cannot update tuples during a parallel operation")));
6269 
6270  buffer = ReadBuffer(relation, ItemPointerGetBlockNumber(&(tuple->t_self)));
6272  page = (Page) BufferGetPage(buffer);
6273 
6274  offnum = ItemPointerGetOffsetNumber(&(tuple->t_self));
6275  if (PageGetMaxOffsetNumber(page) >= offnum)
6276  lp = PageGetItemId(page, offnum);
6277 
6278  if (PageGetMaxOffsetNumber(page) < offnum || !ItemIdIsNormal(lp))
6279  elog(ERROR, "invalid lp");
6280 
6281  htup = (HeapTupleHeader) PageGetItem(page, lp);
6282 
6283  oldlen = ItemIdGetLength(lp) - htup->t_hoff;
6284  newlen = tuple->t_len - tuple->t_data->t_hoff;
6285  if (oldlen != newlen || htup->t_hoff != tuple->t_data->t_hoff)
6286  elog(ERROR, "wrong tuple length");
6287 
6288  /* NO EREPORT(ERROR) from here till changes are logged */
6290 
6291  memcpy((char *) htup + htup->t_hoff,
6292  (char *) tuple->t_data + tuple->t_data->t_hoff,
6293  newlen);
6294 
6295  MarkBufferDirty(buffer);
6296 
6297  /* XLOG stuff */
6298  if (RelationNeedsWAL(relation))
6299  {
6300  xl_heap_inplace xlrec;
6301  XLogRecPtr recptr;
6302 
6303  xlrec.offnum = ItemPointerGetOffsetNumber(&tuple->t_self);
6304 
6305  XLogBeginInsert();
6306  XLogRegisterData((char *) &xlrec, SizeOfHeapInplace);
6307 
6308  XLogRegisterBuffer(0, buffer, REGBUF_STANDARD);
6309  XLogRegisterBufData(0, (char *) htup + htup->t_hoff, newlen);
6310 
6311  /* inplace updates aren't decoded atm, don't log the origin */
6312 
6313  recptr = XLogInsert(RM_HEAP_ID, XLOG_HEAP_INPLACE);
6314 
6315  PageSetLSN(page, recptr);
6316  }
6317 
6318  END_CRIT_SECTION();
6319 
6320  UnlockReleaseBuffer(buffer);
6321 
6322  /*
6323  * Send out shared cache inval if necessary. Note that because we only
6324  * pass the new version of the tuple, this mustn't be used for any
6325  * operations that could change catcache lookup keys. But we aren't
6326  * bothering with index updates either, so that's true a fortiori.
6327  */
6329  CacheInvalidateHeapTuple(relation, tuple, NULL);
6330 }
void XLogRegisterBufData(uint8 block_id, char *data, int len)
Definition: xloginsert.c:361
void CacheInvalidateHeapTuple(Relation relation, HeapTuple tuple, HeapTuple newtuple)
Definition: inval.c:1087
void MarkBufferDirty(Buffer buffer)
Definition: bufmgr.c:1450
void XLogRegisterBuffer(uint8 block_id, Buffer buffer, uint8 flags)
Definition: xloginsert.c:213
HeapTupleHeaderData * HeapTupleHeader
Definition: htup.h:23
#define END_CRIT_SECTION()
Definition: miscadmin.h:132
#define SizeOfHeapInplace
Definition: heapam_xlog.h:286
#define START_CRIT_SECTION()
Definition: miscadmin.h:130
int errcode(int sqlerrcode)
Definition: elog.c:575
#define BUFFER_LOCK_EXCLUSIVE
Definition: bufmgr.h:89
#define PageGetMaxOffsetNumber(page)
Definition: bufpage.h:354
uint16 OffsetNumber
Definition: off.h:24
HeapTupleHeader t_data
Definition: htup.h:67
#define ItemIdGetLength(itemId)
Definition: itemid.h:58
bool IsInParallelMode(void)
Definition: xact.c:913
void UnlockReleaseBuffer(Buffer buffer)
Definition: bufmgr.c:3332
#define ERROR
Definition: elog.h:43
ItemPointerData t_self
Definition: htup.h:65
uint32 t_len
Definition: htup.h:64
#define REGBUF_STANDARD
Definition: xloginsert.h:35
unsigned int uint32
Definition: c.h:268
#define BufferGetPage(buffer)
Definition: bufmgr.h:160
#define ereport(elevel, rest)
Definition: elog.h:122
#define PageGetItemId(page, offsetNumber)
Definition: bufpage.h:232
void XLogRegisterData(char *data, int len)
Definition: xloginsert.c:323
XLogRecPtr XLogInsert(RmgrId rmid, uint8 info)
Definition: xloginsert.c:415
OffsetNumber offnum
Definition: heapam_xlog.h:282
void LockBuffer(Buffer buffer, int mode)
Definition: bufmgr.c:3546
#define NULL
Definition: c.h:229
uint64 XLogRecPtr
Definition: xlogdefs.h:21
#define ItemIdIsNormal(itemId)
Definition: itemid.h:98
WalTimeSample buffer[LAG_TRACKER_BUFFER_SIZE]
Definition: walsender.c:207
Buffer ReadBuffer(Relation reln, BlockNumber blockNum)
Definition: bufmgr.c:594
#define ItemPointerGetOffsetNumber(pointer)
Definition: itemptr.h:76
#define XLOG_HEAP_INPLACE
Definition: heapam_xlog.h:39
#define RelationNeedsWAL(relation)
Definition: rel.h:506
#define IsBootstrapProcessingMode()
Definition: miscadmin.h:365
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define elog
Definition: elog.h:219
#define ItemPointerGetBlockNumber(pointer)
Definition: itemptr.h:66
void XLogBeginInsert(void)
Definition: xloginsert.c:120
#define PageSetLSN(page, lsn)
Definition: bufpage.h:365
int Buffer
Definition: buf.h:23
#define PageGetItem(page, itemId)
Definition: bufpage.h:337
Pointer Page
Definition: bufpage.h:74
Oid heap_insert ( Relation  relation,
HeapTuple  tup,
CommandId  cid,
int  options,
BulkInsertState  bistate 
)

Definition at line 2399 of file heapam.c.

References Assert, buffer, BufferGetBlockNumber(), BufferGetPage, CacheInvalidateHeapTuple(), CheckForSerializableConflictIn(), END_CRIT_SECTION, FirstOffsetNumber, xl_heap_insert::flags, GetCurrentTransactionId(), heap_freetuple(), HEAP_INSERT_SKIP_WAL, HEAP_INSERT_SPECULATIVE, heap_prepare_insert(), HeapTupleGetOid, InvalidBuffer, ItemPointerGetBlockNumber, ItemPointerGetOffsetNumber, log_heap_new_cid(), MarkBufferDirty(), xl_heap_insert::offnum, PageClearAllVisible, PageGetMaxOffsetNumber, PageIsAllVisible, PageSetLSN, pgstat_count_heap_insert(), REGBUF_KEEP_DATA, REGBUF_STANDARD, REGBUF_WILL_INIT, RelationGetBufferForTuple(), RelationIsAccessibleInLogicalDecoding, RelationIsLogicallyLogged, RelationNeedsWAL, RelationPutHeapTuple(), ReleaseBuffer(), SizeOfHeapHeader, SizeOfHeapInsert, SizeofHeapTupleHeader, START_CRIT_SECTION, HeapTupleData::t_data, xl_heap_header::t_hoff, HeapTupleHeaderData::t_hoff, xl_heap_header::t_infomask, HeapTupleHeaderData::t_infomask, xl_heap_header::t_infomask2, HeapTupleHeaderData::t_infomask2, HeapTupleData::t_len, HeapTupleData::t_self, UnlockReleaseBuffer(), visibilitymap_clear(), VISIBILITYMAP_VALID_BITS, XLH_INSERT_ALL_VISIBLE_CLEARED, XLH_INSERT_CONTAINS_NEW_TUPLE, XLH_INSERT_IS_SPECULATIVE, XLOG_HEAP_INIT_PAGE, XLOG_HEAP_INSERT, XLOG_INCLUDE_ORIGIN, XLogBeginInsert(), XLogInsert(), XLogRegisterBufData(), XLogRegisterBuffer(), XLogRegisterData(), and XLogSetRecordFlags().

Referenced by ATRewriteTable(), CopyFrom(), ExecInsert(), intorel_receive(), simple_heap_insert(), toast_save_datum(), and transientrel_receive().

2401 {
2403  HeapTuple heaptup;
2404  Buffer buffer;
2405  Buffer vmbuffer = InvalidBuffer;
2406  bool all_visible_cleared = false;
2407 
2408  /*
2409  * Fill in tuple header fields, assign an OID, and toast the tuple if
2410  * necessary.
2411  *
2412  * Note: below this point, heaptup is the data we actually intend to store
2413  * into the relation; tup is the caller's original untoasted data.
2414  */
2415  heaptup = heap_prepare_insert(relation, tup, xid, cid, options);
2416 
2417  /*
2418  * Find buffer to insert this tuple into. If the page is all visible,
2419  * this will also pin the requisite visibility map page.
2420  */
2421  buffer = RelationGetBufferForTuple(relation, heaptup->t_len,
2422  InvalidBuffer, options, bistate,
2423  &vmbuffer, NULL);
2424 
2425  /*
2426  * We're about to do the actual insert -- but check for conflict first, to
2427  * avoid possibly having to roll back work we've just done.
2428  *
2429  * This is safe without a recheck as long as there is no possibility of
2430  * another process scanning the page between this check and the insert
2431  * being visible to the scan (i.e., an exclusive buffer content lock is
2432  * continuously held from this point until the tuple insert is visible).
2433  *
2434  * For a heap insert, we only need to check for table-level SSI locks. Our
2435  * new tuple can't possibly conflict with existing tuple locks, and heap
2436  * page locks are only consolidated versions of tuple locks; they do not
2437  * lock "gaps" as index page locks do. So we don't need to specify a
2438  * buffer when making the call, which makes for a faster check.
2439  */
2441 
2442  /* NO EREPORT(ERROR) from here till changes are logged */
2444 
2445  RelationPutHeapTuple(relation, buffer, heaptup,
2446  (options & HEAP_INSERT_SPECULATIVE) != 0);
2447 
2448  if (PageIsAllVisible(BufferGetPage(buffer)))
2449  {
2450  all_visible_cleared = true;
2452  visibilitymap_clear(relation,
2453  ItemPointerGetBlockNumber(&(heaptup->t_self)),
2454  vmbuffer, VISIBILITYMAP_VALID_BITS);
2455  }
2456 
2457  /*
2458  * XXX Should we set PageSetPrunable on this page ?
2459  *
2460  * The inserting transaction may eventually abort thus making this tuple
2461  * DEAD and hence available for pruning. Though we don't want to optimize
2462  * for aborts, if no other tuple in this page is UPDATEd/DELETEd, the
2463  * aborted tuple will never be pruned until next vacuum is triggered.
2464  *
2465  * If you do add PageSetPrunable here, add it in heap_xlog_insert too.
2466  */
2467 
2468  MarkBufferDirty(buffer);
2469 
2470  /* XLOG stuff */
2471  if (!(options & HEAP_INSERT_SKIP_WAL) && RelationNeedsWAL(relation))
2472  {
2473  xl_heap_insert xlrec;
2474  xl_heap_header xlhdr;
2475  XLogRecPtr recptr;
2476  Page page = BufferGetPage(buffer);
2477  uint8 info = XLOG_HEAP_INSERT;
2478  int bufflags = 0;
2479 
2480  /*
2481  * If this is a catalog, we need to transmit combocids to properly
2482  * decode, so log that as well.
2483  */
2485  log_heap_new_cid(relation, heaptup);
2486 
2487  /*
2488  * If this is the single and first tuple on page, we can reinit the
2489  * page instead of restoring the whole thing. Set flag, and hide
2490  * buffer references from XLogInsert.
2491  */
2492  if (ItemPointerGetOffsetNumber(&(heaptup->t_self)) == FirstOffsetNumber &&
2494  {
2495  info |= XLOG_HEAP_INIT_PAGE;
2496  bufflags |= REGBUF_WILL_INIT;
2497  }
2498 
2499  xlrec.offnum = ItemPointerGetOffsetNumber(&heaptup->t_self);
2500  xlrec.flags = 0;
2501  if (all_visible_cleared)
2506 
2507  /*
2508  * For logical decoding, we need the tuple even if we're doing a full
2509  * page write, so make sure it's included even if we take a full-page
2510  * image. (XXX We could alternatively store a pointer into the FPW).
2511  */
2512  if (RelationIsLogicallyLogged(relation))
2513  {
2515  bufflags |= REGBUF_KEEP_DATA;
2516  }
2517 
2518  XLogBeginInsert();
2519  XLogRegisterData((char *) &xlrec, SizeOfHeapInsert);
2520 
2521  xlhdr.t_infomask2 = heaptup->t_data->t_infomask2;
2522  xlhdr.t_infomask = heaptup->t_data->t_infomask;
2523  xlhdr.t_hoff = heaptup->t_data->t_hoff;
2524 
2525  /*
2526  * note we mark xlhdr as belonging to buffer; if XLogInsert decides to
2527  * write the whole page to the xlog, we don't need to store
2528  * xl_heap_header in the xlog.
2529  */
2530  XLogRegisterBuffer(0, buffer, REGBUF_STANDARD | bufflags);
2531  XLogRegisterBufData(0, (char *) &xlhdr, SizeOfHeapHeader);
2532  /* PG73FORMAT: write bitmap [+ padding] [+ oid] + data */
2534  (char *) heaptup->t_data + SizeofHeapTupleHeader,
2535  heaptup->t_len - SizeofHeapTupleHeader);
2536 
2537  /* filtering by origin on a row level is much more efficient */
2539 
2540  recptr = XLogInsert(RM_HEAP_ID, info);
2541 
2542  PageSetLSN(page, recptr);
2543  }
2544 
2545  END_CRIT_SECTION();
2546 
2547  UnlockReleaseBuffer(buffer);
2548  if (vmbuffer != InvalidBuffer)
2549  ReleaseBuffer(vmbuffer);
2550 
2551  /*
2552  * If tuple is cachable, mark it for invalidation from the caches in case
2553  * we abort. Note it is OK to do this after releasing the buffer, because
2554  * the heaptup data structure is all in local memory, not in the shared
2555  * buffer.
2556  */
2557  CacheInvalidateHeapTuple(relation, heaptup, NULL);
2558 
2559  /* Note: speculative insertions are counted too, even if aborted later */
2560  pgstat_count_heap_insert(relation, 1);
2561 
2562  /*
2563  * If heaptup is a private copy, release it. Don't forget to copy t_self
2564  * back to the caller's image, too.
2565  */
2566  if (heaptup != tup)
2567  {
2568  tup->t_self = heaptup->t_self;
2569  heap_freetuple(heaptup);
2570  }
2571 
2572  return HeapTupleGetOid(tup);
2573 }
void XLogRegisterBufData(uint8 block_id, char *data, int len)
Definition: xloginsert.c:361
#define SizeofHeapTupleHeader
Definition: htup_details.h:170
#define XLOG_HEAP_INSERT
Definition: heapam_xlog.h:32
static XLogRecPtr log_heap_new_cid(Relation relation, HeapTuple tup)
Definition: heapam.c:7748
void CacheInvalidateHeapTuple(Relation relation, HeapTuple tuple, HeapTuple newtuple)
Definition: inval.c:1087
static HeapTuple heap_prepare_insert(Relation relation, HeapTuple tup, TransactionId xid, CommandId cid, int options)
Definition: heapam.c:2583
#define PageIsAllVisible(page)
Definition: bufpage.h:382
uint32 TransactionId
Definition: c.h:397
void MarkBufferDirty(Buffer buffer)
Definition: bufmgr.c:1450
void XLogRegisterBuffer(uint8 block_id, Buffer buffer, uint8 flags)
Definition: xloginsert.c:213
#define END_CRIT_SECTION()
Definition: miscadmin.h:132
unsigned char uint8
Definition: c.h:266
#define XLH_INSERT_IS_SPECULATIVE
Definition: heapam_xlog.h:68
#define InvalidBuffer
Definition: buf.h:25
#define REGBUF_WILL_INIT
Definition: xloginsert.h:32
uint16 t_infomask2
Definition: heapam_xlog.h:122
#define START_CRIT_SECTION()
Definition: miscadmin.h:130
#define XLOG_INCLUDE_ORIGIN
Definition: xlog.h:192
#define HEAP_INSERT_SKIP_WAL
Definition: heapam.h:28
void ReleaseBuffer(Buffer buffer)
Definition: bufmgr.c:3309
#define RelationIsLogicallyLogged(relation)
Definition: rel.h:576
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1374
#define PageGetMaxOffsetNumber(page)
Definition: bufpage.h:354
void RelationPutHeapTuple(Relation relation, Buffer buffer, HeapTuple tuple, bool token)
Definition: hio.c:36
void CheckForSerializableConflictIn(Relation relation, HeapTuple tuple, Buffer buffer)
Definition: predicate.c:4243
#define XLOG_HEAP_INIT_PAGE
Definition: heapam_xlog.h:46
#define HEAP_INSERT_SPECULATIVE
Definition: heapam.h:31
#define VISIBILITYMAP_VALID_BITS
Definition: visibilitymap.h:28
HeapTupleHeader t_data
Definition: htup.h:67
bool visibilitymap_clear(Relation rel, BlockNumber heapBlk, Buffer buf, uint8 flags)
void UnlockReleaseBuffer(Buffer buffer)
Definition: bufmgr.c:3332
#define XLH_INSERT_CONTAINS_NEW_TUPLE
Definition: heapam_xlog.h:69
ItemPointerData t_self
Definition: htup.h:65
TransactionId GetCurrentTransactionId(void)
Definition: xact.c:417
uint32 t_len
Definition: htup.h:64
#define FirstOffsetNumber
Definition: off.h:27
#define REGBUF_STANDARD
Definition: xloginsert.h:35
Buffer RelationGetBufferForTuple(Relation relation, Size len, Buffer otherBuffer, int options, BulkInsertState bistate, Buffer *vmbuffer, Buffer *vmbuffer_other)
Definition: hio.c:297
void XLogSetRecordFlags(uint8 flags)
Definition: xloginsert.c:397
#define BufferGetPage(buffer)
Definition: bufmgr.h:160
void XLogRegisterData(char *data, int len)
Definition: xloginsert.c:323
XLogRecPtr XLogInsert(RmgrId rmid, uint8 info)
Definition: xloginsert.c:415
#define RelationIsAccessibleInLogicalDecoding(relation)
Definition: rel.h:560
#define REGBUF_KEEP_DATA
Definition: xloginsert.h:38
#define PageClearAllVisible(page)
Definition: bufpage.h:386
#define NULL
Definition: c.h:229
uint64 XLogRecPtr
Definition: xlogdefs.h:21
#define Assert(condition)
Definition: c.h:675
WalTimeSample buffer[LAG_TRACKER_BUFFER_SIZE]
Definition: walsender.c:207
uint16 t_infomask
Definition: heapam_xlog.h:123
#define ItemPointerGetOffsetNumber(pointer)
Definition: itemptr.h:76
#define RelationNeedsWAL(relation)
Definition: rel.h:506
#define SizeOfHeapInsert
Definition: heapam_xlog.h:138
#define XLH_INSERT_ALL_VISIBLE_CLEARED
Definition: heapam_xlog.h:66
BlockNumber BufferGetBlockNumber(Buffer buffer)
Definition: bufmgr.c:2605
void pgstat_count_heap_insert(Relation rel, PgStat_Counter n)
Definition: pgstat.c:1806
#define ItemPointerGetBlockNumber(pointer)
Definition: itemptr.h:66
#define HeapTupleGetOid(tuple)
Definition: htup_details.h:695
void XLogBeginInsert(void)
Definition: xloginsert.c:120
#define PageSetLSN(page, lsn)
Definition: bufpage.h:365
int Buffer
Definition: buf.h:23
OffsetNumber offnum
Definition: heapam_xlog.h:132
#define SizeOfHeapHeader
Definition: heapam_xlog.h:127
Pointer Page
Definition: bufpage.h:74
HTSU_Result heap_lock_tuple ( Relation  relation,
HeapTuple  tuple,
CommandId  cid,
LockTupleMode  mode,
LockWaitPolicy  wait_policy,
bool  follow_update,
Buffer buffer,
HeapUpdateFailureData hufd 
)

Definition at line 4594 of file heapam.c.

References Assert, BUFFER_LOCK_EXCLUSIVE, BUFFER_LOCK_UNLOCK, BufferGetPage, BufferIsValid, HeapUpdateFailureData::cmax, compute_infobits(), compute_new_xmax_infomask(), ConditionalMultiXactIdWait(), ConditionalXactLockTableWait(), HeapUpdateFailureData::ctid, DoesMultiXactIdConflict(), elog, END_CRIT_SECTION, ereport, errcode(), errmsg(), ERROR, xl_heap_lock::flags, get_mxact_status_for_lock(), GetCurrentTransactionId(), GetMultiXactIdMembers(), heap_acquire_tuplock(), HEAP_KEYS_UPDATED, heap_lock_updated_tuple(), HEAP_XMAX_BITS, HEAP_XMAX_INVALID, HEAP_XMAX_IS_EXCL_LOCKED, HEAP_XMAX_IS_KEYSHR_LOCKED, HEAP_XMAX_IS_LOCKED_ONLY, HEAP_XMAX_IS_MULTI, HEAP_XMAX_IS_SHR_LOCKED, HeapTupleBeingUpdated, HeapTupleHeaderClearHotUpdated, HeapTupleHeaderGetCmax(), HeapTupleHeaderGetRawXmax, HeapTupleHeaderGetUpdateXid, HeapTupleHeaderIsOnlyLocked(), HeapTupleHeaderSetXmax, HeapTupleInvisible, HeapTupleMayBeUpdated, HeapTupleSatisfiesUpdate(), HeapTupleSelfUpdated, HeapTupleUpdated, HeapTupleWouldBlock, i, xl_heap_lock::infobits_set, InvalidBuffer, InvalidCommandId, ItemIdGetLength, ItemIdIsNormal, ItemPointerCopy, ItemPointerGetBlockNumber, ItemPointerGetOffsetNumber, LockBuffer(), xl_heap_lock::locking_xid, LockTupleExclusive, LockTupleKeyShare, LockTupleNoKeyExclusive, LockTupleShare, LockWaitBlock, LockWaitError, LockWaitSkip, MarkBufferDirty(), MultiXactIdSetOldestMember(), MultiXactIdWait(), MultiXactStatusNoKeyUpdate, xl_heap_lock::offnum, PageGetItem, PageGetItemId, PageIsAllVisible, PageSetLSN, pfree(), ReadBuffer(), REGBUF_STANDARD, RelationGetRelationName, RelationGetRelid, RelationNeedsWAL, ReleaseBuffer(), result, SizeOfHeapLock, START_CRIT_SECTION, status(), HeapTupleHeaderData::t_ctid, HeapTupleData::t_data, HeapTupleHeaderData::t_infomask, HeapTupleHeaderData::t_infomask2, HeapTupleData::t_len, HeapTupleData::t_self, HeapTupleData::t_tableOid, TransactionIdEquals, TransactionIdIsCurrentTransactionId(), TUPLOCK_from_mxstatus, UnlockTupleTuplock, UpdateXmaxHintBits(), VISIBILITYMAP_ALL_FROZEN, visibilitymap_clear(), visibilitymap_pin(), XactLockTableWait(), XLH_LOCK_ALL_FROZEN_CLEARED, XLOG_HEAP_LOCK, XLogBeginInsert(), XLogInsert(), XLogRegisterBuffer(), XLogRegisterData(), XLTW_Lock, HeapUpdateFailureData::xmax, and xmax_infomask_changed().

Referenced by EvalPlanQualFetch(), ExecLockRows(), ExecOnConflictUpdate(), GetTupleForTrigger(), RelationFindReplTupleByIndex(), and RelationFindReplTupleSeq().

4598 {
4600  ItemPointer tid = &(tuple->t_self);
4601  ItemId lp;
4602  Page page;
4603  Buffer vmbuffer = InvalidBuffer;
4604  BlockNumber block;
4605  TransactionId xid,
4606  xmax;
4607  uint16 old_infomask,
4608  new_infomask,
4609  new_infomask2;
4610  bool first_time = true;
4611  bool have_tuple_lock = false;
4612  bool cleared_all_frozen = false;
4613 
4614  *buffer = ReadBuffer(relation, ItemPointerGetBlockNumber(tid));
4615  block = ItemPointerGetBlockNumber(tid);
4616 
4617  /*
4618  * Before locking the buffer, pin the visibility map page if it appears to
4619  * be necessary. Since we haven't got the lock yet, someone else might be
4620  * in the middle of changing this, so we'll need to recheck after we have
4621  * the lock.
4622  */
4624  visibilitymap_pin(relation, block, &vmbuffer);
4625 
4627 
4628  page = BufferGetPage(*buffer);
4629  lp = PageGetItemId(page, ItemPointerGetOffsetNumber(tid));
4630  Assert(ItemIdIsNormal(lp));
4631 
4632  tuple->t_data = (HeapTupleHeader) PageGetItem(page, lp);
4633  tuple->t_len = ItemIdGetLength(lp);
4634  tuple->t_tableOid = RelationGetRelid(relation);
4635 
4636 l3:
4637  result = HeapTupleSatisfiesUpdate(tuple, cid, *buffer);
4638 
4639  if (result == HeapTupleInvisible)
4640  {
4641  /*
4642  * This is possible, but only when locking a tuple for ON CONFLICT
4643  * UPDATE. We return this value here rather than throwing an error in
4644  * order to give that case the opportunity to throw a more specific
4645  * error.
4646  */
4647  result = HeapTupleInvisible;
4648  goto out_locked;
4649  }
4650  else if (result == HeapTupleBeingUpdated || result == HeapTupleUpdated)
4651  {
4652  TransactionId xwait;
4653  uint16 infomask;
4654  uint16 infomask2;
4655  bool require_sleep;
4656  ItemPointerData t_ctid;
4657 
4658  /* must copy state data before unlocking buffer */
4659  xwait = HeapTupleHeaderGetRawXmax(tuple->t_data);
4660  infomask = tuple->t_data->t_infomask;
4661  infomask2 = tuple->t_data->t_infomask2;
4662  ItemPointerCopy(&tuple->t_data->t_ctid, &t_ctid);
4663 
4665 
4666  /*
4667  * If any subtransaction of the current top transaction already holds
4668  * a lock as strong as or stronger than what we're requesting, we
4669  * effectively hold the desired lock already. We *must* succeed
4670  * without trying to take the tuple lock, else we will deadlock
4671  * against anyone wanting to acquire a stronger lock.
4672  *
4673  * Note we only do this the first time we loop on the HTSU result;
4674  * there is no point in testing in subsequent passes, because
4675  * evidently our own transaction cannot have acquired a new lock after
4676  * the first time we checked.
4677  */
4678  if (first_time)
4679  {
4680  first_time = false;
4681 
4682  if (infomask & HEAP_XMAX_IS_MULTI)
4683  {
4684  int i;
4685  int nmembers;
4686  MultiXactMember *members;
4687 
4688  /*
4689  * We don't need to allow old multixacts here; if that had
4690  * been the case, HeapTupleSatisfiesUpdate would have returned
4691  * MayBeUpdated and we wouldn't be here.
4692  */
4693  nmembers =
4694  GetMultiXactIdMembers(xwait, &members, false,
4695  HEAP_XMAX_IS_LOCKED_ONLY(infomask));
4696 
4697  for (i = 0; i < nmembers; i++)
4698  {
4699  /* only consider members of our own transaction */
4700  if (!TransactionIdIsCurrentTransactionId(members[i].xid))
4701  continue;
4702 
4703  if (TUPLOCK_from_mxstatus(members[i].status) >= mode)
4704  {
4705  pfree(members);
4706  result = HeapTupleMayBeUpdated;
4707  goto out_unlocked;
4708  }
4709  }
4710 
4711  if (members)
4712  pfree(members);
4713  }
4714  else if (TransactionIdIsCurrentTransactionId(xwait))
4715  {
4716  switch (mode)
4717  {
4718  case LockTupleKeyShare:
4719  Assert(HEAP_XMAX_IS_KEYSHR_LOCKED(infomask) ||
4720  HEAP_XMAX_IS_SHR_LOCKED(infomask) ||
4721  HEAP_XMAX_IS_EXCL_LOCKED(infomask));
4722  result = HeapTupleMayBeUpdated;
4723  goto out_unlocked;
4724  case LockTupleShare:
4725  if (HEAP_XMAX_IS_SHR_LOCKED(infomask) ||
4726  HEAP_XMAX_IS_EXCL_LOCKED(infomask))
4727  {
4728  result = HeapTupleMayBeUpdated;
4729  goto out_unlocked;
4730  }
4731  break;
4733  if (HEAP_XMAX_IS_EXCL_LOCKED(infomask))
4734  {
4735  result = HeapTupleMayBeUpdated;
4736  goto out_unlocked;
4737  }
4738  break;
4739  case LockTupleExclusive:
4740  if (HEAP_XMAX_IS_EXCL_LOCKED(infomask) &&
4741  infomask2 & HEAP_KEYS_UPDATED)
4742  {
4743  result = HeapTupleMayBeUpdated;
4744  goto out_unlocked;
4745  }
4746  break;
4747  }
4748  }
4749  }
4750 
4751  /*
4752  * Initially assume that we will have to wait for the locking
4753  * transaction(s) to finish. We check various cases below in which
4754  * this can be turned off.
4755  */
4756  require_sleep = true;
4757  if (mode == LockTupleKeyShare)
4758  {
4759  /*
4760  * If we're requesting KeyShare, and there's no update present, we
4761  * don't need to wait. Even if there is an update, we can still
4762  * continue if the key hasn't been modified.
4763  *
4764  * However, if there are updates, we need to walk the update chain
4765  * to mark future versions of the row as locked, too. That way,
4766  * if somebody deletes that future version, we're protected
4767  * against the key going away. This locking of future versions
4768  * could block momentarily, if a concurrent transaction is
4769  * deleting a key; or it could return a value to the effect that
4770  * the transaction deleting the key has already committed. So we
4771  * do this before re-locking the buffer; otherwise this would be
4772  * prone to deadlocks.
4773  *
4774  * Note that the TID we're locking was grabbed before we unlocked
4775  * the buffer. For it to change while we're not looking, the
4776  * other properties we're testing for below after re-locking the
4777  * buffer would also change, in which case we would restart this
4778  * loop above.
4779  */
4780  if (!(infomask2 & HEAP_KEYS_UPDATED))
4781  {
4782  bool updated;
4783 
4784  updated = !HEAP_XMAX_IS_LOCKED_ONLY(infomask);
4785 
4786  /*
4787  * If there are updates, follow the update chain; bail out if
4788  * that cannot be done.
4789  */
4790  if (follow_updates && updated)
4791  {
4792  HTSU_Result res;
4793 
4794  res = heap_lock_updated_tuple(relation, tuple, &t_ctid,
4796  mode);
4797  if (res != HeapTupleMayBeUpdated)
4798  {
4799  result = res;
4800  /* recovery code expects to have buffer lock held */
4802  goto failed;
4803  }
4804  }
4805 
4807 
4808  /*
4809  * Make sure it's still an appropriate lock, else start over.
4810  * Also, if it wasn't updated before we released the lock, but
4811  * is updated now, we start over too; the reason is that we
4812  * now need to follow the update chain to lock the new
4813  * versions.
4814  */
4815  if (!HeapTupleHeaderIsOnlyLocked(tuple->t_data) &&
4816  ((tuple->t_data->t_infomask2 & HEAP_KEYS_UPDATED) ||
4817  !updated))
4818  goto l3;
4819 
4820  /* Things look okay, so we can skip sleeping */
4821  require_sleep = false;
4822 
4823  /*
4824  * Note we allow Xmax to change here; other updaters/lockers
4825  * could have modified it before we grabbed the buffer lock.
4826  * However, this is not a problem, because with the recheck we
4827  * just did we ensure that they still don't conflict with the
4828  * lock we want.
4829  */
4830  }
4831  }
4832  else if (mode == LockTupleShare)
4833  {
4834  /*
4835  * If we're requesting Share, we can similarly avoid sleeping if
4836  * there's no update and no exclusive lock present.
4837  */
4838  if (HEAP_XMAX_IS_LOCKED_ONLY(infomask) &&
4839  !HEAP_XMAX_IS_EXCL_LOCKED(infomask))
4840  {
4842 
4843  /*
4844  * Make sure it's still an appropriate lock, else start over.
4845  * See above about allowing xmax to change.
4846  */
4847  if (!HEAP_XMAX_IS_LOCKED_ONLY(tuple->t_data->t_infomask) ||
4849  goto l3;
4850  require_sleep = false;
4851  }
4852  }
4853  else if (mode == LockTupleNoKeyExclusive)
4854  {
4855  /*
4856  * If we're requesting NoKeyExclusive, we might also be able to
4857  * avoid sleeping; just ensure that there no conflicting lock
4858  * already acquired.
4859  */
4860  if (infomask & HEAP_XMAX_IS_MULTI)
4861  {
4862  if (!DoesMultiXactIdConflict((MultiXactId) xwait, infomask,
4863  mode))
4864  {
4865  /*
4866  * No conflict, but if the xmax changed under us in the
4867  * meantime, start over.
4868  */
4870  if (xmax_infomask_changed(tuple->t_data->t_infomask, infomask) ||
4872  xwait))
4873  goto l3;
4874 
4875  /* otherwise, we're good */
4876  require_sleep = false;
4877  }
4878  }
4879  else if (HEAP_XMAX_IS_KEYSHR_LOCKED(infomask))
4880  {
4882 
4883  /* if the xmax changed in the meantime, start over */
4884  if (xmax_infomask_changed(tuple->t_data->t_infomask, infomask) ||
4887  xwait))
4888  goto l3;
4889  /* otherwise, we're good */
4890  require_sleep = false;
4891  }
4892  }
4893 
4894  /*
4895  * As a check independent from those above, we can also avoid sleeping
4896  * if the current transaction is the sole locker of the tuple. Note
4897  * that the strength of the lock already held is irrelevant; this is
4898  * not about recording the lock in Xmax (which will be done regardless
4899  * of this optimization, below). Also, note that the cases where we
4900  * hold a lock stronger than we are requesting are already handled
4901  * above by not doing anything.
4902  *
4903  * Note we only deal with the non-multixact case here; MultiXactIdWait
4904  * is well equipped to deal with this situation on its own.
4905  */
4906  if (require_sleep && !(infomask & HEAP_XMAX_IS_MULTI) &&
4908  {
4909  /* ... but if the xmax changed in the meantime, start over */
4911  if (xmax_infomask_changed(tuple->t_data->t_infomask, infomask) ||
4913  xwait))
4914  goto l3;
4916  require_sleep = false;
4917  }
4918 
4919  /*
4920  * Time to sleep on the other transaction/multixact, if necessary.
4921  *
4922  * If the other transaction is an update that's already committed,
4923  * then sleeping cannot possibly do any good: if we're required to
4924  * sleep, get out to raise an error instead.
4925  *
4926  * By here, we either have already acquired the buffer exclusive lock,
4927  * or we must wait for the locking transaction or multixact; so below
4928  * we ensure that we grab buffer lock after the sleep.
4929  */
4930  if (require_sleep && result == HeapTupleUpdated)
4931  {
4933  goto failed;
4934  }
4935  else if (require_sleep)
4936  {
4937  /*
4938  * Acquire tuple lock to establish our priority for the tuple, or
4939  * die trying. LockTuple will release us when we are next-in-line
4940  * for the tuple. We must do this even if we are share-locking.
4941  *
4942  * If we are forced to "start over" below, we keep the tuple lock;
4943  * this arranges that we stay at the head of the line while
4944  * rechecking tuple state.
4945  */
4946  if (!heap_acquire_tuplock(relation, tid, mode, wait_policy,
4947  &have_tuple_lock))
4948  {
4949  /*
4950  * This can only happen if wait_policy is Skip and the lock
4951  * couldn't be obtained.
4952  */
4953  result = HeapTupleWouldBlock;
4954  /* recovery code expects to have buffer lock held */
4956  goto failed;
4957  }
4958 
4959  if (infomask & HEAP_XMAX_IS_MULTI)
4960  {
4962 
4963  /* We only ever lock tuples, never update them */
4964  if (status >= MultiXactStatusNoKeyUpdate)
4965  elog(ERROR, "invalid lock mode in heap_lock_tuple");
4966 
4967  /* wait for multixact to end, or die trying */
4968  switch (wait_policy)
4969  {
4970  case LockWaitBlock:
4971  MultiXactIdWait((MultiXactId) xwait, status, infomask,
4972  relation, &tuple->t_self, XLTW_Lock, NULL);
4973  break;
4974  case LockWaitSkip:
4976  status, infomask, relation,
4977  NULL))
4978  {
4979  result = HeapTupleWouldBlock;
4980  /* recovery code expects to have buffer lock held */
4982  goto failed;
4983  }
4984  break;
4985  case LockWaitError:
4987  status, infomask, relation,
4988  NULL))
4989  ereport(ERROR,
4990  (errcode(ERRCODE_LOCK_NOT_AVAILABLE),
4991  errmsg("could not obtain lock on row in relation \"%s\"",
4992  RelationGetRelationName(relation))));
4993 
4994  break;
4995  }
4996 
4997  /*
4998  * Of course, the multixact might not be done here: if we're
4999  * requesting a light lock mode, other transactions with light
5000  * locks could still be alive, as well as locks owned by our
5001  * own xact or other subxacts of this backend. We need to
5002  * preserve the surviving MultiXact members. Note that it
5003  * isn't absolutely necessary in the latter case, but doing so
5004  * is simpler.
5005  */
5006  }
5007  else
5008  {
5009  /* wait for regular transaction to end, or die trying */
5010  switch (wait_policy)
5011  {
5012  case LockWaitBlock:
5013  XactLockTableWait(xwait, relation, &tuple->t_self,
5014  XLTW_Lock);
5015  break;
5016  case LockWaitSkip:
5017  if (!ConditionalXactLockTableWait(xwait))
5018  {
5019  result = HeapTupleWouldBlock;
5020  /* recovery code expects to have buffer lock held */
5022  goto failed;
5023  }
5024  break;
5025  case LockWaitError:
5026  if (!ConditionalXactLockTableWait(xwait))
5027  ereport(ERROR,
5028  (errcode(ERRCODE_LOCK_NOT_AVAILABLE),
5029  errmsg("could not obtain lock on row in relation \"%s\"",
5030  RelationGetRelationName(relation))));
5031  break;
5032  }
5033  }
5034 
5035  /* if there are updates, follow the update chain */
5036  if (follow_updates && !HEAP_XMAX_IS_LOCKED_ONLY(infomask))
5037  {
5038  HTSU_Result res;
5039 
5040  res = heap_lock_updated_tuple(relation, tuple, &t_ctid,
5042  mode);
5043  if (res != HeapTupleMayBeUpdated)
5044  {
5045  result = res;
5046  /* recovery code expects to have buffer lock held */
5048  goto failed;
5049  }
5050  }
5051 
5053 
5054  /*
5055  * xwait is done, but if xwait had just locked the tuple then some
5056  * other xact could update this tuple before we get to this point.
5057  * Check for xmax change, and start over if so.
5058  */
5059  if (xmax_infomask_changed(tuple->t_data->t_infomask, infomask) ||
5061  xwait))
5062  goto l3;
5063 
5064  if (!(infomask & HEAP_XMAX_IS_MULTI))
5065  {
5066  /*
5067  * Otherwise check if it committed or aborted. Note we cannot
5068  * be here if the tuple was only locked by somebody who didn't
5069  * conflict with us; that would have been handled above. So
5070  * that transaction must necessarily be gone by now. But
5071  * don't check for this in the multixact case, because some
5072  * locker transactions might still be running.
5073  */
5074  UpdateXmaxHintBits(tuple->t_data, *buffer, xwait);
5075  }
5076  }
5077 
5078  /* By here, we're certain that we hold buffer exclusive lock again */
5079 
5080  /*
5081  * We may lock if previous xmax aborted, or if it committed but only
5082  * locked the tuple without updating it; or if we didn't have to wait
5083  * at all for whatever reason.
5084  */
5085  if (!require_sleep ||
5086  (tuple->t_data->t_infomask & HEAP_XMAX_INVALID) ||
5089  result = HeapTupleMayBeUpdated;
5090  else
5091  result = HeapTupleUpdated;
5092  }
5093 
5094 failed:
5095  if (result != HeapTupleMayBeUpdated)
5096  {
5097  Assert(result == HeapTupleSelfUpdated || result == HeapTupleUpdated ||
5098  result == HeapTupleWouldBlock);
5099  Assert(!(tuple->t_data->t_infomask & HEAP_XMAX_INVALID));
5100  hufd->ctid = tuple->t_data->t_ctid;
5101  hufd->xmax = HeapTupleHeaderGetUpdateXid(tuple->t_data);
5102  if (result == HeapTupleSelfUpdated)
5103  hufd->cmax = HeapTupleHeaderGetCmax(tuple->t_data);
5104  else
5105  hufd->cmax = InvalidCommandId;
5106  goto out_locked;
5107  }
5108 
5109  /*
5110  * If we didn't pin the visibility map page and the page has become all
5111  * visible while we were busy locking the buffer, or during some
5112  * subsequent window during which we had it unlocked, we'll have to unlock
5113  * and re-lock, to avoid holding the buffer lock across I/O. That's a bit
5114  * unfortunate, especially since we'll now have to recheck whether the
5115  * tuple has been locked or updated under us, but hopefully it won't
5116  * happen very often.
5117  */
5118  if (vmbuffer == InvalidBuffer && PageIsAllVisible(page))
5119  {
5121  visibilitymap_pin(relation, block, &vmbuffer);
5123  goto l3;
5124  }
5125 
5126  xmax = HeapTupleHeaderGetRawXmax(tuple->t_data);
5127  old_infomask = tuple->t_data->t_infomask;
5128 
5129  /*
5130  * If this is the first possibly-multixact-able operation in the current
5131  * transaction, set my per-backend OldestMemberMXactId setting. We can be
5132  * certain that the transaction will never become a member of any older
5133  * MultiXactIds than that. (We have to do this even if we end up just
5134  * using our own TransactionId below, since some other backend could
5135  * incorporate our XID into a MultiXact immediately afterwards.)
5136  */
5138 
5139  /*
5140  * Compute the new xmax and infomask to store into the tuple. Note we do
5141  * not modify the tuple just yet, because that would leave it in the wrong
5142  * state if multixact.c elogs.
5143  */
5144  compute_new_xmax_infomask(xmax, old_infomask, tuple->t_data->t_infomask2,
5145  GetCurrentTransactionId(), mode, false,
5146  &xid, &new_infomask, &new_infomask2);
5147 
5149 
5150  /*
5151  * Store transaction information of xact locking the tuple.
5152  *
5153  * Note: Cmax is meaningless in this context, so don't set it; this avoids
5154  * possibly generating a useless combo CID. Moreover, if we're locking a
5155  * previously updated tuple, it's important to preserve the Cmax.
5156  *
5157  * Also reset the HOT UPDATE bit, but only if there's no update; otherwise
5158  * we would break the HOT chain.
5159  */
5160  tuple->t_data->t_infomask &= ~HEAP_XMAX_BITS;
5161  tuple->t_data->t_infomask2 &= ~HEAP_KEYS_UPDATED;
5162  tuple->t_data->t_infomask |= new_infomask;
5163  tuple->t_data->t_infomask2 |= new_infomask2;
5164  if (HEAP_XMAX_IS_LOCKED_ONLY(new_infomask))
5166  HeapTupleHeaderSetXmax(tuple->t_data, xid);
5167 
5168  /*
5169  * Make sure there is no forward chain link in t_ctid. Note that in the
5170  * cases where the tuple has been updated, we must not overwrite t_ctid,
5171  * because it was set by the updater. Moreover, if the tuple has been
5172  * updated, we need to follow the update chain to lock the new versions of
5173  * the tuple as well.
5174  */
5175  if (HEAP_XMAX_IS_LOCKED_ONLY(new_infomask))
5176  tuple->t_data->t_ctid = *tid;
5177 
5178  /* Clear only the all-frozen bit on visibility map if needed */
5179  if (PageIsAllVisible(page) &&
5180  visibilitymap_clear(relation, block, vmbuffer,
5182  cleared_all_frozen = true;
5183 
5184 
5186 
5187  /*
5188  * XLOG stuff. You might think that we don't need an XLOG record because
5189  * there is no state change worth restoring after a crash. You would be
5190  * wrong however: we have just written either a TransactionId or a
5191  * MultiXactId that may never have been seen on disk before, and we need
5192  * to make sure that there are XLOG entries covering those ID numbers.
5193  * Else the same IDs might be re-used after a crash, which would be
5194  * disastrous if this page made it to disk before the crash. Essentially
5195  * we have to enforce the WAL log-before-data rule even in this case.
5196  * (Also, in a PITR log-shipping or 2PC environment, we have to have XLOG
5197  * entries for everything anyway.)
5198  */
5199  if (RelationNeedsWAL(relation))
5200  {
5201  xl_heap_lock xlrec;
5202  XLogRecPtr recptr;
5203 
5204  XLogBeginInsert();
5206 
5207  xlrec.offnum = ItemPointerGetOffsetNumber(&tuple->t_self);
5208  xlrec.locking_xid = xid;
5209  xlrec.infobits_set = compute_infobits(new_infomask,
5210  tuple->t_data->t_infomask2);
5211  xlrec.flags = cleared_all_frozen ? XLH_LOCK_ALL_FROZEN_CLEARED : 0;
5212  XLogRegisterData((char *) &xlrec, SizeOfHeapLock);
5213 
5214  /* we don't decode row locks atm, so no need to log the origin */
5215 
5216  recptr = XLogInsert(RM_HEAP_ID, XLOG_HEAP_LOCK);
5217 
5218  PageSetLSN(page, recptr);
5219  }
5220 
5221  END_CRIT_SECTION();
5222 
5223  result = HeapTupleMayBeUpdated;
5224 
5225 out_locked:
5227 
5228 out_unlocked:
5229  if (BufferIsValid(vmbuffer))
5230  ReleaseBuffer(vmbuffer);
5231 
5232  /*
5233  * Don't update the visibility map here. Locking a tuple doesn't change
5234  * visibility info.
5235  */
5236 
5237  /*
5238  * Now that we have successfully marked the tuple as locked, we can
5239  * release the lmgr tuple lock, if we had it.
5240  */
5241  if (have_tuple_lock)
5242  UnlockTupleTuplock(relation, tid, mode);
5243 
5244  return result;
5245 }
#define HeapTupleHeaderGetUpdateXid(tup)
Definition: htup_details.h:359
bool HeapTupleHeaderIsOnlyLocked(HeapTupleHeader tuple)
Definition: tqual.c:1585
MultiXactStatus
Definition: multixact.h:40
#define BUFFER_LOCK_UNLOCK
Definition: bufmgr.h:87
#define HEAP_XMAX_BITS
Definition: htup_details.h:256
OffsetNumber offnum
Definition: heapam_xlog.h:253
static uint8 compute_infobits(uint16 infomask, uint16 infomask2)
Definition: heapam.c:2955
#define TransactionIdEquals(id1, id2)
Definition: transam.h:43
#define PageIsAllVisible(page)
Definition: bufpage.h:382
#define XLH_LOCK_ALL_FROZEN_CLEARED
Definition: heapam_xlog.h:247
TransactionId locking_xid
Definition: heapam_xlog.h:252
uint32 TransactionId
Definition: c.h:397
HTSU_Result HeapTupleSatisfiesUpdate(HeapTuple htup, CommandId curcid, Buffer buffer)
Definition: tqual.c:460
bool TransactionIdIsCurrentTransactionId(TransactionId xid)
Definition: xact.c:773
void visibilitymap_pin(Relation rel, BlockNumber heapBlk, Buffer *buf)
void MarkBufferDirty(Buffer buffer)
Definition: bufmgr.c:1450
void XLogRegisterBuffer(uint8 block_id, Buffer buffer, uint8 flags)
Definition: xloginsert.c:213
HeapTupleHeaderData * HeapTupleHeader
Definition: htup.h:23
#define VISIBILITYMAP_ALL_FROZEN
Definition: visibilitymap.h:27
static bool xmax_infomask_changed(uint16 new_infomask, uint16 old_infomask)
Definition: heapam.c:2977
#define HeapTupleHeaderClearHotUpdated(tup)
Definition: htup_details.h:497
#define END_CRIT_SECTION()
Definition: miscadmin.h:132
#define InvalidBuffer
Definition: buf.h:25
#define START_CRIT_SECTION()
Definition: miscadmin.h:130
int errcode(int sqlerrcode)
Definition: elog.c:575
return result
Definition: formatting.c:1618
uint32 BlockNumber
Definition: block.h:31
void ReleaseBuffer(Buffer buffer)
Definition: bufmgr.c:3309
#define BUFFER_LOCK_EXCLUSIVE
Definition: bufmgr.h:89
#define UnlockTupleTuplock(rel, tup, mode)
Definition: heapam.c:184
bool ConditionalXactLockTableWait(TransactionId xid)
Definition: lmgr.c:607
#define HEAP_XMAX_IS_SHR_LOCKED(infomask)
Definition: htup_details.h:248
void MultiXactIdSetOldestMember(void)
Definition: multixact.c:623
HeapTupleHeader t_data
Definition: htup.h:67
#define HeapTupleHeaderGetRawXmax(tup)
Definition: htup_details.h:369
unsigned short uint16
Definition: c.h:267
void pfree(void *pointer)
Definition: mcxt.c:950
#define ItemIdGetLength(itemId)
Definition: itemid.h:58
bool visibilitymap_clear(Relation rel, BlockNumber heapBlk, Buffer buf, uint8 flags)
#define ERROR
Definition: elog.h:43
#define HEAP_XMAX_INVALID
Definition: htup_details.h:193
int8 infobits_set
Definition: heapam_xlog.h:254
ItemPointerData t_ctid
Definition: htup_details.h:150
ItemPointerData t_self
Definition: htup.h:65
static void MultiXactIdWait(MultiXactId multi, MultiXactStatus status, uint16 infomask, Relation rel, ItemPointer ctid, XLTW_Oper oper, int *remaining)
Definition: heapam.c:7164
TransactionId GetCurrentTransactionId(void)
Definition: xact.c:417
uint32 t_len
Definition: htup.h:64
#define REGBUF_STANDARD
Definition: xloginsert.h:35
CommandId cmax
Definition: heapam.h:72
#define HeapTupleHeaderSetXmax(tup, xid)
Definition: htup_details.h:374
HTSU_Result
Definition: snapshot.h:119
#define RelationGetRelationName(relation)
Definition: rel.h:437
Oid t_tableOid
Definition: htup.h:66
#define SizeOfHeapLock
Definition: heapam_xlog.h:258
#define BufferGetPage(buffer)
Definition: bufmgr.h:160
#define ereport(elevel, rest)
Definition: elog.h:122
static void compute_new_xmax_infomask(TransactionId xmax, uint16 old_infomask, uint16 old_infomask2, TransactionId add_to_xmax, LockTupleMode mode, bool is_update, TransactionId *result_xmax, uint16 *result_infomask, uint16 *result_infomask2)
Definition: heapam.c:5309
TransactionId xmax
Definition: heapam.h:71
#define PageGetItemId(page, offsetNumber)
Definition: bufpage.h:232
void XLogRegisterData(char *data, int len)
Definition: xloginsert.c:323
XLogRecPtr XLogInsert(RmgrId rmid, uint8 info)
Definition: xloginsert.c:415
#define InvalidCommandId
Definition: c.h:414
#define HEAP_XMAX_IS_LOCKED_ONLY(infomask)
Definition: htup_details.h:216
void LockBuffer(Buffer buffer, int mode)
Definition: bufmgr.c:3546
#define HEAP_KEYS_UPDATED
Definition: htup_details.h:264
#define HEAP_XMAX_IS_MULTI
Definition: htup_details.h:194
static void UpdateXmaxHintBits(HeapTupleHeader tuple, Buffer buffer, TransactionId xid)
Definition: heapam.c:2300
static bool heap_acquire_tuplock(Relation relation, ItemPointer tid, LockTupleMode mode, LockWaitPolicy wait_policy, bool *have_tuple_lock)
Definition: heapam.c:5260
TransactionId MultiXactId
Definition: c.h:407
void XactLockTableWait(TransactionId xid, Relation rel, ItemPointer ctid, XLTW_Oper oper)
Definition: lmgr.c:554
#define NULL
Definition: c.h:229
uint64 XLogRecPtr
Definition: xlogdefs.h:21
#define Assert(condition)
Definition: c.h:675
Definition: lmgr.h:29
CommandId HeapTupleHeaderGetCmax(HeapTupleHeader tup)
Definition: combocid.c:119
static bool DoesMultiXactIdConflict(MultiXactId multi, uint16 infomask, LockTupleMode lockmode)
Definition: heapam.c:6997
#define ItemIdIsNormal(itemId)
Definition: itemid.h:98
WalTimeSample buffer[LAG_TRACKER_BUFFER_SIZE]
Definition: walsender.c:207
Buffer ReadBuffer(Relation reln, BlockNumber blockNum)
Definition: bufmgr.c:594
#define BufferIsValid(bufnum)
Definition: bufmgr.h:114
#define ItemPointerGetOffsetNumber(pointer)
Definition: itemptr.h:76
#define RelationNeedsWAL(relation)
Definition: rel.h:506
#define TUPLOCK_from_mxstatus(status)
Definition: heapam.c:204
static HTSU_Result heap_lock_updated_tuple(Relation rel, HeapTuple tuple, ItemPointer ctid, TransactionId xid, LockTupleMode mode)
Definition: heapam.c:5977
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define XLOG_HEAP_LOCK
Definition: heapam_xlog.h:38
int i
static MultiXactStatus get_mxact_status_for_lock(LockTupleMode mode, bool is_update)
Definition: heapam.c:4541
ItemPointerData ctid
Definition: heapam.h:70
#define HEAP_XMAX_IS_EXCL_LOCKED(infomask)
Definition: htup_details.h:250
int GetMultiXactIdMembers(MultiXactId multi, MultiXactMember **members, bool from_pgupgrade, bool onlyLock)
Definition: multixact.c:1202
#define elog
Definition: elog.h:219
#define ItemPointerGetBlockNumber(pointer)
Definition: itemptr.h:66
#define HEAP_XMAX_IS_KEYSHR_LOCKED(infomask)
Definition: htup_details.h:252
static void static void status(const char *fmt,...) pg_attribute_printf(1
Definition: pg_regress.c:224
void XLogBeginInsert(void)
Definition: xloginsert.c:120
#define PageSetLSN(page, lsn)
Definition: bufpage.h:365
int Buffer
Definition: buf.h:23
#define RelationGetRelid(relation)
Definition: rel.h:417
static bool ConditionalMultiXactIdWait(MultiXactId multi, MultiXactStatus status, uint16 infomask, Relation rel, int *remaining)
Definition: heapam.c:7186
#define PageGetItem(page, itemId)
Definition: bufpage.h:337
Pointer Page
Definition: bufpage.h:74
#define ItemPointerCopy(fromPointer, toPointer)
Definition: itemptr.h:120
void heap_multi_insert ( Relation  relation,
HeapTuple tuples,
int  ntuples,
CommandId  cid,
int  options,
BulkInsertState  bistate 
)

Definition at line 2661 of file heapam.c.

References Assert, buffer, BufferGetBlockNumber(), BufferGetPage, CacheInvalidateHeapTuple(), CHECK_FOR_INTERRUPTS, CheckForSerializableConflictIn(), xl_multi_insert_tuple::datalen, END_CRIT_SECTION, FirstOffsetNumber, xl_heap_multi_insert::flags, GetCurrentTransactionId(), HEAP_DEFAULT_FILLFACTOR, HEAP_INSERT_SKIP_WAL, heap_prepare_insert(), i, init(), InvalidBuffer, IsCatalogRelation(), ItemPointerGetOffsetNumber, log_heap_new_cid(), MarkBufferDirty(), MAXALIGN, xl_heap_multi_insert::ntuples, NULL, xl_heap_multi_insert::offsets, PageClearAllVisible, PageGetHeapFreeSpace(), PageGetMaxOffsetNumber, PageIsAllVisible, PageSetLSN, palloc(), pgstat_count_heap_insert(), REGBUF_KEEP_DATA, REGBUF_STANDARD, REGBUF_WILL_INIT, RelationGetBufferForTuple(), RelationGetTargetPageFreeSpace, RelationIsAccessibleInLogicalDecoding, RelationIsLogicallyLogged, RelationNeedsWAL, RelationPutHeapTuple(), ReleaseBuffer(), SHORTALIGN, SizeOfHeapMultiInsert, SizeofHeapTupleHeader, SizeOfMultiInsertTuple, START_CRIT_SECTION, HeapTupleData::t_data, HeapTupleHeaderData::t_hoff, xl_multi_insert_tuple::t_hoff, HeapTupleHeaderData::t_infomask, xl_multi_insert_tuple::t_infomask, HeapTupleHeaderData::t_infomask2, xl_multi_insert_tuple::t_infomask2, HeapTupleData::t_len, HeapTupleData::t_self, UnlockReleaseBuffer(), visibilitymap_clear(), VISIBILITYMAP_VALID_BITS, XLH_INSERT_ALL_VISIBLE_CLEARED, XLH_INSERT_CONTAINS_NEW_TUPLE, XLH_INSERT_LAST_IN_MULTI, XLOG_HEAP2_MULTI_INSERT, XLOG_HEAP_INIT_PAGE, XLOG_INCLUDE_ORIGIN, XLogBeginInsert(), XLogInsert(), XLogRegisterBufData(), XLogRegisterBuffer(), XLogRegisterData(), and XLogSetRecordFlags().

Referenced by CopyFromInsertBatch().

2663 {
2665  HeapTuple *heaptuples;
2666  int i;
2667  int ndone;
2668  char *scratch = NULL;
2669  Page page;
2670  bool needwal;
2671  Size saveFreeSpace;
2672  bool need_tuple_data = RelationIsLogicallyLogged(relation);
2673  bool need_cids = RelationIsAccessibleInLogicalDecoding(relation);
2674 
2675  needwal = !(options & HEAP_INSERT_SKIP_WAL) && RelationNeedsWAL(relation);
2676  saveFreeSpace = RelationGetTargetPageFreeSpace(relation,
2678 
2679  /* Toast and set header data in all the tuples */
2680  heaptuples = palloc(ntuples * sizeof(HeapTuple));
2681  for (i = 0; i < ntuples; i++)
2682  heaptuples[i] = heap_prepare_insert(relation, tuples[i],
2683  xid, cid, options);
2684 
2685  /*
2686  * Allocate some memory to use for constructing the WAL record. Using
2687  * palloc() within a critical section is not safe, so we allocate this
2688  * beforehand.
2689  */
2690  if (needwal)
2691  scratch = palloc(BLCKSZ);
2692 
2693  /*
2694  * We're about to do the actual inserts -- but check for conflict first,
2695  * to minimize the possibility of having to roll back work we've just
2696  * done.
2697  *
2698  * A check here does not definitively prevent a serialization anomaly;
2699  * that check MUST be done at least past the point of acquiring an
2700  * exclusive buffer content lock on every buffer that will be affected,
2701  * and MAY be done after all inserts are reflected in the buffers and
2702  * those locks are released; otherwise there race condition. Since
2703  * multiple buffers can be locked and unlocked in the loop below, and it
2704  * would not be feasible to identify and lock all of those buffers before
2705  * the loop, we must do a final check at the end.
2706  *
2707  * The check here could be omitted with no loss of correctness; it is
2708  * present strictly as an optimization.
2709  *
2710  * For heap inserts, we only need to check for table-level SSI locks. Our
2711  * new tuples can't possibly conflict with existing tuple locks, and heap
2712  * page locks are only consolidated versions of tuple locks; they do not
2713  * lock "gaps" as index page locks do. So we don't need to specify a
2714  * buffer when making the call, which makes for a faster check.
2715  */
2717 
2718  ndone = 0;
2719  while (ndone < ntuples)
2720  {
2721  Buffer buffer;
2722  Buffer vmbuffer = InvalidBuffer;
2723  bool all_visible_cleared = false;
2724  int nthispage;
2725 
2727 
2728  /*
2729  * Find buffer where at least the next tuple will fit. If the page is
2730  * all-visible, this will also pin the requisite visibility map page.
2731  */
2732  buffer = RelationGetBufferForTuple(relation, heaptuples[ndone]->t_len,
2733  InvalidBuffer, options, bistate,
2734  &vmbuffer, NULL);
2735  page = BufferGetPage(buffer);
2736 
2737  /* NO EREPORT(ERROR) from here till changes are logged */
2739 
2740  /*
2741  * RelationGetBufferForTuple has ensured that the first tuple fits.
2742  * Put that on the page, and then as many other tuples as fit.
2743  */
2744  RelationPutHeapTuple(relation, buffer, heaptuples[ndone], false);
2745  for (nthispage = 1; ndone + nthispage < ntuples; nthispage++)
2746  {
2747  HeapTuple heaptup = heaptuples[ndone + nthispage];
2748 
2749  if (PageGetHeapFreeSpace(page) < MAXALIGN(heaptup->t_len) + saveFreeSpace)
2750  break;
2751 
2752  RelationPutHeapTuple(relation, buffer, heaptup, false);
2753 
2754  /*
2755  * We don't use heap_multi_insert for catalog tuples yet, but
2756  * better be prepared...
2757  */
2758  if (needwal && need_cids)
2759  log_heap_new_cid(relation, heaptup);
2760  }
2761 
2762  if (PageIsAllVisible(page))
2763  {
2764  all_visible_cleared = true;
2765  PageClearAllVisible(page);
2766  visibilitymap_clear(relation,
2767  BufferGetBlockNumber(buffer),
2768  vmbuffer, VISIBILITYMAP_VALID_BITS);
2769  }
2770 
2771  /*
2772  * XXX Should we set PageSetPrunable on this page ? See heap_insert()
2773  */
2774 
2775  MarkBufferDirty(buffer);
2776 
2777  /* XLOG stuff */
2778  if (needwal)
2779  {
2780  XLogRecPtr recptr;
2781  xl_heap_multi_insert *xlrec;
2783  char *tupledata;
2784  int totaldatalen;
2785  char *scratchptr = scratch;
2786  bool init;
2787  int bufflags = 0;
2788 
2789  /*
2790  * If the page was previously empty, we can reinit the page
2791  * instead of restoring the whole thing.
2792  */
2793  init = (ItemPointerGetOffsetNumber(&(heaptuples[ndone]->t_self)) == FirstOffsetNumber &&
2794  PageGetMaxOffsetNumber(page) == FirstOffsetNumber + nthispage - 1);
2795 
2796  /* allocate xl_heap_multi_insert struct from the scratch area */
2797  xlrec = (xl_heap_multi_insert *) scratchptr;
2798  scratchptr += SizeOfHeapMultiInsert;
2799 
2800  /*
2801  * Allocate offsets array. Unless we're reinitializing the page,
2802  * in that case the tuples are stored in order starting at
2803  * FirstOffsetNumber and we don't need to store the offsets
2804  * explicitly.
2805  */
2806  if (!init)
2807  scratchptr += nthispage * sizeof(OffsetNumber);
2808 
2809  /* the rest of the scratch space is used for tuple data */
2810  tupledata = scratchptr;
2811 
2812  xlrec->flags = all_visible_cleared ? XLH_INSERT_ALL_VISIBLE_CLEARED : 0;
2813  xlrec->ntuples = nthispage;
2814 
2815  /*
2816  * Write out an xl_multi_insert_tuple and the tuple data itself
2817  * for each tuple.
2818  */
2819  for (i = 0; i < nthispage; i++)
2820  {
2821  HeapTuple heaptup = heaptuples[ndone + i];
2822  xl_multi_insert_tuple *tuphdr;
2823  int datalen;
2824 
2825  if (!init)
2826  xlrec->offsets[i] = ItemPointerGetOffsetNumber(&heaptup->t_self);
2827  /* xl_multi_insert_tuple needs two-byte alignment. */
2828  tuphdr = (xl_multi_insert_tuple *) SHORTALIGN(scratchptr);
2829  scratchptr = ((char *) tuphdr) + SizeOfMultiInsertTuple;
2830 
2831  tuphdr->t_infomask2 = heaptup->t_data->t_infomask2;
2832  tuphdr->t_infomask = heaptup->t_data->t_infomask;
2833  tuphdr->t_hoff = heaptup->t_data->t_hoff;
2834 
2835  /* write bitmap [+ padding] [+ oid] + data */
2836  datalen = heaptup->t_len - SizeofHeapTupleHeader;
2837  memcpy(scratchptr,
2838  (char *) heaptup->t_data + SizeofHeapTupleHeader,
2839  datalen);
2840  tuphdr->datalen = datalen;
2841  scratchptr += datalen;
2842  }
2843  totaldatalen = scratchptr - tupledata;
2844  Assert((scratchptr - scratch) < BLCKSZ);
2845 
2846  if (need_tuple_data)
2848 
2849  /*
2850  * Signal that this is the last xl_heap_multi_insert record
2851  * emitted by this call to heap_multi_insert(). Needed for logical
2852  * decoding so it knows when to cleanup temporary data.
2853  */
2854  if (ndone + nthispage == ntuples)
2855  xlrec->flags |= XLH_INSERT_LAST_IN_MULTI;
2856 
2857  if (init)
2858  {
2859  info |= XLOG_HEAP_INIT_PAGE;
2860  bufflags |= REGBUF_WILL_INIT;
2861  }
2862 
2863  /*
2864  * If we're doing logical decoding, include the new tuple data
2865  * even if we take a full-page image of the page.
2866  */
2867  if (need_tuple_data)
2868  bufflags |= REGBUF_KEEP_DATA;
2869 
2870  XLogBeginInsert();
2871  XLogRegisterData((char *) xlrec, tupledata - scratch);
2872  XLogRegisterBuffer(0, buffer, REGBUF_STANDARD | bufflags);
2873 
2874  XLogRegisterBufData(0, tupledata, totaldatalen);
2875 
2876  /* filtering by origin on a row level is much more efficient */
2878 
2879  recptr = XLogInsert(RM_HEAP2_ID, info);
2880 
2881  PageSetLSN(page, recptr);
2882  }
2883 
2884  END_CRIT_SECTION();
2885 
2886  UnlockReleaseBuffer(buffer);
2887  if (vmbuffer != InvalidBuffer)
2888  ReleaseBuffer(vmbuffer);
2889 
2890  ndone += nthispage;
2891  }
2892 
2893  /*
2894  * We're done with the actual inserts. Check for conflicts again, to
2895  * ensure that all rw-conflicts in to these inserts are detected. Without
2896  * this final check, a sequential scan of the heap may have locked the
2897  * table after the "before" check, missing one opportunity to detect the
2898  * conflict, and then scanned the table before the new tuples were there,
2899  * missing the other chance to detect the conflict.
2900  *
2901  * For heap inserts, we only need to check for table-level SSI locks. Our
2902  * new tuples can't possibly conflict with existing tuple locks, and heap
2903  * page locks are only consolidated versions of tuple locks; they do not
2904  * lock "gaps" as index page locks do. So we don't need to specify a
2905  * buffer when making the call.
2906  */
2908 
2909  /*
2910  * If tuples are cachable, mark them for invalidation from the caches in
2911  * case we abort. Note it is OK to do this after releasing the buffer,
2912  * because the heaptuples data structure is all in local memory, not in
2913  * the shared buffer.
2914  */
2915  if (IsCatalogRelation(relation))
2916  {
2917  for (i = 0; i < ntuples; i++)
2918  CacheInvalidateHeapTuple(relation, heaptuples[i], NULL);
2919  }
2920 
2921  /*
2922  * Copy t_self fields back to the caller's original tuples. This does
2923  * nothing for untoasted tuples (tuples[i] == heaptuples[i)], but it's
2924  * probably faster to always copy than check.
2925  */
2926  for (i = 0; i < ntuples; i++)
2927  tuples[i]->t_self = heaptuples[i]->t_self;
2928 
2929  pgstat_count_heap_insert(relation, ntuples);
2930 }
void XLogRegisterBufData(uint8 block_id, char *data, int len)
Definition: xloginsert.c:361
#define SizeofHeapTupleHeader
Definition: htup_details.h:170
bool IsCatalogRelation(Relation relation)
Definition: catalog.c:91
static XLogRecPtr log_heap_new_cid(Relation relation, HeapTuple tup)
Definition: heapam.c:7748
void CacheInvalidateHeapTuple(Relation relation, HeapTuple tuple, HeapTuple newtuple)
Definition: inval.c:1087
static HeapTuple heap_prepare_insert(Relation relation, HeapTuple tup, TransactionId xid, CommandId cid, int options)
Definition: heapam.c:2583
#define PageIsAllVisible(page)
Definition: bufpage.h:382
uint32 TransactionId
Definition: c.h:397
OffsetNumber offsets[FLEXIBLE_ARRAY_MEMBER]
Definition: heapam_xlog.h:155
void MarkBufferDirty(Buffer buffer)
Definition: bufmgr.c:1450
void XLogRegisterBuffer(uint8 block_id, Buffer buffer, uint8 flags)
Definition: xloginsert.c:213
#define END_CRIT_SECTION()
Definition: miscadmin.h:132
unsigned char uint8
Definition: c.h:266
#define InvalidBuffer
Definition: buf.h:25
#define SizeOfHeapMultiInsert
Definition: heapam_xlog.h:158
#define REGBUF_WILL_INIT
Definition: xloginsert.h:32
#define START_CRIT_SECTION()
Definition: miscadmin.h:130
#define XLOG_INCLUDE_ORIGIN
Definition: xlog.h:192
#define HEAP_INSERT_SKIP_WAL
Definition: heapam.h:28
void ReleaseBuffer(Buffer buffer)
Definition: bufmgr.c:3309
#define RelationIsLogicallyLogged(relation)
Definition: rel.h:576
#define PageGetMaxOffsetNumber(page)
Definition: bufpage.h:354
void RelationPutHeapTuple(Relation relation, Buffer buffer, HeapTuple tuple, bool token)
Definition: hio.c:36
void CheckForSerializableConflictIn(Relation relation, HeapTuple tuple, Buffer buffer)
Definition: predicate.c:4243
#define XLOG_HEAP_INIT_PAGE
Definition: heapam_xlog.h:46
#define XLOG_HEAP2_MULTI_INSERT
Definition: heapam_xlog.h:58
uint16 OffsetNumber
Definition: off.h:24
#define VISIBILITYMAP_VALID_BITS
Definition: visibilitymap.h:28
HeapTupleHeader t_data
Definition: htup.h:67
bool visibilitymap_clear(Relation rel, BlockNumber heapBlk, Buffer buf, uint8 flags)
void UnlockReleaseBuffer(Buffer buffer)
Definition: bufmgr.c:3332
Size PageGetHeapFreeSpace(Page page)
Definition: bufpage.c:666
#define XLH_INSERT_CONTAINS_NEW_TUPLE
Definition: heapam_xlog.h:69
ItemPointerData t_self
Definition: htup.h:65
TransactionId GetCurrentTransactionId(void)
Definition: xact.c:417
uint32 t_len
Definition: htup.h:64
#define FirstOffsetNumber
Definition: off.h:27
#define REGBUF_STANDARD
Definition: xloginsert.h:35
Buffer RelationGetBufferForTuple(Relation relation, Size len, Buffer otherBuffer, int options, BulkInsertState bistate, Buffer *vmbuffer, Buffer *vmbuffer_other)
Definition: hio.c:297
void XLogSetRecordFlags(uint8 flags)
Definition: xloginsert.c:397
#define BufferGetPage(buffer)
Definition: bufmgr.h:160
#define RelationGetTargetPageFreeSpace(relation, defaultff)
Definition: rel.h:308
#define XLH_INSERT_LAST_IN_MULTI
Definition: heapam_xlog.h:67
void XLogRegisterData(char *data, int len)
Definition: xloginsert.c:323
XLogRecPtr XLogInsert(RmgrId rmid, uint8 info)
Definition: xloginsert.c:415
#define RelationIsAccessibleInLogicalDecoding(relation)
Definition: rel.h:560
#define REGBUF_KEEP_DATA
Definition: xloginsert.h:38
#define PageClearAllVisible(page)
Definition: bufpage.h:386
#define NULL
Definition: c.h:229
uint64 XLogRecPtr
Definition: xlogdefs.h:21
#define Assert(condition)
Definition: c.h:675
WalTimeSample buffer[LAG_TRACKER_BUFFER_SIZE]
Definition: walsender.c:207
size_t Size
Definition: c.h:356
#define MAXALIGN(LEN)
Definition: c.h:588
#define ItemPointerGetOffsetNumber(pointer)
Definition: itemptr.h:76
static void init(bool is_no_vacuum)
Definition: pgbench.c:2571
#define RelationNeedsWAL(relation)
Definition: rel.h:506
#define XLH_INSERT_ALL_VISIBLE_CLEARED
Definition: heapam_xlog.h:66
BlockNumber BufferGetBlockNumber(Buffer buffer)
Definition: bufmgr.c:2605
void pgstat_count_heap_insert(Relation rel, PgStat_Counter n)
Definition: pgstat.c:1806
void * palloc(Size size)
Definition: mcxt.c:849
int i
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:97
#define HEAP_DEFAULT_FILLFACTOR
Definition: rel.h:287
#define SHORTALIGN(LEN)
Definition: c.h:584
void XLogBeginInsert(void)
Definition: xloginsert.c:120
#define PageSetLSN(page, lsn)
Definition: bufpage.h:365
int Buffer
Definition: buf.h:23
Pointer Page
Definition: bufpage.h:74
#define SizeOfMultiInsertTuple
Definition: heapam_xlog.h:169
Relation heap_open ( Oid  relationId,
LOCKMODE  lockmode 
)

Definition at line 1287 of file heapam.c.

References ereport, errcode(), errmsg(), ERROR, RelationData::rd_rel, relation_open(), RelationGetRelationName, RELKIND_COMPOSITE_TYPE, and RELKIND_INDEX.

Referenced by acquire_inherited_sample_rows(), AcquireRewriteLocks(), AddEnumLabel(), AddNewAttributeTuples(), AddRoleMems(), AfterTriggerSetState(), AggregateCreate(), AlterCollation(), AlterConstraintNamespaces(), AlterDatabase(), AlterDatabaseOwner(), AlterDomainAddConstraint(), AlterDomainDefault(), AlterDomainDropConstraint(), AlterDomainNotNull(), AlterDomainValidateConstraint(), AlterEventTrigger(), AlterEventTriggerOwner(), AlterEventTriggerOwner_oid(), AlterExtensionNamespace(), AlterForeignDataWrapper(), AlterForeignDataWrapperOwner(), AlterForeignDataWrapperOwner_oid(), AlterForeignServer(), AlterForeignServerOwner(), AlterForeignServerOwner_oid(), AlterFunction(), AlterObjectNamespace_oid(), AlterOperator(), AlterPolicy(), AlterPublication(), AlterPublicationOwner(), AlterPublicationOwner_oid(), AlterPublicationTables(), AlterRole(), AlterSchemaOwner(), AlterSchemaOwner_oid(), AlterSeqNamespaces(), AlterSequence(), AlterSetting(), AlterSubscription(), AlterSubscriptionOwner(), AlterSubscriptionOwner_oid(), AlterTableMoveAll(), AlterTableNamespaceInternal(), AlterTableSpaceOptions(), AlterTSConfiguration(), AlterTSDictionary(), AlterTypeNamespaceInternal(), AlterTypeOwner(), AlterTypeOwner_oid(), AlterTypeOwnerInternal(), AlterUserMapping(), AppendAttributeTuples(), ApplyExtensionUpdates(), AssignTypeArrayOid(), ATAddCheckConstraint(), ATAddForeignKeyConstraint(), ATExecAddColumn(), ATExecAddOf(), ATExecAlterColumnGenericOptions(), ATExecAlterColumnType(), ATExecAlterConstraint(), ATExecAttachPartition(), ATExecChangeOwner(), ATExecDetachPartition(), ATExecDisableRowSecurity(), ATExecDropColumn(), ATExecDropConstraint(), ATExecDropNotNull(), ATExecDropOf(), ATExecEnableRowSecurity(), ATExecForceNoForceRowSecurity(), ATExecGenericOptions(), ATExecSetNotNull(), ATExecSetOptions(), ATExecSetRelOptions(), ATExecSetStatistics(), ATExecSetStorage(), ATExecSetTableSpace(), ATExecValidateConstraint(), ATPrepChangePersistence(), ATRewriteTable(), ATRewriteTables(), AttrDefaultFetch(), boot_openrel(), brin_summarize_new_values(), bringetbitmap(), brinvacuumcleanup(), bt_index_check_internal(), build_indices(), build_physical_tlist(), BuildRelationExtStatistics(), CatalogCacheInitializeCache(), change_owner_fix_column_acls(), change_owner_recurse_to_sequences(), changeDependencyFor(), changeDependencyOnOwner(), check_db_file_conflict(), check_selective_binary_conversion(), CheckAndCreateToastTable(), CheckConstraintFetch(), checkSharedDependencies(), ChooseConstraintName(), cluster(), CollationCreate(), ConstraintNameIsUsed(), ConversionCreate(), copy_heap_data(), copyTemplateDependencies(), CountDBSubscriptions(), create_proc_lang(), create_toast_table(), CreateAccessMethod(), CreateCast(), CreateComments(), CreateConstraintEntry(), createdb(), CreateForeignDataWrapper(), CreateForeignServer(), CreateForeignTable(), CreateInheritance(), CreateOpFamily(), CreatePolicy(), CreatePublication(), CreateRole(), CreateSharedComments(), CreateStatistics(), CreateSubscription(), CreateTableSpace(), CreateTransform(), CreateTrigger(), CreateUserMapping(), currtid_byreloid(), database_to_xmlschema_internal(), DefineIndex(), DefineOpClass(), DefineQueryRewrite(), DefineRelation(), DefineSequence(), DefineTSConfiguration(), DefineTSDictionary(), DefineTSParser(), DefineTSTemplate(), DeleteAttributeTuples(), DeleteComments(), deleteDependencyRecordsFor(), deleteDependencyRecordsForClass(), DeleteInitPrivs(), deleteOneObject(), DeleteRelationTuple(), DeleteSecurityLabel(), DeleteSequenceTuple(), DeleteSharedComments(), deleteSharedDependencyRecordsFor(), DeleteSharedSecurityLabel(), DeleteSystemAttributeTuples(), DelRoleMems(), deparseColumnRef(), deparseFromExprForRel(), deparseSelectSql(), do_autovacuum(), drop_parent_dependency(), DropCastById(), dropDatabaseDependencies(), dropdb(), DropProceduralLanguageById(), DropRole(), DropSetting(), DropSubscription(), DropTableSpace(), DropTransformById(), EnableDisableRule(), EnableDisableTrigger(), enum_endpoint(), enum_range_internal(), EnumValuesCreate(), EnumValuesDelete(), EventTriggerSQLDropAddObject(), exec_object_restorecon(), ExecAlterExtensionStmt(), ExecAlterObjectSchemaStmt(), ExecAlterOwnerStmt(), ExecGetTriggerResultRel(), ExecGrant_Database(), ExecGrant_Fdw(), ExecGrant_ForeignServer(), ExecGrant_Function(), ExecGrant_Language(), ExecGrant_Largeobject(), ExecGrant_Namespace(), ExecGrant_Relation(), ExecGrant_Tablespace(), ExecGrant_Type(), ExecInitModifyTable(), ExecOpenScanRelation(), ExecRefreshMatView(), ExecRenameStmt(), ExecSetupPartitionTupleRouting(), ExecuteTruncate(), expand_inherited_rtentry(), expand_targetlist(), extension_config_remove(), find_composite_type_dependencies(), find_inheritance_children(), find_language_template(), find_typed_table_dependencies(), finish_heap_swap(), fireRIRrules(), generate_partition_qual(), get_actual_variable_range(), get_constraint_index(), get_database_list(), get_database_oid(), get_db_info(), get_domain_constraint_oid(), get_extension_name(), get_extension_oid(), get_extension_schema(), get_file_fdw_attribute_options(), get_index_constraint(), get_partition_parent(), get_pkey_attnames(), get_primary_key_attnos(), get_rel_oids(), get_relation_constraint_oid(), get_relation_constraints(), get_relation_data_width(), get_relation_info(), get_relation_policy_oid(), get_rels_with_domain(), get_row_security_policies(), get_subscription_list(), get_tables_to_cluster(), get_tablespace_name(), get_tablespace_oid(), get_trigger_oid(), GetAllTablesPublicationRelations(), GetAllTablesPublications(), GetComment(), getConstraintTypeDescription(), GetDatabaseTuple(), GetDatabaseTupleByOid(), GetDefaultOpClass(), getExtensionOfObject(), getObjectDescription(), getObjectIdentityParts(), getOwnedSequences(), GetPublicationRelations(), getRelationsInNamespace(), GetSecurityLabel(), GetSharedSecurityLabel(), GetSubscriptionNotReadyRelations(), GetSubscriptionRelations(), GetSubscriptionRelState(), gettype(), GrantRole(), has_row_triggers(), heap_create_with_catalog(), heap_drop_with_catalog(), heap_sync(), heap_truncate(), heap_truncate_find_FKs(), heap_truncate_one_rel(), index_build(), index_constraint_create(), index_create(), index_drop(), index_set_state_flags(), index_update_stats(), infer_arbiter_indexes(), InitPlan(), insert_event_trigger_tuple(), InsertExtensionTuple(), InsertRule(), intorel_startup(), isQueryUsingTempRelation_walker(), LargeObjectCreate(), LargeObjectDrop(), LargeObjectExists(), load_domaintype_info(), load_enum_cache_data(), logicalrep_rel_open(), LogicalRepSyncTableStart(), lookup_ts_config_cache(), LookupOpclassInfo(), make_new_heap(), make_viewdef(), makeArrayTypeName(), mark_index_clustered(), MergeAttributesIntoExisting(), MergeConstraintsIntoExisting(), MergeWithExistingConstraint(), movedb(), myLargeObjectExists(), NamespaceCreate(), objectsInSchemaToOids(), open_lo_relation(), OpenTableList(), OperatorCreate(), OperatorShellMake(), OperatorUpd(), performDeletion(), performMultipleDeletions(), pg_event_trigger_ddl_commands(), pg_extension_config_dump(), pg_extension_ownercheck(), pg_get_constraintdef_worker(), pg_get_replica_identity_index(), pg_get_serial_sequence(), pg_get_triggerdef_worker(), pg_identify_object(), pg_largeobject_aclmask_snapshot(), pg_largeobject_ownercheck(), pgstat_collect_oids(), postgresPlanDirectModify(), postgresPlanForeignModify(), ProcedureCreate(), process_settings(), publication_add_relation(), RangeCreate(), RangeDelete(), recordExtensionInitPrivWorker(), recordExtObjInitPriv(), recordMultipleDependencies(), recordSharedDependencyOn(), refresh_by_match_merge(), regclassin(), regoperin(), regprocin(), regtypein(), reindex_index(), reindex_relation(), ReindexMultipleTables(), relation_has_policies(), relation_mark_replica_identity(), RelationBuildRowSecurity(), RelationBuildRuleLock(), RelationBuildTriggers(), RelationBuildTupleDesc(), RelationGetExclusionInfo(), RelationGetFKeyList(), RelationGetIndexList(), RelationGetPartitionDispatchInfo(), RelationGetStatExtList(), RelationRemoveInheritance(), RelationSetNewRelfilenode(), RelidByRelfilenode(), remove_dbtablespaces(), RemoveAccessMethodById(), RemoveAmOpEntryById(), RemoveAmProcEntryById(), RemoveAttrDefault(), RemoveAttrDefaultById(), RemoveAttributeById(), RemoveCollationById(), RemoveConstraintById(), RemoveConversionById(), RemoveDefaultACLById(), RemoveEventTriggerById(), RemoveExtensionById(), RemoveForeignDataWrapperById(), RemoveForeignServerById(), RemoveFunctionById(), RemoveInheritance(), RemoveOpClassById(), RemoveOperatorById(), RemoveOpFamilyById(), RemovePartitionKeyByRelId(), RemovePolicyById(), RemovePublicationById(), RemovePublicationRelById(), RemoveRewriteRuleById(), RemoveRoleFromObjectACL(), RemoveRoleFromObjectPolicy(), RemoveSchemaById(), RemoveStatistics(), RemoveStatisticsById(), RemoveStatisticsExt(), RemoveSubscriptionRel(), RemoveTriggerById(), RemoveTSConfigurationById(), RemoveTSDictionaryById(), RemoveTSParserById(), RemoveTSTemplateById(), RemoveTypeById(), RemoveUserMappingById(), rename_policy(), renameatt_internal(), RenameConstraint(), RenameConstraintById(), RenameDatabase(), RenameEnumLabel(), RenameRelationInternal(), RenameRewriteRule(), RenameRole(), RenameSchema(), RenameTableSpace(), renametrig(), RenameType(), RenameTypeInternal(), replorigin_create(), replorigin_drop(), RewriteQuery(), rewriteTargetView(), RI_FKey_cascade_del(), RI_FKey_cascade_upd(), RI_FKey_check(), RI_FKey_setdefault_del(), RI_FKey_setdefault_upd(), RI_FKey_setnull_del(), RI_FKey_setnull_upd(), ri_restrict_del(), ri_restrict_upd(), ScanPgRelation(), schema_to_xmlschema_internal(), SearchCatCache(), SearchCatCacheList(), sepgsql_attribute_post_create(), sepgsql_database_post_create(), sepgsql_index_modify(), sepgsql_proc_post_create(), sepgsql_proc_setattr(), sepgsql_relation_post_create(), sepgsql_relation_setattr(), sepgsql_schema_post_create(), sequenceIsOwned(), SetDefaultACL(), SetFunctionArgType(), SetFunctionReturnType(), SetMatViewPopulatedState(), SetRelationHasSubclass(), SetRelationNumChecks(), SetRelationRuleStatus(), SetSecurityLabel(), SetSharedSecurityLabel(), SetSubscriptionRelState(), shdepDropOwned(), shdepReassignOwned(), StoreAttrDefault(), StoreCatalogInheritance(), storeOperators(), StorePartitionBound(), StorePartitionKey(), storeProcedures(), swap_relation_files(), table_to_xml_and_xmlschema(), table_to_xmlschema(), ThereIsAtLeastOneRole(), toast_delete_datum(), toast_fetch_datum(), toast_fetch_datum_slice(), toast_get_valid_index(), toast_save_datum(), toastid_valueid_exists(), transientrel_startup(), TypeCreate(), typeInheritsFrom(), TypeShellMake(), update_attstats(), updateAclDependencies(), UpdateIndexRelation(), vac_truncate_clog(), vac_update_datfrozenxid(), vac_update_relstats(), and validate_index().

1288 {
1289  Relation r;
1290 
1291  r = relation_open(relationId, lockmode);
1292 
1293  if (r->rd_rel->relkind == RELKIND_INDEX)
1294  ereport(ERROR,
1295  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1296  errmsg("\"%s\" is an index",
1298  else if (r->rd_rel->relkind == RELKIND_COMPOSITE_TYPE)
1299  ereport(ERROR,
1300  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1301  errmsg("\"%s\" is a composite type",
1303 
1304  return r;
1305 }
int errcode(int sqlerrcode)
Definition: elog.c:575
Form_pg_class rd_rel
Definition: rel.h:114
#define RELKIND_COMPOSITE_TYPE
Definition: pg_class.h:166
#define ERROR
Definition: elog.h:43
#define RelationGetRelationName(relation)
Definition: rel.h:437
#define ereport(elevel, rest)
Definition: elog.h:122
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define RELKIND_INDEX
Definition: pg_class.h:161
Relation relation_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1117
Relation heap_openrv ( const RangeVar relation,
LOCKMODE  lockmode 
)

Definition at line 1315 of file heapam.c.

References ereport, errcode(), errmsg(), ERROR, RelationData::rd_rel, relation_openrv(), RelationGetRelationName, RELKIND_COMPOSITE_TYPE, and RELKIND_INDEX.

Referenced by ATAddForeignKeyConstraint(), ATExecAddInherit(), ATExecAttachPartition(), ATExecDetachPartition(), ATExecDropInherit(), boot_openrel(), BootstrapToastTable(), CreateStatistics(), CreateTrigger(), currtid_byrelname(), DefineIndex(), DoCopy(), ExecuteTruncate(), get_rel_from_relname(), MergeAttributes(), OpenTableList(), pgrowlocks(), transformIndexConstraint(), and transformRuleStmt().

1316 {
1317  Relation r;
1318 
1319  r = relation_openrv(relation, lockmode);
1320 
1321  if (r->rd_rel->relkind == RELKIND_INDEX)
1322  ereport(ERROR,
1323  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1324  errmsg("\"%s\" is an index",
1326  else if (r->rd_rel->relkind == RELKIND_COMPOSITE_TYPE)
1327  ereport(ERROR,
1328  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1329  errmsg("\"%s\" is a composite type",
1331 
1332  return r;
1333 }
Relation relation_openrv(const RangeVar *relation, LOCKMODE lockmode)
Definition: heapam.c:1195
int errcode(int sqlerrcode)
Definition: elog.c:575
Form_pg_class rd_rel
Definition: rel.h:114
#define RELKIND_COMPOSITE_TYPE
Definition: pg_class.h:166
#define ERROR
Definition: elog.h:43
#define RelationGetRelationName(relation)
Definition: rel.h:437
#define ereport(elevel, rest)
Definition: elog.h:122
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define RELKIND_INDEX
Definition: pg_class.h:161
Relation heap_openrv_extended ( const RangeVar relation,
LOCKMODE  lockmode,
bool  missing_ok 
)

Definition at line 1344 of file heapam.c.

References ereport, errcode(), errmsg(), ERROR, RelationData::rd_rel, relation_openrv_extended(), RelationGetRelationName, RELKIND_COMPOSITE_TYPE, and RELKIND_INDEX.

Referenced by get_object_address_relobject(), and parserOpenTable().

1346 {
1347  Relation r;
1348 
1349  r = relation_openrv_extended(relation, lockmode, missing_ok);
1350 
1351  if (r)
1352  {
1353  if (r->rd_rel->relkind == RELKIND_INDEX)
1354  ereport(ERROR,
1355  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1356  errmsg("\"%s\" is an index",
1358  else if (r->rd_rel->relkind == RELKIND_COMPOSITE_TYPE)
1359  ereport(ERROR,
1360  (errcode(ERRCODE_WRONG_OBJECT_TYPE),
1361  errmsg("\"%s\" is a composite type",
1363  }
1364 
1365  return r;
1366 }
int errcode(int sqlerrcode)
Definition: elog.c:575
Form_pg_class rd_rel
Definition: rel.h:114
#define RELKIND_COMPOSITE_TYPE
Definition: pg_class.h:166
#define ERROR
Definition: elog.h:43
#define RelationGetRelationName(relation)
Definition: rel.h:437
#define ereport(elevel, rest)
Definition: elog.h:122
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define RELKIND_INDEX
Definition: pg_class.h:161
Relation relation_openrv_extended(const RangeVar *relation, LOCKMODE lockmode, bool missing_ok)
Definition: heapam.c:1230
int heap_page_prune ( Relation  relation,
Buffer  buffer,
TransactionId  OldestXmin,
bool  report_stats,
TransactionId latestRemovedXid 
)

Definition at line 182 of file pruneheap.c.

References BufferGetPage, END_CRIT_SECTION, FirstOffsetNumber, heap_page_prune_execute(), heap_prune_chain(), InvalidTransactionId, ItemIdIsDead, ItemIdIsUsed, PruneState::latestRemovedXid, log_heap_clean(), MarkBufferDirty(), MarkBufferDirtyHint(), PruneState::marked, PruneState::ndead, PruneState::new_prune_xid, PruneState::nowdead, PruneState::nowunused, PruneState::nredirected, PruneState::nunused, OffsetNumberNext, PageClearFull, PageGetItemId, PageGetMaxOffsetNumber, PageIsFull, PageSetLSN, pgstat_update_heap_dead_tuples(), PruneState::redirected, RelationNeedsWAL, and START_CRIT_SECTION.

Referenced by heap_page_prune_opt(), and lazy_scan_heap().

184 {
185  int ndeleted = 0;
186  Page page = BufferGetPage(buffer);
187  OffsetNumber offnum,
188  maxoff;
189  PruneState prstate;
190 
191  /*
192  * Our strategy is to scan the page and make lists of items to change,
193  * then apply the changes within a critical section. This keeps as much
194  * logic as possible out of the critical section, and also ensures that
195  * WAL replay will work the same as the normal case.
196  *
197  * First, initialize the new pd_prune_xid value to zero (indicating no
198  * prunable tuples). If we find any tuples which may soon become
199  * prunable, we will save the lowest relevant XID in new_prune_xid. Also
200  * initialize the rest of our working state.
201  */
203  prstate.latestRemovedXid = *latestRemovedXid;
204  prstate.nredirected = prstate.ndead = prstate.nunused = 0;
205  memset(prstate.marked, 0, sizeof(prstate.marked));
206 
207  /* Scan the page */
208  maxoff = PageGetMaxOffsetNumber(page);
209  for (offnum = FirstOffsetNumber;
210  offnum <= maxoff;
211  offnum = OffsetNumberNext(offnum))
212  {
213  ItemId itemid;
214 
215  /* Ignore items already processed as part of an earlier chain */
216  if (prstate.marked[offnum])
217  continue;
218 
219  /* Nothing to do if slot is empty or already dead */
220  itemid = PageGetItemId(page, offnum);
221  if (!ItemIdIsUsed(itemid) || ItemIdIsDead(itemid))
222  continue;
223 
224  /* Process this item or chain of items */
225  ndeleted += heap_prune_chain(relation, buffer, offnum,
226  OldestXmin,
227  &prstate);
228  }
229 
230  /* Any error while applying the changes is critical */
232 
233  /* Have we found any prunable items? */
234  if (prstate.nredirected > 0 || prstate.ndead > 0 || prstate.nunused > 0)
235  {
236  /*
237  * Apply the planned item changes, then repair page fragmentation, and
238  * update the page's hint bit about whether it has free line pointers.
239  */
241  prstate.redirected, prstate.nredirected,
242  prstate.nowdead, prstate.ndead,
243  prstate.nowunused, prstate.nunused);
244 
245  /*
246  * Update the page's pd_prune_xid field to either zero, or the lowest
247  * XID of any soon-prunable tuple.
248  */
249  ((PageHeader) page)->pd_prune_xid = prstate.new_prune_xid;
250 
251  /*
252  * Also clear the "page is full" flag, since there's no point in
253  * repeating the prune/defrag process until something else happens to
254  * the page.
255  */
256  PageClearFull(page);
257 
259 
260  /*
261  * Emit a WAL HEAP_CLEAN record showing what we did
262  */
263  if (RelationNeedsWAL(relation))
264  {
265  XLogRecPtr recptr;
266 
267  recptr = log_heap_clean(relation, buffer,
268  prstate.redirected, prstate.nredirected,
269  prstate.nowdead, prstate.ndead,
270  prstate.nowunused, prstate.nunused,
271  prstate.latestRemovedXid);
272 
273  PageSetLSN(BufferGetPage(buffer), recptr);
274  }
275  }
276  else
277  {
278  /*
279  * If we didn't prune anything, but have found a new value for the
280  * pd_prune_xid field, update it and mark the buffer dirty. This is
281  * treated as a non-WAL-logged hint.
282  *
283  * Also clear the "page is full" flag if it is set, since there's no
284  * point in repeating the prune/defrag process until something else
285  * happens to the page.
286  */
287  if (((PageHeader) page)->pd_prune_xid != prstate.new_prune_xid ||
288  PageIsFull(page))
289  {
290  ((PageHeader) page)->pd_prune_xid = prstate.new_prune_xid;
291  PageClearFull(page);
293  }
294  }
295 
297 
298  /*
299  * If requested, report the number of tuples reclaimed to pgstats. This is
300  * ndeleted minus ndead, because we don't want to count a now-DEAD root
301  * item as a deletion for this purpose.
302  */
303  if (report_stats && ndeleted > prstate.ndead)
304  pgstat_update_heap_dead_tuples(relation, ndeleted - prstate.ndead);
305 
306  *latestRemovedXid = prstate.latestRemovedXid;
307 
308  /*
309  * XXX Should we update the FSM information of this page ?
310  *
311  * There are two schools of thought here. We may not want to update FSM
312  * information so that the page is not used for unrelated UPDATEs/INSERTs
313  * and any free space in this page will remain available for further
314  * UPDATEs in *this* page, thus improving chances for doing HOT updates.
315  *
316  * But for a large table and where a page does not receive further UPDATEs
317  * for a long time, we might waste this space by not updating the FSM
318  * information. The relation may get extended and fragmented further.
319  *
320  * One possibility is to leave "fillfactor" worth of space in this page
321  * and update FSM with the remaining space.
322  */
323 
324  return ndeleted;
325 }
static int heap_prune_chain(Relation relation, Buffer buffer, OffsetNumber rootoffnum, TransactionId OldestXmin, PruneState *prstate)
Definition: pruneheap.c:354
int nredirected
Definition: pruneheap.c:36
void pgstat_update_heap_dead_tuples(Relation rel, int delta)
Definition: pgstat.c:1936
void MarkBufferDirtyHint(Buffer buffer, bool buffer_std)
Definition: bufmgr.c:3379
void MarkBufferDirty(Buffer buffer)
Definition: bufmgr.c:1450
#define END_CRIT_SECTION()
Definition: miscadmin.h:132
#define ItemIdIsUsed(itemId)
Definition: itemid.h:91
#define START_CRIT_SECTION()
Definition: miscadmin.h:130
OffsetNumber nowdead[MaxHeapTuplesPerPage]
Definition: pruneheap.c:41
#define ItemIdIsDead(itemId)
Definition: itemid.h:112