PostgreSQL Source Code  git master
xact.c File Reference
#include "postgres.h"
#include <time.h>
#include <unistd.h>
#include "access/commit_ts.h"
#include "access/multixact.h"
#include "access/parallel.h"
#include "access/subtrans.h"
#include "access/transam.h"
#include "access/twophase.h"
#include "access/xact.h"
#include "access/xlog.h"
#include "access/xloginsert.h"
#include "access/xlogutils.h"
#include "catalog/namespace.h"
#include "catalog/storage.h"
#include "commands/async.h"
#include "commands/tablecmds.h"
#include "commands/trigger.h"
#include "executor/spi.h"
#include "libpq/be-fsstubs.h"
#include "libpq/pqsignal.h"
#include "miscadmin.h"
#include "pgstat.h"
#include "replication/logical.h"
#include "replication/logicallauncher.h"
#include "replication/origin.h"
#include "replication/syncrep.h"
#include "replication/walsender.h"
#include "storage/condition_variable.h"
#include "storage/fd.h"
#include "storage/lmgr.h"
#include "storage/predicate.h"
#include "storage/proc.h"
#include "storage/procarray.h"
#include "storage/sinvaladt.h"
#include "storage/smgr.h"
#include "utils/builtins.h"
#include "utils/catcache.h"
#include "utils/combocid.h"
#include "utils/guc.h"
#include "utils/inval.h"
#include "utils/memutils.h"
#include "utils/relmapper.h"
#include "utils/snapmgr.h"
#include "utils/timeout.h"
#include "utils/timestamp.h"
#include "pg_trace.h"
Include dependency graph for xact.c:

Go to the source code of this file.

Data Structures

struct  TransactionStateData
 
struct  XactCallbackItem
 
struct  SubXactCallbackItem
 

Typedefs

typedef enum TransState TransState
 
typedef enum TBlockState TBlockState
 
typedef struct TransactionStateData TransactionStateData
 
typedef TransactionStateDataTransactionState
 
typedef struct XactCallbackItem XactCallbackItem
 
typedef struct SubXactCallbackItem SubXactCallbackItem
 

Enumerations

enum  TransState {
  TRANS_DEFAULT, TRANS_START, TRANS_INPROGRESS, TRANS_COMMIT,
  TRANS_ABORT, TRANS_PREPARE
}
 
enum  TBlockState {
  TBLOCK_DEFAULT, TBLOCK_STARTED, TBLOCK_BEGIN, TBLOCK_INPROGRESS,
  TBLOCK_IMPLICIT_INPROGRESS, TBLOCK_PARALLEL_INPROGRESS, TBLOCK_END, TBLOCK_ABORT,
  TBLOCK_ABORT_END, TBLOCK_ABORT_PENDING, TBLOCK_PREPARE, TBLOCK_SUBBEGIN,
  TBLOCK_SUBINPROGRESS, TBLOCK_SUBRELEASE, TBLOCK_SUBCOMMIT, TBLOCK_SUBABORT,
  TBLOCK_SUBABORT_END, TBLOCK_SUBABORT_PENDING, TBLOCK_SUBRESTART, TBLOCK_SUBABORT_RESTART
}
 

Functions

static void AssignTransactionId (TransactionState s)
 
static void AbortTransaction (void)
 
static void AtAbort_Memory (void)
 
static void AtCleanup_Memory (void)
 
static void AtAbort_ResourceOwner (void)
 
static void AtCCI_LocalCache (void)
 
static void AtCommit_Memory (void)
 
static void AtStart_Cache (void)
 
static void AtStart_Memory (void)
 
static void AtStart_ResourceOwner (void)
 
static void CallXactCallbacks (XactEvent event)
 
static void CallSubXactCallbacks (SubXactEvent event, SubTransactionId mySubid, SubTransactionId parentSubid)
 
static void CleanupTransaction (void)
 
static void CheckTransactionBlock (bool isTopLevel, bool throwError, const char *stmtType)
 
static void CommitTransaction (void)
 
static TransactionId RecordTransactionAbort (bool isSubXact)
 
static void StartTransaction (void)
 
static void StartSubTransaction (void)
 
static void CommitSubTransaction (void)
 
static void AbortSubTransaction (void)
 
static void CleanupSubTransaction (void)
 
static void PushTransaction (void)
 
static void PopTransaction (void)
 
static void AtSubAbort_Memory (void)
 
static void AtSubCleanup_Memory (void)
 
static void AtSubAbort_ResourceOwner (void)
 
static void AtSubCommit_Memory (void)
 
static void AtSubStart_Memory (void)
 
static void AtSubStart_ResourceOwner (void)
 
static void ShowTransactionState (const char *str)
 
static void ShowTransactionStateRec (const char *str, TransactionState state)
 
static const char * BlockStateAsString (TBlockState blockState)
 
static const char * TransStateAsString (TransState state)
 
bool IsTransactionState (void)
 
bool IsAbortedTransactionBlockState (void)
 
TransactionId GetTopTransactionId (void)
 
TransactionId GetTopTransactionIdIfAny (void)
 
TransactionId GetCurrentTransactionId (void)
 
TransactionId GetCurrentTransactionIdIfAny (void)
 
void MarkCurrentTransactionIdLoggedIfAny (void)
 
TransactionId GetStableLatestTransactionId (void)
 
SubTransactionId GetCurrentSubTransactionId (void)
 
bool SubTransactionIsActive (SubTransactionId subxid)
 
CommandId GetCurrentCommandId (bool used)
 
TimestampTz GetCurrentTransactionStartTimestamp (void)
 
TimestampTz GetCurrentStatementStartTimestamp (void)
 
TimestampTz GetCurrentTransactionStopTimestamp (void)
 
void SetCurrentStatementStartTimestamp (void)
 
static void SetCurrentTransactionStopTimestamp (void)
 
int GetCurrentTransactionNestLevel (void)
 
bool TransactionIdIsCurrentTransactionId (TransactionId xid)
 
bool TransactionStartedDuringRecovery (void)
 
void EnterParallelMode (void)
 
void ExitParallelMode (void)
 
bool IsInParallelMode (void)
 
void CommandCounterIncrement (void)
 
void ForceSyncCommit (void)
 
static TransactionId RecordTransactionCommit (void)
 
static void AtSubCommit_childXids (void)
 
static void AtSubAbort_childXids (void)
 
static void PrepareTransaction (void)
 
void StartTransactionCommand (void)
 
void CommitTransactionCommand (void)
 
void AbortCurrentTransaction (void)
 
void PreventInTransactionBlock (bool isTopLevel, const char *stmtType)
 
void WarnNoTransactionBlock (bool isTopLevel, const char *stmtType)
 
void RequireTransactionBlock (bool isTopLevel, const char *stmtType)
 
bool IsInTransactionBlock (bool isTopLevel)
 
void RegisterXactCallback (XactCallback callback, void *arg)
 
void UnregisterXactCallback (XactCallback callback, void *arg)
 
void RegisterSubXactCallback (SubXactCallback callback, void *arg)
 
void UnregisterSubXactCallback (SubXactCallback callback, void *arg)
 
void BeginTransactionBlock (void)
 
bool PrepareTransactionBlock (const char *gid)
 
bool EndTransactionBlock (void)
 
void UserAbortTransactionBlock (void)
 
void BeginImplicitTransactionBlock (void)
 
void EndImplicitTransactionBlock (void)
 
void DefineSavepoint (const char *name)
 
void ReleaseSavepoint (const char *name)
 
void RollbackToSavepoint (const char *name)
 
void BeginInternalSubTransaction (const char *name)
 
void ReleaseCurrentSubTransaction (void)
 
void RollbackAndReleaseCurrentSubTransaction (void)
 
void AbortOutOfAnyTransaction (void)
 
bool IsTransactionBlock (void)
 
bool IsTransactionOrTransactionBlock (void)
 
char TransactionBlockStatusCode (void)
 
bool IsSubTransaction (void)
 
Size EstimateTransactionStateSpace (void)
 
void SerializeTransactionState (Size maxsize, char *start_address)
 
void StartParallelWorkerTransaction (char *tstatespace)
 
void EndParallelWorkerTransaction (void)
 
int xactGetCommittedChildren (TransactionId **ptr)
 
XLogRecPtr XactLogCommitRecord (TimestampTz commit_time, int nsubxacts, TransactionId *subxacts, int nrels, RelFileNode *rels, int nmsgs, SharedInvalidationMessage *msgs, bool relcacheInval, bool forceSync, int xactflags, TransactionId twophase_xid, const char *twophase_gid)
 
XLogRecPtr XactLogAbortRecord (TimestampTz abort_time, int nsubxacts, TransactionId *subxacts, int nrels, RelFileNode *rels, int xactflags, TransactionId twophase_xid, const char *twophase_gid)
 
static void xact_redo_commit (xl_xact_parsed_commit *parsed, TransactionId xid, XLogRecPtr lsn, RepOriginId origin_id)
 
static void xact_redo_abort (xl_xact_parsed_abort *parsed, TransactionId xid)
 
void xact_redo (XLogReaderState *record)
 

Variables

int DefaultXactIsoLevel = XACT_READ_COMMITTED
 
int XactIsoLevel
 
bool DefaultXactReadOnly = false
 
bool XactReadOnly
 
bool DefaultXactDeferrable = false
 
bool XactDeferrable
 
int synchronous_commit = SYNCHRONOUS_COMMIT_ON
 
TransactionId XactTopTransactionId = InvalidTransactionId
 
int nParallelCurrentXids = 0
 
TransactionIdParallelCurrentXids
 
int MyXactFlags
 
static TransactionStateData TopTransactionStateData
 
static int nUnreportedXids
 
static TransactionId unreportedXids [PGPROC_MAX_CACHED_SUBXIDS]
 
static TransactionState CurrentTransactionState = &TopTransactionStateData
 
static SubTransactionId currentSubTransactionId
 
static CommandId currentCommandId
 
static bool currentCommandIdUsed
 
static TimestampTz xactStartTimestamp
 
static TimestampTz stmtStartTimestamp
 
static TimestampTz xactStopTimestamp
 
static char * prepareGID
 
static bool forceSyncCommit = false
 
static MemoryContext TransactionAbortContext = NULL
 
static XactCallbackItemXact_callbacks = NULL
 
static SubXactCallbackItemSubXact_callbacks = NULL
 

Typedef Documentation

◆ SubXactCallbackItem

◆ TBlockState

◆ TransactionState

Definition at line 194 of file xact.c.

◆ TransactionStateData

◆ TransState

◆ XactCallbackItem

Enumeration Type Documentation

◆ TBlockState

Enumerator
TBLOCK_DEFAULT 
TBLOCK_STARTED 
TBLOCK_BEGIN 
TBLOCK_INPROGRESS 
TBLOCK_IMPLICIT_INPROGRESS 
TBLOCK_PARALLEL_INPROGRESS 
TBLOCK_END 
TBLOCK_ABORT 
TBLOCK_ABORT_END 
TBLOCK_ABORT_PENDING 
TBLOCK_PREPARE 
TBLOCK_SUBBEGIN 
TBLOCK_SUBINPROGRESS 
TBLOCK_SUBRELEASE 
TBLOCK_SUBCOMMIT 
TBLOCK_SUBABORT 
TBLOCK_SUBABORT_END 
TBLOCK_SUBABORT_PENDING 
TBLOCK_SUBRESTART 
TBLOCK_SUBABORT_RESTART 

Definition at line 138 of file xact.c.

139 {
140  /* not-in-transaction-block states */
141  TBLOCK_DEFAULT, /* idle */
142  TBLOCK_STARTED, /* running single-query transaction */
143 
144  /* transaction block states */
145  TBLOCK_BEGIN, /* starting transaction block */
146  TBLOCK_INPROGRESS, /* live transaction */
147  TBLOCK_IMPLICIT_INPROGRESS, /* live transaction after implicit BEGIN */
148  TBLOCK_PARALLEL_INPROGRESS, /* live transaction inside parallel worker */
149  TBLOCK_END, /* COMMIT received */
150  TBLOCK_ABORT, /* failed xact, awaiting ROLLBACK */
151  TBLOCK_ABORT_END, /* failed xact, ROLLBACK received */
152  TBLOCK_ABORT_PENDING, /* live xact, ROLLBACK received */
153  TBLOCK_PREPARE, /* live xact, PREPARE received */
154 
155  /* subtransaction states */
156  TBLOCK_SUBBEGIN, /* starting a subtransaction */
157  TBLOCK_SUBINPROGRESS, /* live subtransaction */
158  TBLOCK_SUBRELEASE, /* RELEASE received */
159  TBLOCK_SUBCOMMIT, /* COMMIT received while TBLOCK_SUBINPROGRESS */
160  TBLOCK_SUBABORT, /* failed subxact, awaiting ROLLBACK */
161  TBLOCK_SUBABORT_END, /* failed subxact, ROLLBACK received */
162  TBLOCK_SUBABORT_PENDING, /* live subxact, ROLLBACK received */
163  TBLOCK_SUBRESTART, /* live subxact, ROLLBACK TO received */
164  TBLOCK_SUBABORT_RESTART /* failed subxact, ROLLBACK TO received */
165 } TBlockState;
TBlockState
Definition: xact.c:138

◆ TransState

enum TransState
Enumerator
TRANS_DEFAULT 
TRANS_START 
TRANS_INPROGRESS 
TRANS_COMMIT 
TRANS_ABORT 
TRANS_PREPARE 

Definition at line 122 of file xact.c.

123 {
124  TRANS_DEFAULT, /* idle */
125  TRANS_START, /* transaction starting */
126  TRANS_INPROGRESS, /* inside a valid transaction */
127  TRANS_COMMIT, /* commit in progress */
128  TRANS_ABORT, /* abort in progress */
129  TRANS_PREPARE /* prepare in progress */
130 } TransState;
TransState
Definition: xact.c:122

Function Documentation

◆ AbortCurrentTransaction()

void AbortCurrentTransaction ( void  )

Definition at line 2984 of file xact.c.

References AbortCurrentTransaction(), AbortSubTransaction(), AbortTransaction(), TransactionStateData::blockState, CleanupSubTransaction(), CleanupTransaction(), CurrentTransactionState, TransactionStateData::state, TBLOCK_ABORT, TBLOCK_ABORT_END, TBLOCK_ABORT_PENDING, TBLOCK_BEGIN, TBLOCK_DEFAULT, TBLOCK_END, TBLOCK_IMPLICIT_INPROGRESS, TBLOCK_INPROGRESS, TBLOCK_PARALLEL_INPROGRESS, TBLOCK_PREPARE, TBLOCK_STARTED, TBLOCK_SUBABORT, TBLOCK_SUBABORT_END, TBLOCK_SUBABORT_PENDING, TBLOCK_SUBABORT_RESTART, TBLOCK_SUBBEGIN, TBLOCK_SUBCOMMIT, TBLOCK_SUBINPROGRESS, TBLOCK_SUBRELEASE, TBLOCK_SUBRESTART, TRANS_DEFAULT, TRANS_INPROGRESS, and TRANS_START.

Referenced by AbortCurrentTransaction(), AutoVacLauncherMain(), PostgresMain(), ReorderBufferCommit(), ReorderBufferImmediateInvalidation(), SnapBuildClearExportedSnapshot(), and SPI_rollback().

2985 {
2987 
2988  switch (s->blockState)
2989  {
2990  case TBLOCK_DEFAULT:
2991  if (s->state == TRANS_DEFAULT)
2992  {
2993  /* we are idle, so nothing to do */
2994  }
2995  else
2996  {
2997  /*
2998  * We can get here after an error during transaction start
2999  * (state will be TRANS_START). Need to clean up the
3000  * incompletely started transaction. First, adjust the
3001  * low-level state to suppress warning message from
3002  * AbortTransaction.
3003  */
3004  if (s->state == TRANS_START)
3005  s->state = TRANS_INPROGRESS;
3006  AbortTransaction();
3008  }
3009  break;
3010 
3011  /*
3012  * If we aren't in a transaction block, we just do the basic abort
3013  * & cleanup transaction. For this purpose, we treat an implicit
3014  * transaction block as if it were a simple statement.
3015  */
3016  case TBLOCK_STARTED:
3018  AbortTransaction();
3021  break;
3022 
3023  /*
3024  * If we are in TBLOCK_BEGIN it means something screwed up right
3025  * after reading "BEGIN TRANSACTION". We assume that the user
3026  * will interpret the error as meaning the BEGIN failed to get him
3027  * into a transaction block, so we should abort and return to idle
3028  * state.
3029  */
3030  case TBLOCK_BEGIN:
3031  AbortTransaction();
3034  break;
3035 
3036  /*
3037  * We are somewhere in a transaction block and we've gotten a
3038  * failure, so we abort the transaction and set up the persistent
3039  * ABORT state. We will stay in ABORT until we get a ROLLBACK.
3040  */
3041  case TBLOCK_INPROGRESS:
3043  AbortTransaction();
3044  s->blockState = TBLOCK_ABORT;
3045  /* CleanupTransaction happens when we exit TBLOCK_ABORT_END */
3046  break;
3047 
3048  /*
3049  * Here, we failed while trying to COMMIT. Clean up the
3050  * transaction and return to idle state (we do not want to stay in
3051  * the transaction).
3052  */
3053  case TBLOCK_END:
3054  AbortTransaction();
3057  break;
3058 
3059  /*
3060  * Here, we are already in an aborted transaction state and are
3061  * waiting for a ROLLBACK, but for some reason we failed again! So
3062  * we just remain in the abort state.
3063  */
3064  case TBLOCK_ABORT:
3065  case TBLOCK_SUBABORT:
3066  break;
3067 
3068  /*
3069  * We are in a failed transaction and we got the ROLLBACK command.
3070  * We have already aborted, we just need to cleanup and go to idle
3071  * state.
3072  */
3073  case TBLOCK_ABORT_END:
3076  break;
3077 
3078  /*
3079  * We are in a live transaction and we got a ROLLBACK command.
3080  * Abort, cleanup, go to idle state.
3081  */
3082  case TBLOCK_ABORT_PENDING:
3083  AbortTransaction();
3086  break;
3087 
3088  /*
3089  * Here, we failed while trying to PREPARE. Clean up the
3090  * transaction and return to idle state (we do not want to stay in
3091  * the transaction).
3092  */
3093  case TBLOCK_PREPARE:
3094  AbortTransaction();
3097  break;
3098 
3099  /*
3100  * We got an error inside a subtransaction. Abort just the
3101  * subtransaction, and go to the persistent SUBABORT state until
3102  * we get ROLLBACK.
3103  */
3104  case TBLOCK_SUBINPROGRESS:
3107  break;
3108 
3109  /*
3110  * If we failed while trying to create a subtransaction, clean up
3111  * the broken subtransaction and abort the parent. The same
3112  * applies if we get a failure while ending a subtransaction.
3113  */
3114  case TBLOCK_SUBBEGIN:
3115  case TBLOCK_SUBRELEASE:
3116  case TBLOCK_SUBCOMMIT:
3118  case TBLOCK_SUBRESTART:
3122  break;
3123 
3124  /*
3125  * Same as above, except the Abort() was already done.
3126  */
3127  case TBLOCK_SUBABORT_END:
3131  break;
3132  }
3133 }
void AbortCurrentTransaction(void)
Definition: xact.c:2984
static TransactionState CurrentTransactionState
Definition: xact.c:232
TBlockState blockState
Definition: xact.c:177
TransState state
Definition: xact.c:176
static void CleanupTransaction(void)
Definition: xact.c:2624
static void AbortSubTransaction(void)
Definition: xact.c:4664
static void AbortTransaction(void)
Definition: xact.c:2444
static void CleanupSubTransaction(void)
Definition: xact.c:4812

◆ AbortOutOfAnyTransaction()

void AbortOutOfAnyTransaction ( void  )

Definition at line 4318 of file xact.c.

References AbortSubTransaction(), AbortTransaction(), Assert, AtAbort_Memory(), AtAbort_Portals(), AtCleanup_Memory(), AtSubAbort_Portals(), TransactionStateData::blockState, CleanupSubTransaction(), CleanupTransaction(), CurrentTransactionState, TransactionStateData::curTransactionOwner, TransactionStateData::parent, TransactionStateData::state, TransactionStateData::subTransactionId, TBLOCK_ABORT, TBLOCK_ABORT_END, TBLOCK_ABORT_PENDING, TBLOCK_BEGIN, TBLOCK_DEFAULT, TBLOCK_END, TBLOCK_IMPLICIT_INPROGRESS, TBLOCK_INPROGRESS, TBLOCK_PARALLEL_INPROGRESS, TBLOCK_PREPARE, TBLOCK_STARTED, TBLOCK_SUBABORT, TBLOCK_SUBABORT_END, TBLOCK_SUBABORT_PENDING, TBLOCK_SUBABORT_RESTART, TBLOCK_SUBBEGIN, TBLOCK_SUBCOMMIT, TBLOCK_SUBINPROGRESS, TBLOCK_SUBRELEASE, TBLOCK_SUBRESTART, TRANS_DEFAULT, TRANS_INPROGRESS, and TRANS_START.

Referenced by do_autovacuum(), perform_work_item(), RemoveTempRelationsCallback(), and ShutdownPostgres().

4319 {
4321 
4322  /* Ensure we're not running in a doomed memory context */
4323  AtAbort_Memory();
4324 
4325  /*
4326  * Get out of any transaction or nested transaction
4327  */
4328  do
4329  {
4330  switch (s->blockState)
4331  {
4332  case TBLOCK_DEFAULT:
4333  if (s->state == TRANS_DEFAULT)
4334  {
4335  /* Not in a transaction, do nothing */
4336  }
4337  else
4338  {
4339  /*
4340  * We can get here after an error during transaction start
4341  * (state will be TRANS_START). Need to clean up the
4342  * incompletely started transaction. First, adjust the
4343  * low-level state to suppress warning message from
4344  * AbortTransaction.
4345  */
4346  if (s->state == TRANS_START)
4347  s->state = TRANS_INPROGRESS;
4348  AbortTransaction();
4350  }
4351  break;
4352  case TBLOCK_STARTED:
4353  case TBLOCK_BEGIN:
4354  case TBLOCK_INPROGRESS:
4357  case TBLOCK_END:
4358  case TBLOCK_ABORT_PENDING:
4359  case TBLOCK_PREPARE:
4360  /* In a transaction, so clean up */
4361  AbortTransaction();
4364  break;
4365  case TBLOCK_ABORT:
4366  case TBLOCK_ABORT_END:
4367 
4368  /*
4369  * AbortTransaction is already done, still need Cleanup.
4370  * However, if we failed partway through running ROLLBACK,
4371  * there will be an active portal running that command, which
4372  * we need to shut down before doing CleanupTransaction.
4373  */
4374  AtAbort_Portals();
4377  break;
4378 
4379  /*
4380  * In a subtransaction, so clean it up and abort parent too
4381  */
4382  case TBLOCK_SUBBEGIN:
4383  case TBLOCK_SUBINPROGRESS:
4384  case TBLOCK_SUBRELEASE:
4385  case TBLOCK_SUBCOMMIT:
4387  case TBLOCK_SUBRESTART:
4390  s = CurrentTransactionState; /* changed by pop */
4391  break;
4392 
4393  case TBLOCK_SUBABORT:
4394  case TBLOCK_SUBABORT_END:
4396  /* As above, but AbortSubTransaction already done */
4397  if (s->curTransactionOwner)
4398  {
4399  /* As in TBLOCK_ABORT, might have a live portal to zap */
4404  }
4406  s = CurrentTransactionState; /* changed by pop */
4407  break;
4408  }
4409  } while (s->blockState != TBLOCK_DEFAULT);
4410 
4411  /* Should be out of all subxacts now */
4412  Assert(s->parent == NULL);
4413 
4414  /* If we didn't actually have anything to do, revert to TopMemoryContext */
4415  AtCleanup_Memory();
4416 }
static TransactionState CurrentTransactionState
Definition: xact.c:232
static void AtCleanup_Memory(void)
Definition: xact.c:1724
void AtAbort_Portals(void)
Definition: portalmem.c:762
TBlockState blockState
Definition: xact.c:177
TransState state
Definition: xact.c:176
ResourceOwner curTransactionOwner
Definition: xact.c:181
static void CleanupTransaction(void)
Definition: xact.c:2624
struct TransactionStateData * parent
Definition: xact.c:191
SubTransactionId subTransactionId
Definition: xact.c:173
static void AbortSubTransaction(void)
Definition: xact.c:4664
static void AtAbort_Memory(void)
Definition: xact.c:1634
static void AbortTransaction(void)
Definition: xact.c:2444
#define Assert(condition)
Definition: c.h:699
void AtSubAbort_Portals(SubTransactionId mySubid, SubTransactionId parentSubid, ResourceOwner myXactOwner, ResourceOwner parentXactOwner)
Definition: portalmem.c:958
static void CleanupSubTransaction(void)
Definition: xact.c:4812

◆ AbortSubTransaction()

static void AbortSubTransaction ( void  )
static

Definition at line 4664 of file xact.c.

References AbortBufferIO(), AfterTriggerEndSubXact(), AtEOSubXact_Files(), AtEOSubXact_HashTables(), AtEOSubXact_Inval(), AtEOSubXact_LargeObject(), AtEOSubXact_Namespace(), AtEOSubXact_on_commit_actions(), AtEOSubXact_Parallel(), AtEOSubXact_PgStat(), AtEOSubXact_RelationCache(), AtEOSubXact_SPI(), AtEOXact_GUC(), AtSubAbort_childXids(), AtSubAbort_Memory(), AtSubAbort_Notify(), AtSubAbort_Portals(), AtSubAbort_ResourceOwner(), AtSubAbort_smgr(), AtSubAbort_Snapshot(), CallSubXactCallbacks(), ConditionVariableCancelSleep(), CurrentTransactionState, TransactionStateData::curTransactionOwner, elog, TransactionStateData::gucNestLevel, HOLD_INTERRUPTS, IsInParallelMode(), LockErrorCleanup(), LWLockReleaseAll(), TransactionStateData::nestingLevel, TransactionStateData::parallelModeLevel, TransactionStateData::parent, PG_SETMASK, pgstat_progress_end_command(), pgstat_report_wait_end(), TransactionStateData::prevSecContext, TransactionStateData::prevUser, TransactionStateData::prevXactReadOnly, RecordTransactionAbort(), reschedule_timeouts(), RESOURCE_RELEASE_AFTER_LOCKS, RESOURCE_RELEASE_BEFORE_LOCKS, RESOURCE_RELEASE_LOCKS, ResourceOwnerRelease(), RESUME_INTERRUPTS, SetUserIdAndSecContext(), ShowTransactionState(), TransactionStateData::state, TransactionStateData::subTransactionId, SUBXACT_EVENT_ABORT_SUB, TRANS_ABORT, TRANS_INPROGRESS, TransactionStateData::transactionId, TransactionIdIsValid, TransStateAsString(), UnBlockSig, UnlockBuffers(), WARNING, XactReadOnly, and XLogResetInsertion().

Referenced by AbortCurrentTransaction(), AbortOutOfAnyTransaction(), CommitTransactionCommand(), and RollbackAndReleaseCurrentSubTransaction().

4665 {
4667 
4668  /* Prevent cancel/die interrupt while cleaning up */
4669  HOLD_INTERRUPTS();
4670 
4671  /* Make sure we have a valid memory context and resource owner */
4674 
4675  /*
4676  * Release any LW locks we might be holding as quickly as possible.
4677  * (Regular locks, however, must be held till we finish aborting.)
4678  * Releasing LW locks is critical since we might try to grab them again
4679  * while cleaning up!
4680  *
4681  * FIXME This may be incorrect --- Are there some locks we should keep?
4682  * Buffer locks, for example? I don't think so but I'm not sure.
4683  */
4684  LWLockReleaseAll();
4685 
4688  AbortBufferIO();
4689  UnlockBuffers();
4690 
4691  /* Reset WAL record construction state */
4693 
4694  /* Cancel condition variable sleep */
4696 
4697  /*
4698  * Also clean up any open wait for lock, since the lock manager will choke
4699  * if we try to wait for another lock before doing this.
4700  */
4701  LockErrorCleanup();
4702 
4703  /*
4704  * If any timeout events are still active, make sure the timeout interrupt
4705  * is scheduled. This covers possible loss of a timeout interrupt due to
4706  * longjmp'ing out of the SIGINT handler (see notes in handle_sig_alarm).
4707  * We delay this till after LockErrorCleanup so that we don't uselessly
4708  * reschedule lock or deadlock check timeouts.
4709  */
4711 
4712  /*
4713  * Re-enable signals, in case we got here by longjmp'ing out of a signal
4714  * handler. We do this fairly early in the sequence so that the timeout
4715  * infrastructure will be functional if needed while aborting.
4716  */
4718 
4719  /*
4720  * check the current transaction state
4721  */
4722  ShowTransactionState("AbortSubTransaction");
4723 
4724  if (s->state != TRANS_INPROGRESS)
4725  elog(WARNING, "AbortSubTransaction while in %s state",
4727 
4728  s->state = TRANS_ABORT;
4729 
4730  /*
4731  * Reset user ID which might have been changed transiently. (See notes in
4732  * AbortTransaction.)
4733  */
4735 
4736  /* Exit from parallel mode, if necessary. */
4737  if (IsInParallelMode())
4738  {
4740  s->parallelModeLevel = 0;
4741  }
4742 
4743  /*
4744  * We can skip all this stuff if the subxact failed before creating a
4745  * ResourceOwner...
4746  */
4747  if (s->curTransactionOwner)
4748  {
4749  AfterTriggerEndSubXact(false);
4755  s->parent->subTransactionId);
4757 
4758  /* Advertise the fact that we aborted in pg_xact. */
4759  (void) RecordTransactionAbort(true);
4760 
4761  /* Post-abort cleanup */
4764 
4766  s->parent->subTransactionId);
4767 
4770  false, false);
4772  s->parent->subTransactionId);
4773  AtEOSubXact_Inval(false);
4776  false, false);
4779  false, false);
4780  AtSubAbort_smgr();
4781 
4782  AtEOXact_GUC(false, s->gucNestLevel);
4783  AtEOSubXact_SPI(false, s->subTransactionId);
4785  s->parent->subTransactionId);
4787  s->parent->subTransactionId);
4789  s->parent->subTransactionId);
4791  AtEOSubXact_PgStat(false, s->nestingLevel);
4793  }
4794 
4795  /*
4796  * Restore the upper transaction's read-only state, too. This should be
4797  * redundant with GUC's cleanup but we may as well do it for consistency
4798  * with the commit case.
4799  */
4801 
4803 }
static void AtSubAbort_ResourceOwner(void)
Definition: xact.c:1679
void AtEOSubXact_RelationCache(bool isCommit, SubTransactionId mySubid, SubTransactionId parentSubid)
Definition: relcache.c:2912
static TransactionState CurrentTransactionState
Definition: xact.c:232
void SetUserIdAndSecContext(Oid userid, int sec_context)
Definition: miscinit.c:491
void AtEOSubXact_HashTables(bool isCommit, int nestDepth)
Definition: dynahash.c:1860
void AtEOSubXact_SPI(bool isCommit, SubTransactionId mySubid)
Definition: spi.c:303
#define PG_SETMASK(mask)
Definition: pqsignal.h:19
void reschedule_timeouts(void)
Definition: timeout.c:408
#define RESUME_INTERRUPTS()
Definition: miscadmin.h:117
void AtSubAbort_Snapshot(int level)
Definition: snapmgr.c:1023
TransState state
Definition: xact.c:176
ResourceOwner curTransactionOwner
Definition: xact.c:181
bool IsInParallelMode(void)
Definition: xact.c:905
void ConditionVariableCancelSleep(void)
static void AtSubAbort_Memory(void)
Definition: xact.c:1654
void XLogResetInsertion(void)
Definition: xloginsert.c:193
struct TransactionStateData * parent
Definition: xact.c:191
static void ShowTransactionState(const char *str)
Definition: xact.c:5074
void AtEOXact_GUC(bool isCommit, int nestLevel)
Definition: guc.c:5312
SubTransactionId subTransactionId
Definition: xact.c:173
sigset_t UnBlockSig
Definition: pqsignal.c:22
static void AtSubAbort_childXids(void)
Definition: xact.c:1692
static void pgstat_report_wait_end(void)
Definition: pgstat.h:1260
void AtEOSubXact_PgStat(bool isCommit, int nestDepth)
Definition: pgstat.c:2136
void LockErrorCleanup(void)
Definition: proc.c:686
void AtEOSubXact_LargeObject(bool isCommit, SubTransactionId mySubid, SubTransactionId parentSubid)
Definition: be-fsstubs.c:624
#define WARNING
Definition: elog.h:40
void UnlockBuffers(void)
Definition: bufmgr.c:3518
void AtSubAbort_Notify(void)
Definition: async.c:1671
void AtEOSubXact_on_commit_actions(bool isCommit, SubTransactionId mySubid, SubTransactionId parentSubid)
Definition: tablecmds.c:13329
void pgstat_progress_end_command(void)
Definition: pgstat.c:3144
void AtEOSubXact_Files(bool isCommit, SubTransactionId mySubid, SubTransactionId parentSubid)
Definition: fd.c:2872
TransactionId transactionId
Definition: xact.c:172
static void CallSubXactCallbacks(SubXactEvent event, SubTransactionId mySubid, SubTransactionId parentSubid)
Definition: xact.c:3391
bool XactReadOnly
Definition: xact.c:76
int parallelModeLevel
Definition: xact.c:190
void ResourceOwnerRelease(ResourceOwner owner, ResourceReleasePhase phase, bool isCommit, bool isTopLevel)
Definition: resowner.c:474
static const char * TransStateAsString(TransState state)
Definition: xact.c:5178
void AtSubAbort_Portals(SubTransactionId mySubid, SubTransactionId parentSubid, ResourceOwner myXactOwner, ResourceOwner parentXactOwner)
Definition: portalmem.c:958
void AtSubAbort_smgr(void)
Definition: storage.c:470
bool prevXactReadOnly
Definition: xact.c:187
void AbortBufferIO(void)
Definition: bufmgr.c:3974
void AfterTriggerEndSubXact(bool isCommit)
Definition: trigger.c:5082
void AtEOSubXact_Inval(bool isCommit)
Definition: inval.c:988
#define HOLD_INTERRUPTS()
Definition: miscadmin.h:115
#define elog
Definition: elog.h:219
void AtEOSubXact_Namespace(bool isCommit, SubTransactionId mySubid, SubTransactionId parentSubid)
Definition: namespace.c:3962
void LWLockReleaseAll(void)
Definition: lwlock.c:1824
#define TransactionIdIsValid(xid)
Definition: transam.h:41
void AtEOSubXact_Parallel(bool isCommit, SubTransactionId mySubId)
Definition: parallel.c:1161
static TransactionId RecordTransactionAbort(bool isSubXact)
Definition: xact.c:1522

◆ AbortTransaction()

static void AbortTransaction ( void  )
static

Definition at line 2444 of file xact.c.

References AbortBufferIO(), AfterTriggerEndXact(), Assert, AtAbort_Memory(), AtAbort_Notify(), AtAbort_Portals(), AtAbort_ResourceOwner(), AtAbort_Twophase(), AtEOXact_ApplyLauncher(), AtEOXact_Buffers(), AtEOXact_ComboCid(), AtEOXact_Files(), AtEOXact_GUC(), AtEOXact_HashTables(), AtEOXact_Inval(), AtEOXact_LargeObject(), AtEOXact_MultiXact(), AtEOXact_Namespace(), AtEOXact_on_commit_actions(), AtEOXact_Parallel(), AtEOXact_PgStat(), AtEOXact_RelationCache(), AtEOXact_RelationMap(), AtEOXact_SMgr(), AtEOXact_SPI(), TransactionStateData::blockState, CallXactCallbacks(), ConditionVariableCancelSleep(), CurrentTransactionState, elog, HOLD_INTERRUPTS, InvalidTransactionId, IsInParallelMode(), LockErrorCleanup(), LWLockReleaseAll(), PGPROC::lxid, MyProc, TransactionStateData::parallelModeLevel, TransactionStateData::parent, PG_SETMASK, pgstat_progress_end_command(), pgstat_report_wait_end(), pgstat_report_xact_timestamp(), TransactionStateData::prevSecContext, TransactionStateData::prevUser, ProcArrayEndTransaction(), RecordTransactionAbort(), reschedule_timeouts(), RESOURCE_RELEASE_AFTER_LOCKS, RESOURCE_RELEASE_BEFORE_LOCKS, RESOURCE_RELEASE_LOCKS, ResourceOwnerRelease(), RESUME_INTERRUPTS, SetUserIdAndSecContext(), smgrDoPendingDeletes(), TransactionStateData::state, TBLOCK_PARALLEL_INPROGRESS, TopTransactionResourceOwner, TRANS_ABORT, TRANS_INPROGRESS, TRANS_PREPARE, TransStateAsString(), UnBlockSig, UnlockBuffers(), WARNING, XACT_EVENT_ABORT, XACT_EVENT_PARALLEL_ABORT, XactLastRecEnd, XLogResetInsertion(), and XLogSetAsyncXactLSN().

Referenced by AbortCurrentTransaction(), AbortOutOfAnyTransaction(), and CommitTransactionCommand().

2445 {
2447  TransactionId latestXid;
2448  bool is_parallel_worker;
2449 
2450  /* Prevent cancel/die interrupt while cleaning up */
2451  HOLD_INTERRUPTS();
2452 
2453  /* Make sure we have a valid memory context and resource owner */
2454  AtAbort_Memory();
2456 
2457  /*
2458  * Release any LW locks we might be holding as quickly as possible.
2459  * (Regular locks, however, must be held till we finish aborting.)
2460  * Releasing LW locks is critical since we might try to grab them again
2461  * while cleaning up!
2462  */
2463  LWLockReleaseAll();
2464 
2465  /* Clear wait information and command progress indicator */
2468 
2469  /* Clean up buffer I/O and buffer context locks, too */
2470  AbortBufferIO();
2471  UnlockBuffers();
2472 
2473  /* Reset WAL record construction state */
2475 
2476  /* Cancel condition variable sleep */
2478 
2479  /*
2480  * Also clean up any open wait for lock, since the lock manager will choke
2481  * if we try to wait for another lock before doing this.
2482  */
2483  LockErrorCleanup();
2484 
2485  /*
2486  * If any timeout events are still active, make sure the timeout interrupt
2487  * is scheduled. This covers possible loss of a timeout interrupt due to
2488  * longjmp'ing out of the SIGINT handler (see notes in handle_sig_alarm).
2489  * We delay this till after LockErrorCleanup so that we don't uselessly
2490  * reschedule lock or deadlock check timeouts.
2491  */
2493 
2494  /*
2495  * Re-enable signals, in case we got here by longjmp'ing out of a signal
2496  * handler. We do this fairly early in the sequence so that the timeout
2497  * infrastructure will be functional if needed while aborting.
2498  */
2500 
2501  /*
2502  * check the current transaction state
2503  */
2504  is_parallel_worker = (s->blockState == TBLOCK_PARALLEL_INPROGRESS);
2505  if (s->state != TRANS_INPROGRESS && s->state != TRANS_PREPARE)
2506  elog(WARNING, "AbortTransaction while in %s state",
2508  Assert(s->parent == NULL);
2509 
2510  /*
2511  * set the current transaction state information appropriately during the
2512  * abort processing
2513  */
2514  s->state = TRANS_ABORT;
2515 
2516  /*
2517  * Reset user ID which might have been changed transiently. We need this
2518  * to clean up in case control escaped out of a SECURITY DEFINER function
2519  * or other local change of CurrentUserId; therefore, the prior value of
2520  * SecurityRestrictionContext also needs to be restored.
2521  *
2522  * (Note: it is not necessary to restore session authorization or role
2523  * settings here because those can only be changed via GUC, and GUC will
2524  * take care of rolling them back if need be.)
2525  */
2527 
2528  /* If in parallel mode, clean up workers and exit parallel mode. */
2529  if (IsInParallelMode())
2530  {
2531  AtEOXact_Parallel(false);
2532  s->parallelModeLevel = 0;
2533  }
2534 
2535  /*
2536  * do abort processing
2537  */
2538  AfterTriggerEndXact(false); /* 'false' means it's abort */
2539  AtAbort_Portals();
2540  AtEOXact_LargeObject(false);
2541  AtAbort_Notify();
2542  AtEOXact_RelationMap(false);
2543  AtAbort_Twophase();
2544 
2545  /*
2546  * Advertise the fact that we aborted in pg_xact (assuming that we got as
2547  * far as assigning an XID to advertise). But if we're inside a parallel
2548  * worker, skip this; the user backend must be the one to write the abort
2549  * record.
2550  */
2551  if (!is_parallel_worker)
2552  latestXid = RecordTransactionAbort(false);
2553  else
2554  {
2555  latestXid = InvalidTransactionId;
2556 
2557  /*
2558  * Since the parallel master won't get our value of XactLastRecEnd in
2559  * this case, we nudge WAL-writer ourselves in this case. See related
2560  * comments in RecordTransactionAbort for why this matters.
2561  */
2563  }
2564 
2565  TRACE_POSTGRESQL_TRANSACTION_ABORT(MyProc->lxid);
2566 
2567  /*
2568  * Let others know about no transaction in progress by me. Note that this
2569  * must be done _before_ releasing locks we hold and _after_
2570  * RecordTransactionAbort.
2571  */
2572  ProcArrayEndTransaction(MyProc, latestXid);
2573 
2574  /*
2575  * Post-abort cleanup. See notes in CommitTransaction() concerning
2576  * ordering. We can skip all of it if the transaction failed before
2577  * creating a resource owner.
2578  */
2579  if (TopTransactionResourceOwner != NULL)
2580  {
2581  if (is_parallel_worker)
2583  else
2585 
2588  false, true);
2589  AtEOXact_Buffers(false);
2590  AtEOXact_RelationCache(false);
2591  AtEOXact_Inval(false);
2595  false, true);
2598  false, true);
2599  smgrDoPendingDeletes(false);
2600 
2601  AtEOXact_GUC(false, 1);
2602  AtEOXact_SPI(false);
2604  AtEOXact_Namespace(false, is_parallel_worker);
2605  AtEOXact_SMgr();
2606  AtEOXact_Files(false);
2608  AtEOXact_HashTables(false);
2609  AtEOXact_PgStat(false);
2610  AtEOXact_ApplyLauncher(false);
2612  }
2613 
2614  /*
2615  * State remains TRANS_ABORT until CleanupTransaction().
2616  */
2618 }
void AtEOXact_ApplyLauncher(bool isCommit)
Definition: launcher.c:833
void smgrDoPendingDeletes(bool isCommit)
Definition: storage.c:305
static void AtAbort_ResourceOwner(void)
Definition: xact.c:1666
static TransactionState CurrentTransactionState
Definition: xact.c:232
void AtEOXact_Inval(bool isCommit)
Definition: inval.c:929
uint32 TransactionId
Definition: c.h:474
void SetUserIdAndSecContext(Oid userid, int sec_context)
Definition: miscinit.c:491
void pgstat_report_xact_timestamp(TimestampTz tstamp)
Definition: pgstat.c:3196
XLogRecPtr XactLastRecEnd
Definition: xlog.c:339
void AtEOXact_RelationCache(bool isCommit)
Definition: relcache.c:2761
ResourceOwner TopTransactionResourceOwner
Definition: resowner.c:142
PGPROC * MyProc
Definition: proc.c:67
void AtEOXact_Buffers(bool isCommit)
Definition: bufmgr.c:2415
void AtEOXact_RelationMap(bool isCommit)
Definition: relmapper.c:457
static void CallXactCallbacks(XactEvent event)
Definition: xact.c:3336
void AtEOXact_on_commit_actions(bool isCommit)
Definition: tablecmds.c:13287
void ProcArrayEndTransaction(PGPROC *proc, TransactionId latestXid)
Definition: procarray.c:396
#define PG_SETMASK(mask)
Definition: pqsignal.h:19
void reschedule_timeouts(void)
Definition: timeout.c:408
void AtEOXact_Files(bool isCommit)
Definition: fd.c:2905
void AtAbort_Portals(void)
Definition: portalmem.c:762
TBlockState blockState
Definition: xact.c:177
#define RESUME_INTERRUPTS()
Definition: miscadmin.h:117
TransState state
Definition: xact.c:176
void AtEOXact_SMgr(void)
Definition: smgr.c:798
bool IsInParallelMode(void)
Definition: xact.c:905
void ConditionVariableCancelSleep(void)
void AfterTriggerEndXact(bool isCommit)
Definition: trigger.c:4986
void XLogResetInsertion(void)
Definition: xloginsert.c:193
struct TransactionStateData * parent
Definition: xact.c:191
void AtAbort_Twophase(void)
Definition: twophase.c:317
void AtEOXact_GUC(bool isCommit, int nestLevel)
Definition: guc.c:5312
#define InvalidTransactionId
Definition: transam.h:31
sigset_t UnBlockSig
Definition: pqsignal.c:22
static void pgstat_report_wait_end(void)
Definition: pgstat.h:1260
void LockErrorCleanup(void)
Definition: proc.c:686
#define WARNING
Definition: elog.h:40
void UnlockBuffers(void)
Definition: bufmgr.c:3518
static void AtAbort_Memory(void)
Definition: xact.c:1634
void pgstat_progress_end_command(void)
Definition: pgstat.c:3144
void AtAbort_Notify(void)
Definition: async.c:1589
void AtEOXact_ComboCid(void)
Definition: combocid.c:183
void XLogSetAsyncXactLSN(XLogRecPtr asyncXactLSN)
Definition: xlog.c:2633
int parallelModeLevel
Definition: xact.c:190
#define Assert(condition)
Definition: c.h:699
void ResourceOwnerRelease(ResourceOwner owner, ResourceReleasePhase phase, bool isCommit, bool isTopLevel)
Definition: resowner.c:474
static const char * TransStateAsString(TransState state)
Definition: xact.c:5178
void AtEOXact_SPI(bool isCommit)
Definition: spi.c:281
void AtEOXact_MultiXact(void)
Definition: multixact.c:1662
void AbortBufferIO(void)
Definition: bufmgr.c:3974
#define HOLD_INTERRUPTS()
Definition: miscadmin.h:115
#define elog
Definition: elog.h:219
void LWLockReleaseAll(void)
Definition: lwlock.c:1824
void AtEOXact_HashTables(bool isCommit)
Definition: dynahash.c:1834
void AtEOXact_LargeObject(bool isCommit)
Definition: be-fsstubs.c:583
void AtEOXact_Parallel(bool isCommit)
Definition: parallel.c:1180
void AtEOXact_Namespace(bool isCommit, bool parallel)
Definition: namespace.c:3907
static TransactionId RecordTransactionAbort(bool isSubXact)
Definition: xact.c:1522
void AtEOXact_PgStat(bool isCommit)
Definition: pgstat.c:2053
LocalTransactionId lxid
Definition: proc.h:106

◆ AssignTransactionId()

static void AssignTransactionId ( TransactionState  s)
static

Definition at line 489 of file xact.c.

References Assert, CurrentResourceOwner, TransactionStateData::curTransactionOwner, TransactionStateData::didLogXid, elog, ERROR, GetNewTransactionId(), GetTopTransactionId(), IsInParallelMode(), IsParallelWorker, MinSizeOfXactAssignment, TransactionStateData::nestingLevel, xl_xact_assignment::nsubxacts, nUnreportedXids, palloc(), TransactionStateData::parent, pfree(), PGPROC_MAX_CACHED_SUBXIDS, RegisterPredicateLockingXid(), TransactionStateData::state, SubTransSetParent(), TRANS_INPROGRESS, TransactionStateData::transactionId, TransactionIdIsValid, unreportedXids, XactLockTableInsert(), XactTopTransactionId, XLOG_XACT_ASSIGNMENT, XLogBeginInsert(), XLogInsert(), XLogLogicalInfoActive, XLogRegisterData(), XLogStandbyInfoActive, and xl_xact_assignment::xtop.

Referenced by GetCurrentTransactionId(), and GetTopTransactionId().

490 {
491  bool isSubXact = (s->parent != NULL);
492  ResourceOwner currentOwner;
493  bool log_unknown_top = false;
494 
495  /* Assert that caller didn't screw up */
498 
499  /*
500  * Workers synchronize transaction state at the beginning of each parallel
501  * operation, so we can't account for new XIDs at this point.
502  */
504  elog(ERROR, "cannot assign XIDs during a parallel operation");
505 
506  /*
507  * Ensure parent(s) have XIDs, so that a child always has an XID later
508  * than its parent. Musn't recurse here, or we might get a stack overflow
509  * if we're at the bottom of a huge stack of subtransactions none of which
510  * have XIDs yet.
511  */
512  if (isSubXact && !TransactionIdIsValid(s->parent->transactionId))
513  {
514  TransactionState p = s->parent;
515  TransactionState *parents;
516  size_t parentOffset = 0;
517 
518  parents = palloc(sizeof(TransactionState) * s->nestingLevel);
519  while (p != NULL && !TransactionIdIsValid(p->transactionId))
520  {
521  parents[parentOffset++] = p;
522  p = p->parent;
523  }
524 
525  /*
526  * This is technically a recursive call, but the recursion will never
527  * be more than one layer deep.
528  */
529  while (parentOffset != 0)
530  AssignTransactionId(parents[--parentOffset]);
531 
532  pfree(parents);
533  }
534 
535  /*
536  * When wal_level=logical, guarantee that a subtransaction's xid can only
537  * be seen in the WAL stream if its toplevel xid has been logged before.
538  * If necessary we log an xact_assignment record with fewer than
539  * PGPROC_MAX_CACHED_SUBXIDS. Note that it is fine if didLogXid isn't set
540  * for a transaction even though it appears in a WAL record, we just might
541  * superfluously log something. That can happen when an xid is included
542  * somewhere inside a wal record, but not in XLogRecord->xl_xid, like in
543  * xl_standby_locks.
544  */
545  if (isSubXact && XLogLogicalInfoActive() &&
547  log_unknown_top = true;
548 
549  /*
550  * Generate a new Xid and record it in PG_PROC and pg_subtrans.
551  *
552  * NB: we must make the subtrans entry BEFORE the Xid appears anywhere in
553  * shared storage other than PG_PROC; because if there's no room for it in
554  * PG_PROC, the subtrans entry is needed to ensure that other backends see
555  * the Xid as "running". See GetNewTransactionId.
556  */
557  s->transactionId = GetNewTransactionId(isSubXact);
558  if (!isSubXact)
560 
561  if (isSubXact)
563 
564  /*
565  * If it's a top-level transaction, the predicate locking system needs to
566  * be told about it too.
567  */
568  if (!isSubXact)
570 
571  /*
572  * Acquire lock on the transaction XID. (We assume this cannot block.) We
573  * have to ensure that the lock is assigned to the transaction's own
574  * ResourceOwner.
575  */
576  currentOwner = CurrentResourceOwner;
578 
580 
581  CurrentResourceOwner = currentOwner;
582 
583  /*
584  * Every PGPROC_MAX_CACHED_SUBXIDS assigned transaction ids within each
585  * top-level transaction we issue a WAL record for the assignment. We
586  * include the top-level xid and all the subxids that have not yet been
587  * reported using XLOG_XACT_ASSIGNMENT records.
588  *
589  * This is required to limit the amount of shared memory required in a hot
590  * standby server to keep track of in-progress XIDs. See notes for
591  * RecordKnownAssignedTransactionIds().
592  *
593  * We don't keep track of the immediate parent of each subxid, only the
594  * top-level transaction that each subxact belongs to. This is correct in
595  * recovery only because aborted subtransactions are separately WAL
596  * logged.
597  *
598  * This is correct even for the case where several levels above us didn't
599  * have an xid assigned as we recursed up to them beforehand.
600  */
601  if (isSubXact && XLogStandbyInfoActive())
602  {
604  nUnreportedXids++;
605 
606  /*
607  * ensure this test matches similar one in
608  * RecoverPreparedTransactions()
609  */
611  log_unknown_top)
612  {
613  xl_xact_assignment xlrec;
614 
615  /*
616  * xtop is always set by now because we recurse up transaction
617  * stack to the highest unassigned xid and then come back down
618  */
619  xlrec.xtop = GetTopTransactionId();
621  xlrec.nsubxacts = nUnreportedXids;
622 
623  XLogBeginInsert();
624  XLogRegisterData((char *) &xlrec, MinSizeOfXactAssignment);
626  nUnreportedXids * sizeof(TransactionId));
627 
628  (void) XLogInsert(RM_XACT_ID, XLOG_XACT_ASSIGNMENT);
629 
630  nUnreportedXids = 0;
631  /* mark top, not current xact as having been logged */
633  }
634  }
635 }
TransactionId XactTopTransactionId
Definition: xact.c:106
uint32 TransactionId
Definition: c.h:474
ResourceOwner CurrentResourceOwner
Definition: resowner.c:140
TransactionId GetNewTransactionId(bool isSubXact)
Definition: varsup.c:48
TransactionId xtop
Definition: xact.h:190
TransactionId GetTopTransactionId(void)
Definition: xact.c:389
TransState state
Definition: xact.c:176
ResourceOwner curTransactionOwner
Definition: xact.c:181
void pfree(void *pointer)
Definition: mcxt.c:1031
bool IsInParallelMode(void)
Definition: xact.c:905
#define ERROR
Definition: elog.h:43
#define XLogLogicalInfoActive()
Definition: xlog.h:163
struct TransactionStateData * parent
Definition: xact.c:191
#define MinSizeOfXactAssignment
Definition: xact.h:195
#define IsParallelWorker()
Definition: parallel.h:60
void XLogRegisterData(char *data, int len)
Definition: xloginsert.c:323
XLogRecPtr XLogInsert(RmgrId rmid, uint8 info)
Definition: xloginsert.c:415
#define XLOG_XACT_ASSIGNMENT
Definition: xact.h:145
void XactLockTableInsert(TransactionId xid)
Definition: lmgr.c:513
#define XLogStandbyInfoActive()
Definition: xlog.h:160
static int nUnreportedXids
Definition: xact.c:229
#define PGPROC_MAX_CACHED_SUBXIDS
Definition: proc.h:36
TransactionId transactionId
Definition: xact.c:172
#define Assert(condition)
Definition: c.h:699
static TransactionStateData TopTransactionStateData
Definition: xact.c:201
void RegisterPredicateLockingXid(TransactionId xid)
Definition: predicate.c:1834
void * palloc(Size size)
Definition: mcxt.c:924
static TransactionId unreportedXids[PGPROC_MAX_CACHED_SUBXIDS]
Definition: xact.c:230
#define elog
Definition: elog.h:219
#define TransactionIdIsValid(xid)
Definition: transam.h:41
static void AssignTransactionId(TransactionState s)
Definition: xact.c:489
void SubTransSetParent(TransactionId xid, TransactionId parent)
Definition: subtrans.c:74
void XLogBeginInsert(void)
Definition: xloginsert.c:120

◆ AtAbort_Memory()

static void AtAbort_Memory ( void  )
static

Definition at line 1634 of file xact.c.

References MemoryContextSwitchTo(), and TopMemoryContext.

Referenced by AbortOutOfAnyTransaction(), and AbortTransaction().

1635 {
1636  /*
1637  * Switch into TransactionAbortContext, which should have some free space
1638  * even if nothing else does. We'll work in this context until we've
1639  * finished cleaning up.
1640  *
1641  * It is barely possible to get here when we've not been able to create
1642  * TransactionAbortContext yet; if so use TopMemoryContext.
1643  */
1644  if (TransactionAbortContext != NULL)
1646  else
1648 }
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
static MemoryContext TransactionAbortContext
Definition: xact.c:269
MemoryContext TopMemoryContext
Definition: mcxt.c:44

◆ AtAbort_ResourceOwner()

static void AtAbort_ResourceOwner ( void  )
static

Definition at line 1666 of file xact.c.

References CurrentResourceOwner, and TopTransactionResourceOwner.

Referenced by AbortTransaction().

1667 {
1668  /*
1669  * Make sure we have a valid ResourceOwner, if possible (else it will be
1670  * NULL, which is OK)
1671  */
1673 }
ResourceOwner TopTransactionResourceOwner
Definition: resowner.c:142
ResourceOwner CurrentResourceOwner
Definition: resowner.c:140

◆ AtCCI_LocalCache()

static void AtCCI_LocalCache ( void  )
static

Definition at line 1357 of file xact.c.

References AtCCI_RelationMap(), and CommandEndInvalidationMessages().

Referenced by CommandCounterIncrement().

1358 {
1359  /*
1360  * Make any pending relation map changes visible. We must do this before
1361  * processing local sinval messages, so that the map changes will get
1362  * reflected into the relcache when relcache invals are processed.
1363  */
1365 
1366  /*
1367  * Make catalog changes visible to me for the next command.
1368  */
1370 }
void CommandEndInvalidationMessages(void)
Definition: inval.c:1065
void AtCCI_RelationMap(void)
Definition: relmapper.c:423

◆ AtCleanup_Memory()

static void AtCleanup_Memory ( void  )
static

Definition at line 1724 of file xact.c.

References Assert, CurTransactionContext, TransactionStateData::curTransactionContext, MemoryContextDelete(), MemoryContextResetAndDeleteChildren, MemoryContextSwitchTo(), TransactionStateData::parent, TopMemoryContext, and TopTransactionContext.

Referenced by AbortOutOfAnyTransaction(), and CleanupTransaction().

1725 {
1727 
1728  /*
1729  * Now that we're "out" of a transaction, have the system allocate things
1730  * in the top memory context instead of per-transaction contexts.
1731  */
1733 
1734  /*
1735  * Clear the special abort context for next time.
1736  */
1737  if (TransactionAbortContext != NULL)
1739 
1740  /*
1741  * Release all transaction-local memory.
1742  */
1743  if (TopTransactionContext != NULL)
1745  TopTransactionContext = NULL;
1746  CurTransactionContext = NULL;
1748 }
static TransactionState CurrentTransactionState
Definition: xact.c:232
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:211
MemoryContext TopTransactionContext
Definition: mcxt.c:49
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
MemoryContext CurTransactionContext
Definition: mcxt.c:50
static MemoryContext TransactionAbortContext
Definition: xact.c:269
struct TransactionStateData * parent
Definition: xact.c:191
MemoryContext curTransactionContext
Definition: xact.c:180
MemoryContext TopMemoryContext
Definition: mcxt.c:44
#define MemoryContextResetAndDeleteChildren(ctx)
Definition: memutils.h:67
#define Assert(condition)
Definition: c.h:699

◆ AtCommit_Memory()

static void AtCommit_Memory ( void  )
static

Definition at line 1376 of file xact.c.

References Assert, CurTransactionContext, TransactionStateData::curTransactionContext, MemoryContextDelete(), MemoryContextSwitchTo(), TopMemoryContext, and TopTransactionContext.

Referenced by CommitTransaction(), and PrepareTransaction().

1377 {
1378  /*
1379  * Now that we're "out" of a transaction, have the system allocate things
1380  * in the top memory context instead of per-transaction contexts.
1381  */
1383 
1384  /*
1385  * Release all transaction-local memory.
1386  */
1387  Assert(TopTransactionContext != NULL);
1389  TopTransactionContext = NULL;
1390  CurTransactionContext = NULL;
1392 }
static TransactionState CurrentTransactionState
Definition: xact.c:232
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:211
MemoryContext TopTransactionContext
Definition: mcxt.c:49
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
MemoryContext CurTransactionContext
Definition: mcxt.c:50
MemoryContext curTransactionContext
Definition: xact.c:180
MemoryContext TopMemoryContext
Definition: mcxt.c:44
#define Assert(condition)
Definition: c.h:699

◆ AtStart_Cache()

static void AtStart_Cache ( void  )
static

Definition at line 977 of file xact.c.

References AcceptInvalidationMessages().

Referenced by StartTransaction().

978 {
980 }
void AcceptInvalidationMessages(void)
Definition: inval.c:679

◆ AtStart_Memory()

static void AtStart_Memory ( void  )
static

Definition at line 986 of file xact.c.

References ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate, AllocSetContextCreateExtended(), Assert, CurrentTransactionState, CurTransactionContext, TransactionStateData::curTransactionContext, MemoryContextSwitchTo(), TopMemoryContext, and TopTransactionContext.

Referenced by StartTransaction().

987 {
989 
990  /*
991  * If this is the first time through, create a private context for
992  * AbortTransaction to work in. By reserving some space now, we can
993  * insulate AbortTransaction from out-of-memory scenarios. Like
994  * ErrorContext, we set it up with slow growth rate and a nonzero minimum
995  * size, so that space will be reserved immediately.
996  */
997  if (TransactionAbortContext == NULL)
1000  "TransactionAbortContext",
1001  32 * 1024,
1002  32 * 1024,
1003  32 * 1024);
1004 
1005  /*
1006  * We shouldn't have a transaction context already.
1007  */
1008  Assert(TopTransactionContext == NULL);
1009 
1010  /*
1011  * Create a toplevel context for the transaction.
1012  */
1015  "TopTransactionContext",
1017 
1018  /*
1019  * In a top-level transaction, CurTransactionContext is the same as
1020  * TopTransactionContext.
1021  */
1024 
1025  /* Make the CurTransactionContext active. */
1027 }
static TransactionState CurrentTransactionState
Definition: xact.c:232
MemoryContext AllocSetContextCreateExtended(MemoryContext parent, const char *name, Size minContextSize, Size initBlockSize, Size maxBlockSize)
Definition: aset.c:388
MemoryContext TopTransactionContext
Definition: mcxt.c:49
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
MemoryContext CurTransactionContext
Definition: mcxt.c:50
static MemoryContext TransactionAbortContext
Definition: xact.c:269
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:192
MemoryContext curTransactionContext
Definition: xact.c:180
MemoryContext TopMemoryContext
Definition: mcxt.c:44
#define AllocSetContextCreate(parent, name, allocparams)
Definition: memutils.h:170
#define Assert(condition)
Definition: c.h:699

◆ AtStart_ResourceOwner()

static void AtStart_ResourceOwner ( void  )
static

Definition at line 1033 of file xact.c.

References Assert, CurrentResourceOwner, CurrentTransactionState, TransactionStateData::curTransactionOwner, CurTransactionResourceOwner, ResourceOwnerCreate(), and TopTransactionResourceOwner.

Referenced by StartTransaction().

1034 {
1036 
1037  /*
1038  * We shouldn't have a transaction resource owner already.
1039  */
1041 
1042  /*
1043  * Create a toplevel resource owner for the transaction.
1044  */
1045  s->curTransactionOwner = ResourceOwnerCreate(NULL, "TopTransaction");
1046 
1050 }
static TransactionState CurrentTransactionState
Definition: xact.c:232
ResourceOwner TopTransactionResourceOwner
Definition: resowner.c:142
ResourceOwner CurTransactionResourceOwner
Definition: resowner.c:141
ResourceOwner CurrentResourceOwner
Definition: resowner.c:140
ResourceOwner curTransactionOwner
Definition: xact.c:181
#define Assert(condition)
Definition: c.h:699
ResourceOwner ResourceOwnerCreate(ResourceOwner parent, const char *name)
Definition: resowner.c:418

◆ AtSubAbort_childXids()

static void AtSubAbort_childXids ( void  )
static

Definition at line 1692 of file xact.c.

References TransactionStateData::childXids, CurrentTransactionState, TransactionStateData::maxChildXids, TransactionStateData::nChildXids, and pfree().

Referenced by AbortSubTransaction().

1693 {
1695 
1696  /*
1697  * We keep the child-XID arrays in TopTransactionContext (see
1698  * AtSubCommit_childXids). This means we'd better free the array
1699  * explicitly at abort to avoid leakage.
1700  */
1701  if (s->childXids != NULL)
1702  pfree(s->childXids);
1703  s->childXids = NULL;
1704  s->nChildXids = 0;
1705  s->maxChildXids = 0;
1706 
1707  /*
1708  * We could prune the unreportedXids array here. But we don't bother. That
1709  * would potentially reduce number of XLOG_XACT_ASSIGNMENT records but it
1710  * would likely introduce more CPU time into the more common paths, so we
1711  * choose not to do that.
1712  */
1713 }
static TransactionState CurrentTransactionState
Definition: xact.c:232
TransactionId * childXids
Definition: xact.c:182
void pfree(void *pointer)
Definition: mcxt.c:1031

◆ AtSubAbort_Memory()

static void AtSubAbort_Memory ( void  )
static

Definition at line 1654 of file xact.c.

References Assert, and MemoryContextSwitchTo().

Referenced by AbortSubTransaction().

1655 {
1657 
1659 }
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
static MemoryContext TransactionAbortContext
Definition: xact.c:269
#define Assert(condition)
Definition: c.h:699

◆ AtSubAbort_ResourceOwner()

static void AtSubAbort_ResourceOwner ( void  )
static

Definition at line 1679 of file xact.c.

References CurrentResourceOwner, CurrentTransactionState, and TransactionStateData::curTransactionOwner.

Referenced by AbortSubTransaction().

1680 {
1682 
1683  /* Make sure we have a valid ResourceOwner */
1685 }
static TransactionState CurrentTransactionState
Definition: xact.c:232
ResourceOwner CurrentResourceOwner
Definition: resowner.c:140
ResourceOwner curTransactionOwner
Definition: xact.c:181

◆ AtSubCleanup_Memory()

static void AtSubCleanup_Memory ( void  )
static

Definition at line 1760 of file xact.c.

References Assert, CurrentTransactionState, CurTransactionContext, TransactionStateData::curTransactionContext, MemoryContextDelete(), MemoryContextResetAndDeleteChildren, MemoryContextSwitchTo(), and TransactionStateData::parent.

Referenced by CleanupSubTransaction().

1761 {
1763 
1764  Assert(s->parent != NULL);
1765 
1766  /* Make sure we're not in an about-to-be-deleted context */
1769 
1770  /*
1771  * Clear the special abort context for next time.
1772  */
1773  if (TransactionAbortContext != NULL)
1775 
1776  /*
1777  * Delete the subxact local memory contexts. Its CurTransactionContext can
1778  * go too (note this also kills CurTransactionContexts from any children
1779  * of the subxact).
1780  */
1781  if (s->curTransactionContext)
1783  s->curTransactionContext = NULL;
1784 }
static TransactionState CurrentTransactionState
Definition: xact.c:232
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:211
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
MemoryContext CurTransactionContext
Definition: mcxt.c:50
static MemoryContext TransactionAbortContext
Definition: xact.c:269
struct TransactionStateData * parent
Definition: xact.c:191
MemoryContext curTransactionContext
Definition: xact.c:180
#define MemoryContextResetAndDeleteChildren(ctx)
Definition: memutils.h:67
#define Assert(condition)
Definition: c.h:699

◆ AtSubCommit_childXids()

static void AtSubCommit_childXids ( void  )
static

Definition at line 1432 of file xact.c.

References Assert, TransactionStateData::childXids, CurrentTransactionState, ereport, errcode(), errmsg(), ERROR, MaxAllocSize, TransactionStateData::maxChildXids, MemoryContextAlloc(), Min, TransactionStateData::nChildXids, TransactionStateData::parent, pfree(), repalloc(), TopTransactionContext, and TransactionStateData::transactionId.

Referenced by CommitSubTransaction().

1433 {
1435  int new_nChildXids;
1436 
1437  Assert(s->parent != NULL);
1438 
1439  /*
1440  * The parent childXids array will need to hold my XID and all my
1441  * childXids, in addition to the XIDs already there.
1442  */
1443  new_nChildXids = s->parent->nChildXids + s->nChildXids + 1;
1444 
1445  /* Allocate or enlarge the parent array if necessary */
1446  if (s->parent->maxChildXids < new_nChildXids)
1447  {
1448  int new_maxChildXids;
1449  TransactionId *new_childXids;
1450 
1451  /*
1452  * Make it 2x what's needed right now, to avoid having to enlarge it
1453  * repeatedly. But we can't go above MaxAllocSize. (The latter limit
1454  * is what ensures that we don't need to worry about integer overflow
1455  * here or in the calculation of new_nChildXids.)
1456  */
1457  new_maxChildXids = Min(new_nChildXids * 2,
1458  (int) (MaxAllocSize / sizeof(TransactionId)));
1459 
1460  if (new_maxChildXids < new_nChildXids)
1461  ereport(ERROR,
1462  (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
1463  errmsg("maximum number of committed subtransactions (%d) exceeded",
1464  (int) (MaxAllocSize / sizeof(TransactionId)))));
1465 
1466  /*
1467  * We keep the child-XID arrays in TopTransactionContext; this avoids
1468  * setting up child-transaction contexts for what might be just a few
1469  * bytes of grandchild XIDs.
1470  */
1471  if (s->parent->childXids == NULL)
1472  new_childXids =
1474  new_maxChildXids * sizeof(TransactionId));
1475  else
1476  new_childXids = repalloc(s->parent->childXids,
1477  new_maxChildXids * sizeof(TransactionId));
1478 
1479  s->parent->childXids = new_childXids;
1480  s->parent->maxChildXids = new_maxChildXids;
1481  }
1482 
1483  /*
1484  * Copy all my XIDs to parent's array.
1485  *
1486  * Note: We rely on the fact that the XID of a child always follows that
1487  * of its parent. By copying the XID of this subtransaction before the
1488  * XIDs of its children, we ensure that the array stays ordered. Likewise,
1489  * all XIDs already in the array belong to subtransactions started and
1490  * subcommitted before us, so their XIDs must precede ours.
1491  */
1493 
1494  if (s->nChildXids > 0)
1495  memcpy(&s->parent->childXids[s->parent->nChildXids + 1],
1496  s->childXids,
1497  s->nChildXids * sizeof(TransactionId));
1498 
1499  s->parent->nChildXids = new_nChildXids;
1500 
1501  /* Release child's array to avoid leakage */
1502  if (s->childXids != NULL)
1503  pfree(s->childXids);
1504  /* We must reset these to avoid double-free if fail later in commit */
1505  s->childXids = NULL;
1506  s->nChildXids = 0;
1507  s->maxChildXids = 0;
1508 }
static TransactionState CurrentTransactionState
Definition: xact.c:232
MemoryContext TopTransactionContext
Definition: mcxt.c:49
uint32 TransactionId
Definition: c.h:474
#define Min(x, y)
Definition: c.h:857
int errcode(int sqlerrcode)
Definition: elog.c:575
TransactionId * childXids
Definition: xact.c:182
void pfree(void *pointer)
Definition: mcxt.c:1031
#define ERROR
Definition: elog.h:43
struct TransactionStateData * parent
Definition: xact.c:191
#define ereport(elevel, rest)
Definition: elog.h:122
#define MaxAllocSize
Definition: memutils.h:40
TransactionId transactionId
Definition: xact.c:172
#define Assert(condition)
Definition: c.h:699
void * repalloc(void *pointer, Size size)
Definition: mcxt.c:1044
int errmsg(const char *fmt,...)
Definition: elog.c:797
void * MemoryContextAlloc(MemoryContext context, Size size)
Definition: mcxt.c:771

◆ AtSubCommit_Memory()

static void AtSubCommit_Memory ( void  )
static

Definition at line 1403 of file xact.c.

References Assert, CurrentTransactionState, CurTransactionContext, TransactionStateData::curTransactionContext, MemoryContextDelete(), MemoryContextIsEmpty(), MemoryContextSwitchTo(), and TransactionStateData::parent.

Referenced by CommitSubTransaction().

1404 {
1406 
1407  Assert(s->parent != NULL);
1408 
1409  /* Return to parent transaction level's memory context. */
1412 
1413  /*
1414  * Ordinarily we cannot throw away the child's CurTransactionContext,
1415  * since the data it contains will be needed at upper commit. However, if
1416  * there isn't actually anything in it, we can throw it away. This avoids
1417  * a small memory leak in the common case of "trivial" subxacts.
1418  */
1420  {
1422  s->curTransactionContext = NULL;
1423  }
1424 }
static TransactionState CurrentTransactionState
Definition: xact.c:232
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:211
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
MemoryContext CurTransactionContext
Definition: mcxt.c:50
bool MemoryContextIsEmpty(MemoryContext context)
Definition: mcxt.c:451
struct TransactionStateData * parent
Definition: xact.c:191
MemoryContext curTransactionContext
Definition: xact.c:180
#define Assert(condition)
Definition: c.h:699

◆ AtSubStart_Memory()

static void AtSubStart_Memory ( void  )
static

Definition at line 1061 of file xact.c.

References ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate, Assert, CurrentTransactionState, CurTransactionContext, TransactionStateData::curTransactionContext, and MemoryContextSwitchTo().

Referenced by StartSubTransaction().

1062 {
1064 
1065  Assert(CurTransactionContext != NULL);
1066 
1067  /*
1068  * Create a CurTransactionContext, which will be used to hold data that
1069  * survives subtransaction commit but disappears on subtransaction abort.
1070  * We make it a child of the immediate parent's CurTransactionContext.
1071  */
1073  "CurTransactionContext",
1076 
1077  /* Make the CurTransactionContext active. */
1079 }
static TransactionState CurrentTransactionState
Definition: xact.c:232
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
MemoryContext CurTransactionContext
Definition: mcxt.c:50
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:192
MemoryContext curTransactionContext
Definition: xact.c:180
#define AllocSetContextCreate(parent, name, allocparams)
Definition: memutils.h:170
#define Assert(condition)
Definition: c.h:699

◆ AtSubStart_ResourceOwner()

static void AtSubStart_ResourceOwner ( void  )
static

Definition at line 1085 of file xact.c.

References Assert, CurrentResourceOwner, CurrentTransactionState, TransactionStateData::curTransactionOwner, CurTransactionResourceOwner, TransactionStateData::parent, and ResourceOwnerCreate().

Referenced by StartSubTransaction().

1086 {
1088 
1089  Assert(s->parent != NULL);
1090 
1091  /*
1092  * Create a resource owner for the subtransaction. We make it a child of
1093  * the immediate parent's resource owner.
1094  */
1095  s->curTransactionOwner =
1097  "SubTransaction");
1098 
1101 }
static TransactionState CurrentTransactionState
Definition: xact.c:232
ResourceOwner CurTransactionResourceOwner
Definition: resowner.c:141
ResourceOwner CurrentResourceOwner
Definition: resowner.c:140
ResourceOwner curTransactionOwner
Definition: xact.c:181
struct TransactionStateData * parent
Definition: xact.c:191
#define Assert(condition)
Definition: c.h:699
ResourceOwner ResourceOwnerCreate(ResourceOwner parent, const char *name)
Definition: resowner.c:418

◆ BeginImplicitTransactionBlock()

void BeginImplicitTransactionBlock ( void  )

Definition at line 3778 of file xact.c.

References TransactionStateData::blockState, CurrentTransactionState, TBLOCK_IMPLICIT_INPROGRESS, and TBLOCK_STARTED.

Referenced by exec_simple_query().

3779 {
3781 
3782  /*
3783  * If we are in STARTED state (that is, no transaction block is open),
3784  * switch to IMPLICIT_INPROGRESS state, creating an implicit transaction
3785  * block.
3786  *
3787  * For caller convenience, we consider all other transaction states as
3788  * legal here; otherwise the caller would need its own state check, which
3789  * seems rather pointless.
3790  */
3791  if (s->blockState == TBLOCK_STARTED)
3793 }
static TransactionState CurrentTransactionState
Definition: xact.c:232
TBlockState blockState
Definition: xact.c:177

◆ BeginInternalSubTransaction()

void BeginInternalSubTransaction ( const char *  name)

Definition at line 4146 of file xact.c.

References TransactionStateData::blockState, BlockStateAsString(), CommitTransactionCommand(), CurrentTransactionState, elog, ereport, errcode(), errmsg(), ERROR, FATAL, IsInParallelMode(), MemoryContextStrdup(), TransactionStateData::name, PushTransaction(), StartTransactionCommand(), TBLOCK_ABORT, TBLOCK_ABORT_END, TBLOCK_ABORT_PENDING, TBLOCK_BEGIN, TBLOCK_DEFAULT, TBLOCK_END, TBLOCK_IMPLICIT_INPROGRESS, TBLOCK_INPROGRESS, TBLOCK_PARALLEL_INPROGRESS, TBLOCK_PREPARE, TBLOCK_STARTED, TBLOCK_SUBABORT, TBLOCK_SUBABORT_END, TBLOCK_SUBABORT_PENDING, TBLOCK_SUBABORT_RESTART, TBLOCK_SUBBEGIN, TBLOCK_SUBCOMMIT, TBLOCK_SUBINPROGRESS, TBLOCK_SUBRELEASE, TBLOCK_SUBRESTART, and TopTransactionContext.

Referenced by exec_stmt_block(), plperl_spi_exec(), plperl_spi_exec_prepared(), plperl_spi_fetchrow(), plperl_spi_prepare(), plperl_spi_query(), plperl_spi_query_prepared(), pltcl_returnnext(), pltcl_subtrans_begin(), pltcl_subtransaction(), PLy_spi_subtransaction_begin(), PLy_subtransaction_enter(), ReorderBufferCommit(), and ReorderBufferImmediateInvalidation().

4147 {
4149 
4150  /*
4151  * Workers synchronize transaction state at the beginning of each parallel
4152  * operation, so we can't account for new subtransactions after that
4153  * point. We might be able to make an exception for the type of
4154  * subtransaction established by this function, which is typically used in
4155  * contexts where we're going to release or roll back the subtransaction
4156  * before proceeding further, so that no enduring change to the
4157  * transaction state occurs. For now, however, we prohibit this case along
4158  * with all the others.
4159  */
4160  if (IsInParallelMode())
4161  ereport(ERROR,
4162  (errcode(ERRCODE_INVALID_TRANSACTION_STATE),
4163  errmsg("cannot start subtransactions during a parallel operation")));
4164 
4165  switch (s->blockState)
4166  {
4167  case TBLOCK_STARTED:
4168  case TBLOCK_INPROGRESS:
4170  case TBLOCK_END:
4171  case TBLOCK_PREPARE:
4172  case TBLOCK_SUBINPROGRESS:
4173  /* Normal subtransaction start */
4174  PushTransaction();
4175  s = CurrentTransactionState; /* changed by push */
4176 
4177  /*
4178  * Savepoint names, like the TransactionState block itself, live
4179  * in TopTransactionContext.
4180  */
4181  if (name)
4183  break;
4184 
4185  /* These cases are invalid. */
4186  case TBLOCK_DEFAULT:
4187  case TBLOCK_BEGIN:
4189  case TBLOCK_SUBBEGIN:
4190  case TBLOCK_SUBRELEASE:
4191  case TBLOCK_SUBCOMMIT:
4192  case TBLOCK_ABORT:
4193  case TBLOCK_SUBABORT:
4194  case TBLOCK_ABORT_END:
4195  case TBLOCK_SUBABORT_END:
4196  case TBLOCK_ABORT_PENDING:
4198  case TBLOCK_SUBRESTART:
4200  elog(FATAL, "BeginInternalSubTransaction: unexpected state %s",
4202  break;
4203  }
4204 
4207 }
static TransactionState CurrentTransactionState
Definition: xact.c:232
MemoryContext TopTransactionContext
Definition: mcxt.c:49
void CommitTransactionCommand(void)
Definition: xact.c:2744
int errcode(int sqlerrcode)
Definition: elog.c:575
TBlockState blockState
Definition: xact.c:177
bool IsInParallelMode(void)
Definition: xact.c:905
#define ERROR
Definition: elog.h:43
#define FATAL
Definition: elog.h:52
static const char * BlockStateAsString(TBlockState blockState)
Definition: xact.c:5125
#define ereport(elevel, rest)
Definition: elog.h:122
static void PushTransaction(void)
Definition: xact.c:4845
void StartTransactionCommand(void)
Definition: xact.c:2673
const char * name
Definition: encode.c:521
int errmsg(const char *fmt,...)
Definition: elog.c:797
char * MemoryContextStrdup(MemoryContext context, const char *string)
Definition: mcxt.c:1148
#define elog
Definition: elog.h:219

◆ BeginTransactionBlock()

void BeginTransactionBlock ( void  )

Definition at line 3412 of file xact.c.

References TransactionStateData::blockState, BlockStateAsString(), CurrentTransactionState, elog, ereport, errcode(), errmsg(), FATAL, TBLOCK_ABORT, TBLOCK_ABORT_END, TBLOCK_ABORT_PENDING, TBLOCK_BEGIN, TBLOCK_DEFAULT, TBLOCK_END, TBLOCK_IMPLICIT_INPROGRESS, TBLOCK_INPROGRESS, TBLOCK_PARALLEL_INPROGRESS, TBLOCK_PREPARE, TBLOCK_STARTED, TBLOCK_SUBABORT, TBLOCK_SUBABORT_END, TBLOCK_SUBABORT_PENDING, TBLOCK_SUBABORT_RESTART, TBLOCK_SUBBEGIN, TBLOCK_SUBCOMMIT, TBLOCK_SUBINPROGRESS, TBLOCK_SUBRELEASE, TBLOCK_SUBRESTART, and WARNING.

Referenced by standard_ProcessUtility().

3413 {
3415 
3416  switch (s->blockState)
3417  {
3418  /*
3419  * We are not inside a transaction block, so allow one to begin.
3420  */
3421  case TBLOCK_STARTED:
3422  s->blockState = TBLOCK_BEGIN;
3423  break;
3424 
3425  /*
3426  * BEGIN converts an implicit transaction block to a regular one.
3427  * (Note that we allow this even if we've already done some
3428  * commands, which is a bit odd but matches historical practice.)
3429  */
3431  s->blockState = TBLOCK_BEGIN;
3432  break;
3433 
3434  /*
3435  * Already a transaction block in progress.
3436  */
3437  case TBLOCK_INPROGRESS:
3439  case TBLOCK_SUBINPROGRESS:
3440  case TBLOCK_ABORT:
3441  case TBLOCK_SUBABORT:
3442  ereport(WARNING,
3443  (errcode(ERRCODE_ACTIVE_SQL_TRANSACTION),
3444  errmsg("there is already a transaction in progress")));
3445  break;
3446 
3447  /* These cases are invalid. */
3448  case TBLOCK_DEFAULT:
3449  case TBLOCK_BEGIN:
3450  case TBLOCK_SUBBEGIN:
3451  case TBLOCK_END:
3452  case TBLOCK_SUBRELEASE:
3453  case TBLOCK_SUBCOMMIT:
3454  case TBLOCK_ABORT_END:
3455  case TBLOCK_SUBABORT_END:
3456  case TBLOCK_ABORT_PENDING:
3458  case TBLOCK_SUBRESTART:
3460  case TBLOCK_PREPARE:
3461  elog(FATAL, "BeginTransactionBlock: unexpected state %s",
3463  break;
3464  }
3465 }
static TransactionState CurrentTransactionState
Definition: xact.c:232
int errcode(int sqlerrcode)
Definition: elog.c:575
TBlockState blockState
Definition: xact.c:177
#define FATAL
Definition: elog.h:52
static const char * BlockStateAsString(TBlockState blockState)
Definition: xact.c:5125
#define ereport(elevel, rest)
Definition: elog.h:122
#define WARNING
Definition: elog.h:40
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define elog
Definition: elog.h:219

◆ BlockStateAsString()

static const char * BlockStateAsString ( TBlockState  blockState)
static

Definition at line 5125 of file xact.c.

References TBLOCK_ABORT, TBLOCK_ABORT_END, TBLOCK_ABORT_PENDING, TBLOCK_BEGIN, TBLOCK_DEFAULT, TBLOCK_END, TBLOCK_IMPLICIT_INPROGRESS, TBLOCK_INPROGRESS, TBLOCK_PARALLEL_INPROGRESS, TBLOCK_PREPARE, TBLOCK_STARTED, TBLOCK_SUBABORT, TBLOCK_SUBABORT_END, TBLOCK_SUBABORT_PENDING, TBLOCK_SUBABORT_RESTART, TBLOCK_SUBBEGIN, TBLOCK_SUBCOMMIT, TBLOCK_SUBINPROGRESS, TBLOCK_SUBRELEASE, and TBLOCK_SUBRESTART.

Referenced by BeginInternalSubTransaction(), BeginTransactionBlock(), CommitTransactionCommand(), DefineSavepoint(), EndTransactionBlock(), ReleaseCurrentSubTransaction(), ReleaseSavepoint(), RollbackAndReleaseCurrentSubTransaction(), RollbackToSavepoint(), ShowTransactionStateRec(), StartTransactionCommand(), TransactionBlockStatusCode(), and UserAbortTransactionBlock().

5126 {
5127  switch (blockState)
5128  {
5129  case TBLOCK_DEFAULT:
5130  return "DEFAULT";
5131  case TBLOCK_STARTED:
5132  return "STARTED";
5133  case TBLOCK_BEGIN:
5134  return "BEGIN";
5135  case TBLOCK_INPROGRESS:
5136  return "INPROGRESS";
5138  return "IMPLICIT_INPROGRESS";
5140  return "PARALLEL_INPROGRESS";
5141  case TBLOCK_END:
5142  return "END";
5143  case TBLOCK_ABORT:
5144  return "ABORT";
5145  case TBLOCK_ABORT_END:
5146  return "ABORT_END";
5147  case TBLOCK_ABORT_PENDING:
5148  return "ABORT_PENDING";
5149  case TBLOCK_PREPARE:
5150  return "PREPARE";
5151  case TBLOCK_SUBBEGIN:
5152  return "SUBBEGIN";
5153  case TBLOCK_SUBINPROGRESS:
5154  return "SUBINPROGRESS";
5155  case TBLOCK_SUBRELEASE:
5156  return "SUBRELEASE";
5157  case TBLOCK_SUBCOMMIT:
5158  return "SUBCOMMIT";
5159  case TBLOCK_SUBABORT:
5160  return "SUBABORT";
5161  case TBLOCK_SUBABORT_END:
5162  return "SUBABORT_END";
5164  return "SUBABORT_PENDING";
5165  case TBLOCK_SUBRESTART:
5166  return "SUBRESTART";
5168  return "SUBABORT_RESTART";
5169  }
5170  return "UNRECOGNIZED";
5171 }

◆ CallSubXactCallbacks()

static void CallSubXactCallbacks ( SubXactEvent  event,
SubTransactionId  mySubid,
SubTransactionId  parentSubid 
)
static

Definition at line 3391 of file xact.c.

References SubXactCallbackItem::arg, SubXactCallbackItem::callback, and SubXactCallbackItem::next.

Referenced by AbortSubTransaction(), CommitSubTransaction(), and StartSubTransaction().

3394 {
3395  SubXactCallbackItem *item;
3396 
3397  for (item = SubXact_callbacks; item; item = item->next)
3398  item->callback(event, mySubid, parentSubid, item->arg);
3399 }
static SubXactCallbackItem * SubXact_callbacks
Definition: xact.c:293
struct SubXactCallbackItem * next
Definition: xact.c:288
SubXactCallback callback
Definition: xact.c:289

◆ CallXactCallbacks()

static void CallXactCallbacks ( XactEvent  event)
static

Definition at line 3336 of file xact.c.

References XactCallbackItem::arg, XactCallbackItem::callback, and XactCallbackItem::next.

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

3337 {
3338  XactCallbackItem *item;
3339 
3340  for (item = Xact_callbacks; item; item = item->next)
3341  item->callback(event, item->arg);
3342 }
struct XactCallbackItem * next
Definition: xact.c:276
void * arg
Definition: xact.c:278
XactCallback callback
Definition: xact.c:277
static XactCallbackItem * Xact_callbacks
Definition: xact.c:281

◆ CheckTransactionBlock()

static void CheckTransactionBlock ( bool  isTopLevel,
bool  throwError,
const char *  stmtType 
)
static

Definition at line 3228 of file xact.c.

References ereport, errcode(), errmsg(), ERROR, IsSubTransaction(), IsTransactionBlock(), and WARNING.

Referenced by RequireTransactionBlock(), and WarnNoTransactionBlock().

3229 {
3230  /*
3231  * xact block already started?
3232  */
3233  if (IsTransactionBlock())
3234  return;
3235 
3236  /*
3237  * subtransaction?
3238  */
3239  if (IsSubTransaction())
3240  return;
3241 
3242  /*
3243  * inside a function call?
3244  */
3245  if (!isTopLevel)
3246  return;
3247 
3248  ereport(throwError ? ERROR : WARNING,
3249  (errcode(ERRCODE_NO_ACTIVE_SQL_TRANSACTION),
3250  /* translator: %s represents an SQL statement name */
3251  errmsg("%s can only be used in transaction blocks",
3252  stmtType)));
3253  return;
3254 }
int errcode(int sqlerrcode)
Definition: elog.c:575
bool IsTransactionBlock(void)
Definition: xact.c:4422
#define ERROR
Definition: elog.h:43
#define ereport(elevel, rest)
Definition: elog.h:122
#define WARNING
Definition: elog.h:40
bool IsSubTransaction(void)
Definition: xact.c:4495
int errmsg(const char *fmt,...)
Definition: elog.c:797

◆ CleanupSubTransaction()

static void CleanupSubTransaction ( void  )
static

Definition at line 4812 of file xact.c.

References AtSubCleanup_Memory(), AtSubCleanup_Portals(), CurrentResourceOwner, CurrentTransactionState, TransactionStateData::curTransactionOwner, CurTransactionResourceOwner, elog, TransactionStateData::parent, PopTransaction(), ResourceOwnerDelete(), ShowTransactionState(), TransactionStateData::state, TransactionStateData::subTransactionId, TRANS_ABORT, TRANS_DEFAULT, TransStateAsString(), and WARNING.

Referenced by AbortCurrentTransaction(), AbortOutOfAnyTransaction(), CommitTransactionCommand(), and RollbackAndReleaseCurrentSubTransaction().

4813 {
4815 
4816  ShowTransactionState("CleanupSubTransaction");
4817 
4818  if (s->state != TRANS_ABORT)
4819  elog(WARNING, "CleanupSubTransaction while in %s state",
4821 
4823 
4826  if (s->curTransactionOwner)
4828  s->curTransactionOwner = NULL;
4829 
4831 
4832  s->state = TRANS_DEFAULT;
4833 
4834  PopTransaction();
4835 }
static TransactionState CurrentTransactionState
Definition: xact.c:232
static void PopTransaction(void)
Definition: xact.c:4904
ResourceOwner CurTransactionResourceOwner
Definition: resowner.c:141
ResourceOwner CurrentResourceOwner
Definition: resowner.c:140
void ResourceOwnerDelete(ResourceOwner owner)
Definition: resowner.c:684
TransState state
Definition: xact.c:176
ResourceOwner curTransactionOwner
Definition: xact.c:181
struct TransactionStateData * parent
Definition: xact.c:191
static void ShowTransactionState(const char *str)
Definition: xact.c:5074
SubTransactionId subTransactionId
Definition: xact.c:173
void AtSubCleanup_Portals(SubTransactionId mySubid)
Definition: portalmem.c:1071
#define WARNING
Definition: elog.h:40
static void AtSubCleanup_Memory(void)
Definition: xact.c:1760
static const char * TransStateAsString(TransState state)
Definition: xact.c:5178
#define elog
Definition: elog.h:219

◆ CleanupTransaction()

static void CleanupTransaction ( void  )
static

Definition at line 2624 of file xact.c.

References AtCleanup_Memory(), AtCleanup_Portals(), AtEOXact_Snapshot(), TransactionStateData::childXids, CurrentResourceOwner, CurrentTransactionState, TransactionStateData::curTransactionOwner, CurTransactionResourceOwner, elog, FATAL, TransactionStateData::gucNestLevel, InvalidSubTransactionId, InvalidTransactionId, TransactionStateData::maxChildXids, TransactionStateData::nChildXids, TransactionStateData::nestingLevel, nParallelCurrentXids, TransactionStateData::parallelModeLevel, ResourceOwnerDelete(), TransactionStateData::state, TransactionStateData::subTransactionId, TopTransactionResourceOwner, TRANS_ABORT, TRANS_DEFAULT, TransactionStateData::transactionId, TransStateAsString(), and XactTopTransactionId.

Referenced by AbortCurrentTransaction(), AbortOutOfAnyTransaction(), and CommitTransactionCommand().

2625 {
2627 
2628  /*
2629  * State should still be TRANS_ABORT from AbortTransaction().
2630  */
2631  if (s->state != TRANS_ABORT)
2632  elog(FATAL, "CleanupTransaction: unexpected state %s",
2634 
2635  /*
2636  * do abort cleanup processing
2637  */
2638  AtCleanup_Portals(); /* now safe to release portal memory */
2639  AtEOXact_Snapshot(false, true); /* and release the transaction's snapshots */
2640 
2641  CurrentResourceOwner = NULL; /* and resource owner */
2644  s->curTransactionOwner = NULL;
2647 
2648  AtCleanup_Memory(); /* and transaction memory */
2649 
2652  s->nestingLevel = 0;
2653  s->gucNestLevel = 0;
2654  s->childXids = NULL;
2655  s->nChildXids = 0;
2656  s->maxChildXids = 0;
2657  s->parallelModeLevel = 0;
2658 
2661 
2662  /*
2663  * done with abort processing, set current transaction state back to
2664  * default
2665  */
2666  s->state = TRANS_DEFAULT;
2667 }
TransactionId XactTopTransactionId
Definition: xact.c:106
static TransactionState CurrentTransactionState
Definition: xact.c:232
ResourceOwner TopTransactionResourceOwner
Definition: resowner.c:142
ResourceOwner CurTransactionResourceOwner
Definition: resowner.c:141
ResourceOwner CurrentResourceOwner
Definition: resowner.c:140
void ResourceOwnerDelete(ResourceOwner owner)
Definition: resowner.c:684
static void AtCleanup_Memory(void)
Definition: xact.c:1724
int nParallelCurrentXids
Definition: xact.c:107
void AtCleanup_Portals(void)
Definition: portalmem.c:839
TransactionId * childXids
Definition: xact.c:182
TransState state
Definition: xact.c:176
ResourceOwner curTransactionOwner
Definition: xact.c:181
#define FATAL
Definition: elog.h:52
#define InvalidTransactionId
Definition: transam.h:31
SubTransactionId subTransactionId
Definition: xact.c:173
TransactionId transactionId
Definition: xact.c:172
int parallelModeLevel
Definition: xact.c:190
static const char * TransStateAsString(TransState state)
Definition: xact.c:5178
#define InvalidSubTransactionId
Definition: c.h:480
#define elog
Definition: elog.h:219
void AtEOXact_Snapshot(bool isCommit, bool resetXmin)
Definition: snapmgr.c:1059

◆ CommandCounterIncrement()

void CommandCounterIncrement ( void  )

Definition at line 914 of file xact.c.

References AtCCI_LocalCache(), currentCommandId, currentCommandIdUsed, elog, ereport, errcode(), errmsg(), ERROR, InvalidCommandId, IsInParallelMode(), IsParallelWorker, and SnapshotSetCommandId().

Referenced by _SPI_execute_plan(), acquire_inherited_sample_rows(), AddRoleMems(), AlterPublicationOptions(), AlterRole(), apply_handle_delete(), apply_handle_insert(), apply_handle_truncate(), apply_handle_update(), ATAddCheckConstraint(), ATExecAddColumn(), ATExecAlterColumnType(), ATExecCmd(), ATExecDropColumn(), ATExecDropConstraint(), ATExecDropIdentity(), ATExecSetTableSpace(), CommitSubTransaction(), CommitTransactionCommand(), copy_heap_data(), create_ctas_internal(), create_toast_table(), CreateFKCheckTrigger(), createForeignKeyActionTriggers(), createForeignKeyTriggers(), CreateForeignTable(), CreatePublication(), CreateRole(), CreateSchemaCommand(), CreateTrigger(), DefineCollation(), DefineDomain(), DefineQueryRewrite(), DefineRange(), DefineRelation(), DefineType(), DefineVirtualRelation(), deleteOneObject(), DelRoleMems(), DropRole(), EventTriggerDDLCommandEnd(), EventTriggerDDLCommandStart(), EventTriggerInvoke(), EventTriggerSQLDrop(), EventTriggerTableRewrite(), exec_eval_simple_expr(), exec_execute_message(), exec_parse_message(), exec_simple_query(), ExecGrant_Database(), ExecGrant_Fdw(), ExecGrant_ForeignServer(), ExecGrant_Function(), ExecGrant_Language(), ExecGrant_Largeobject(), ExecGrant_Namespace(), ExecGrant_Relation(), ExecGrant_Tablespace(), ExecGrant_Type(), execute_sql_string(), ExplainOnePlan(), findTypeInputFunction(), findTypeOutputFunction(), fmgr_sql(), ImportForeignSchema(), index_build(), index_create(), IndexSetParentIndex(), InitTempTableNamespace(), inv_create(), inv_drop(), inv_truncate(), inv_write(), LogicalRepSyncTableStart(), make_new_heap(), makeConfigurationDependencies(), moveArrayTypeName(), OperatorShellMake(), OperatorUpd(), pg_import_system_collations(), PortalRunMulti(), PreCommit_on_commit_actions(), ProcedureCreate(), ProcessUtilitySlow(), recordExtensionInitPrivWorker(), reindex_relation(), RelationSetNewRelfilenode(), RenumberEnumType(), replorigin_create(), replorigin_drop(), ri_PerformCheck(), SetMatViewPopulatedState(), shdepReassignOwned(), SPI_cursor_open_internal(), StoreConstraints(), StorePartitionBound(), and validatePartitionedIndex().

915 {
916  /*
917  * If the current value of the command counter hasn't been "used" to mark
918  * tuples, we need not increment it, since there's no need to distinguish
919  * a read-only command from others. This helps postpone command counter
920  * overflow, and keeps no-op CommandCounterIncrement operations cheap.
921  */
923  {
924  /*
925  * Workers synchronize transaction state at the beginning of each
926  * parallel operation, so we can't account for new commands after that
927  * point.
928  */
930  elog(ERROR, "cannot start commands during a parallel operation");
931 
932  currentCommandId += 1;
934  {
935  currentCommandId -= 1;
936  ereport(ERROR,
937  (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
938  errmsg("cannot have more than 2^32-2 commands in a transaction")));
939  }
940  currentCommandIdUsed = false;
941 
942  /* Propagate new command ID into static snapshots */
944 
945  /*
946  * Make any catalog changes done by the just-completed command visible
947  * in the local syscache. We obviously don't need to do this after a
948  * read-only command. (But see hacks in inval.c to make real sure we
949  * don't think a command that queued inval messages was read-only.)
950  */
952  }
953 }
int errcode(int sqlerrcode)
Definition: elog.c:575
bool IsInParallelMode(void)
Definition: xact.c:905
#define ERROR
Definition: elog.h:43
#define ereport(elevel, rest)
Definition: elog.h:122
#define IsParallelWorker()
Definition: parallel.h:60
#define InvalidCommandId
Definition: c.h:491
static void AtCCI_LocalCache(void)
Definition: xact.c:1357
void SnapshotSetCommandId(CommandId curcid)
Definition: snapmgr.c:544
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define elog
Definition: elog.h:219
static CommandId currentCommandId
Definition: xact.c:239
static bool currentCommandIdUsed
Definition: xact.c:240

◆ CommitSubTransaction()

static void CommitSubTransaction ( void  )
static

Definition at line 4556 of file xact.c.

References AfterTriggerEndSubXact(), AtEOSubXact_Files(), AtEOSubXact_HashTables(), AtEOSubXact_Inval(), AtEOSubXact_LargeObject(), AtEOSubXact_Namespace(), AtEOSubXact_on_commit_actions(), AtEOSubXact_Parallel(), AtEOSubXact_PgStat(), AtEOSubXact_RelationCache(), AtEOSubXact_SPI(), AtEOXact_GUC(), AtSubCommit_childXids(), AtSubCommit_Memory(), AtSubCommit_Notify(), AtSubCommit_Portals(), AtSubCommit_smgr(), AtSubCommit_Snapshot(), CallSubXactCallbacks(), CommandCounterIncrement(), CurrentResourceOwner, CurrentTransactionState, TransactionStateData::curTransactionOwner, CurTransactionResourceOwner, elog, TransactionStateData::gucNestLevel, IsInParallelMode(), TransactionStateData::nestingLevel, TransactionStateData::parallelModeLevel, TransactionStateData::parent, PopTransaction(), TransactionStateData::prevXactReadOnly, RESOURCE_RELEASE_AFTER_LOCKS, RESOURCE_RELEASE_BEFORE_LOCKS, RESOURCE_RELEASE_LOCKS, ResourceOwnerDelete(), ResourceOwnerRelease(), ShowTransactionState(), TransactionStateData::state, TransactionStateData::subTransactionId, SUBXACT_EVENT_COMMIT_SUB, SUBXACT_EVENT_PRE_COMMIT_SUB, TRANS_COMMIT, TRANS_DEFAULT, TRANS_INPROGRESS, TransactionStateData::transactionId, TransactionIdIsValid, TransStateAsString(), WARNING, XactLockTableDelete(), and XactReadOnly.

Referenced by CommitTransactionCommand(), and ReleaseCurrentSubTransaction().

4557 {
4559 
4560  ShowTransactionState("CommitSubTransaction");
4561 
4562  if (s->state != TRANS_INPROGRESS)
4563  elog(WARNING, "CommitSubTransaction while in %s state",
4565 
4566  /* Pre-commit processing goes here */
4567 
4569  s->parent->subTransactionId);
4570 
4571  /* If in parallel mode, clean up workers and exit parallel mode. */
4572  if (IsInParallelMode())
4573  {
4575  s->parallelModeLevel = 0;
4576  }
4577 
4578  /* Do the actual "commit", such as it is */
4579  s->state = TRANS_COMMIT;
4580 
4581  /* Must CCI to ensure commands of subtransaction are seen as done */
4583 
4584  /*
4585  * Prior to 8.4 we marked subcommit in clog at this point. We now only
4586  * perform that step, if required, as part of the atomic update of the
4587  * whole transaction tree at top level commit or abort.
4588  */
4589 
4590  /* Post-commit cleanup */
4593  AfterTriggerEndSubXact(true);
4598  s->parent->subTransactionId);
4600 
4602  s->parent->subTransactionId);
4603 
4606  true, false);
4608  s->parent->subTransactionId);
4609  AtEOSubXact_Inval(true);
4610  AtSubCommit_smgr();
4611 
4612  /*
4613  * The only lock we actually release here is the subtransaction XID lock.
4614  */
4618 
4619  /*
4620  * Other locks should get transferred to their parent resource owner.
4621  */
4624  true, false);
4627  true, false);
4628 
4629  AtEOXact_GUC(true, s->gucNestLevel);
4632  s->parent->subTransactionId);
4634  s->parent->subTransactionId);
4636  s->parent->subTransactionId);
4638  AtEOSubXact_PgStat(true, s->nestingLevel);
4640 
4641  /*
4642  * We need to restore the upper transaction's read-only state, in case the
4643  * upper is read-write while the child is read-only; GUC will incorrectly
4644  * think it should leave the child state in place.
4645  */
4647 
4651  s->curTransactionOwner = NULL;
4652 
4654 
4655  s->state = TRANS_DEFAULT;
4656 
4657  PopTransaction();
4658 }
void AtEOSubXact_RelationCache(bool isCommit, SubTransactionId mySubid, SubTransactionId parentSubid)
Definition: relcache.c:2912
static TransactionState CurrentTransactionState
Definition: xact.c:232
static void AtSubCommit_Memory(void)
Definition: xact.c:1403
static void PopTransaction(void)
Definition: xact.c:4904
ResourceOwner CurTransactionResourceOwner
Definition: resowner.c:141
ResourceOwner CurrentResourceOwner
Definition: resowner.c:140
void AtEOSubXact_HashTables(bool isCommit, int nestDepth)
Definition: dynahash.c:1860
void ResourceOwnerDelete(ResourceOwner owner)
Definition: resowner.c:684
void AtSubCommit_smgr(void)
Definition: storage.c:450
void AtEOSubXact_SPI(bool isCommit, SubTransactionId mySubid)
Definition: spi.c:303
void AtSubCommit_Snapshot(int level)
Definition: snapmgr.c:1002
static void AtSubCommit_childXids(void)
Definition: xact.c:1432
TransState state
Definition: xact.c:176
ResourceOwner curTransactionOwner
Definition: xact.c:181
bool IsInParallelMode(void)
Definition: xact.c:905
struct TransactionStateData * parent
Definition: xact.c:191
void AtSubCommit_Notify(void)
Definition: async.c:1639
static void ShowTransactionState(const char *str)
Definition: xact.c:5074
void AtEOXact_GUC(bool isCommit, int nestLevel)
Definition: guc.c:5312
SubTransactionId subTransactionId
Definition: xact.c:173
void AtEOSubXact_PgStat(bool isCommit, int nestDepth)
Definition: pgstat.c:2136
void AtEOSubXact_LargeObject(bool isCommit, SubTransactionId mySubid, SubTransactionId parentSubid)
Definition: be-fsstubs.c:624
#define WARNING
Definition: elog.h:40
void AtEOSubXact_on_commit_actions(bool isCommit, SubTransactionId mySubid, SubTransactionId parentSubid)
Definition: tablecmds.c:13329
void CommandCounterIncrement(void)
Definition: xact.c:914
void AtEOSubXact_Files(bool isCommit, SubTransactionId mySubid, SubTransactionId parentSubid)
Definition: fd.c:2872
TransactionId transactionId
Definition: xact.c:172
static void CallSubXactCallbacks(SubXactEvent event, SubTransactionId mySubid, SubTransactionId parentSubid)
Definition: xact.c:3391
bool XactReadOnly
Definition: xact.c:76
int parallelModeLevel
Definition: xact.c:190
void ResourceOwnerRelease(ResourceOwner owner, ResourceReleasePhase phase, bool isCommit, bool isTopLevel)
Definition: resowner.c:474
static const char * TransStateAsString(TransState state)
Definition: xact.c:5178
bool prevXactReadOnly
Definition: xact.c:187
void AfterTriggerEndSubXact(bool isCommit)
Definition: trigger.c:5082
void AtEOSubXact_Inval(bool isCommit)
Definition: inval.c:988
void XactLockTableDelete(TransactionId xid)
Definition: lmgr.c:530
#define elog
Definition: elog.h:219
void AtEOSubXact_Namespace(bool isCommit, SubTransactionId mySubid, SubTransactionId parentSubid)
Definition: namespace.c:3962
#define TransactionIdIsValid(xid)
Definition: transam.h:41
void AtEOSubXact_Parallel(bool isCommit, SubTransactionId mySubId)
Definition: parallel.c:1161
void AtSubCommit_Portals(SubTransactionId mySubid, SubTransactionId parentSubid, ResourceOwner parentXactOwner)
Definition: portalmem.c:924

◆ CommitTransaction()

static void CommitTransaction ( void  )
static

Definition at line 1933 of file xact.c.

References AfterTriggerEndXact(), AfterTriggerFireDeferred(), Assert, AtCommit_Memory(), AtCommit_Notify(), AtEOXact_ApplyLauncher(), AtEOXact_Buffers(), AtEOXact_ComboCid(), AtEOXact_Files(), AtEOXact_GUC(), AtEOXact_HashTables(), AtEOXact_Inval(), AtEOXact_LargeObject(), AtEOXact_MultiXact(), AtEOXact_Namespace(), AtEOXact_on_commit_actions(), AtEOXact_Parallel(), AtEOXact_PgStat(), AtEOXact_RelationCache(), AtEOXact_RelationMap(), AtEOXact_SMgr(), AtEOXact_Snapshot(), AtEOXact_SPI(), TransactionStateData::blockState, CallXactCallbacks(), TransactionStateData::childXids, CurrentResourceOwner, CurrentTransactionState, TransactionStateData::curTransactionOwner, CurTransactionResourceOwner, elog, EnterParallelMode(), TransactionStateData::gucNestLevel, HOLD_INTERRUPTS, InvalidSubTransactionId, InvalidTransactionId, IsInParallelMode(), PGPROC::lxid, TransactionStateData::maxChildXids, MyProc, TransactionStateData::nChildXids, TransactionStateData::nestingLevel, nParallelCurrentXids, TransactionStateData::parallelModeLevel, ParallelWorkerReportLastRecEnd(), TransactionStateData::parent, pgstat_report_xact_timestamp(), PreCommit_CheckForSerializationFailure(), PreCommit_Notify(), PreCommit_on_commit_actions(), PreCommit_Portals(), ProcArrayEndTransaction(), RecordTransactionCommit(), RESOURCE_RELEASE_AFTER_LOCKS, RESOURCE_RELEASE_BEFORE_LOCKS, RESOURCE_RELEASE_LOCKS, ResourceOwnerDelete(), ResourceOwnerRelease(), RESUME_INTERRUPTS, ShowTransactionState(), smgrDoPendingDeletes(), TransactionStateData::state, TransactionStateData::subTransactionId, TBLOCK_PARALLEL_INPROGRESS, TopTransactionResourceOwner, TRANS_COMMIT, TRANS_DEFAULT, TRANS_INPROGRESS, TransactionStateData::transactionId, TransStateAsString(), WARNING, XACT_EVENT_COMMIT, XACT_EVENT_PARALLEL_COMMIT, XACT_EVENT_PARALLEL_PRE_COMMIT, XACT_EVENT_PRE_COMMIT, XactLastRecEnd, and XactTopTransactionId.

Referenced by CommitTransactionCommand(), EndParallelWorkerTransaction(), EndRestoreBlobs(), restore_toc_entry(), and RestoreArchive().

1934 {
1936  TransactionId latestXid;
1937  bool is_parallel_worker;
1938 
1939  is_parallel_worker = (s->blockState == TBLOCK_PARALLEL_INPROGRESS);
1940 
1941  /* Enforce parallel mode restrictions during parallel worker commit. */
1942  if (is_parallel_worker)
1944 
1945  ShowTransactionState("CommitTransaction");
1946 
1947  /*
1948  * check the current transaction state
1949  */
1950  if (s->state != TRANS_INPROGRESS)
1951  elog(WARNING, "CommitTransaction while in %s state",
1953  Assert(s->parent == NULL);
1954 
1955  /*
1956  * Do pre-commit processing that involves calling user-defined code, such
1957  * as triggers. Since closing cursors could queue trigger actions,
1958  * triggers could open cursors, etc, we have to keep looping until there's
1959  * nothing left to do.
1960  */
1961  for (;;)
1962  {
1963  /*
1964  * Fire all currently pending deferred triggers.
1965  */
1967 
1968  /*
1969  * Close open portals (converting holdable ones into static portals).
1970  * If there weren't any, we are done ... otherwise loop back to check
1971  * if they queued deferred triggers. Lather, rinse, repeat.
1972  */
1973  if (!PreCommit_Portals(false))
1974  break;
1975  }
1976 
1979 
1980  /*
1981  * The remaining actions cannot call any user-defined code, so it's safe
1982  * to start shutting down within-transaction services. But note that most
1983  * of this stuff could still throw an error, which would switch us into
1984  * the transaction-abort path.
1985  */
1986 
1987  /* If we might have parallel workers, clean them up now. */
1988  if (IsInParallelMode())
1989  AtEOXact_Parallel(true);
1990 
1991  /* Shut down the deferred-trigger manager */
1992  AfterTriggerEndXact(true);
1993 
1994  /*
1995  * Let ON COMMIT management do its thing (must happen after closing
1996  * cursors, to avoid dangling-reference problems)
1997  */
1999 
2000  /* close large objects before lower-level cleanup */
2001  AtEOXact_LargeObject(true);
2002 
2003  /*
2004  * Mark serializable transaction as complete for predicate locking
2005  * purposes. This should be done as late as we can put it and still allow
2006  * errors to be raised for failure patterns found at commit.
2007  */
2009 
2010  /*
2011  * Insert notifications sent by NOTIFY commands into the queue. This
2012  * should be late in the pre-commit sequence to minimize time spent
2013  * holding the notify-insertion lock.
2014  */
2015  PreCommit_Notify();
2016 
2017  /* Prevent cancel/die interrupt while cleaning up */
2018  HOLD_INTERRUPTS();
2019 
2020  /* Commit updates to the relation map --- do this as late as possible */
2021  AtEOXact_RelationMap(true);
2022 
2023  /*
2024  * set the current transaction state information appropriately during
2025  * commit processing
2026  */
2027  s->state = TRANS_COMMIT;
2028  s->parallelModeLevel = 0;
2029 
2030  if (!is_parallel_worker)
2031  {
2032  /*
2033  * We need to mark our XIDs as committed in pg_xact. This is where we
2034  * durably commit.
2035  */
2036  latestXid = RecordTransactionCommit();
2037  }
2038  else
2039  {
2040  /*
2041  * We must not mark our XID committed; the parallel master is
2042  * responsible for that.
2043  */
2044  latestXid = InvalidTransactionId;
2045 
2046  /*
2047  * Make sure the master will know about any WAL we wrote before it
2048  * commits.
2049  */
2051  }
2052 
2053  TRACE_POSTGRESQL_TRANSACTION_COMMIT(MyProc->lxid);
2054 
2055  /*
2056  * Let others know about no transaction in progress by me. Note that this
2057  * must be done _before_ releasing locks we hold and _after_
2058  * RecordTransactionCommit.
2059  */
2060  ProcArrayEndTransaction(MyProc, latestXid);
2061 
2062  /*
2063  * This is all post-commit cleanup. Note that if an error is raised here,
2064  * it's too late to abort the transaction. This should be just
2065  * noncritical resource releasing.
2066  *
2067  * The ordering of operations is not entirely random. The idea is:
2068  * release resources visible to other backends (eg, files, buffer pins);
2069  * then release locks; then release backend-local resources. We want to
2070  * release locks at the point where any backend waiting for us will see
2071  * our transaction as being fully cleaned up.
2072  *
2073  * Resources that can be associated with individual queries are handled by
2074  * the ResourceOwner mechanism. The other calls here are for backend-wide
2075  * state.
2076  */
2077 
2078  CallXactCallbacks(is_parallel_worker ? XACT_EVENT_PARALLEL_COMMIT
2079  : XACT_EVENT_COMMIT);
2080 
2083  true, true);
2084 
2085  /* Check we've released all buffer pins */
2086  AtEOXact_Buffers(true);
2087 
2088  /* Clean up the relation cache */
2089  AtEOXact_RelationCache(true);
2090 
2091  /*
2092  * Make catalog changes visible to all backends. This has to happen after
2093  * relcache references are dropped (see comments for
2094  * AtEOXact_RelationCache), but before locks are released (if anyone is
2095  * waiting for lock on a relation we've modified, we want them to know
2096  * about the catalog change before they start using the relation).
2097  */
2098  AtEOXact_Inval(true);
2099 
2101 
2104  true, true);
2107  true, true);
2108 
2109  /*
2110  * Likewise, dropping of files deleted during the transaction is best done
2111  * after releasing relcache and buffer pins. (This is not strictly
2112  * necessary during commit, since such pins should have been released
2113  * already, but this ordering is definitely critical during abort.) Since
2114  * this may take many seconds, also delay until after releasing locks.
2115  * Other backends will observe the attendant catalog changes and not
2116  * attempt to access affected files.
2117  */
2118  smgrDoPendingDeletes(true);
2119 
2120  AtCommit_Notify();
2121  AtEOXact_GUC(true, 1);
2122  AtEOXact_SPI(true);
2124  AtEOXact_Namespace(true, is_parallel_worker);
2125  AtEOXact_SMgr();
2126  AtEOXact_Files(true);
2128  AtEOXact_HashTables(true);
2129  AtEOXact_PgStat(true);
2130  AtEOXact_Snapshot(true, false);
2131  AtEOXact_ApplyLauncher(true);
2133 
2134  CurrentResourceOwner = NULL;
2136  s->curTransactionOwner = NULL;
2139 
2140  AtCommit_Memory();
2141 
2144  s->nestingLevel = 0;
2145  s->gucNestLevel = 0;
2146  s->childXids = NULL;
2147  s->nChildXids = 0;
2148  s->maxChildXids = 0;
2149 
2152 
2153  /*
2154  * done with commit processing, set current transaction state back to
2155  * default
2156  */
2157  s->state = TRANS_DEFAULT;
2158 
2160 }
void AtEOXact_ApplyLauncher(bool isCommit)
Definition: launcher.c:833
TransactionId XactTopTransactionId
Definition: xact.c:106
void smgrDoPendingDeletes(bool isCommit)
Definition: storage.c:305
static TransactionState CurrentTransactionState
Definition: xact.c:232
void AtEOXact_Inval(bool isCommit)
Definition: inval.c:929
uint32 TransactionId
Definition: c.h:474
static void AtCommit_Memory(void)
Definition: xact.c:1376
void pgstat_report_xact_timestamp(TimestampTz tstamp)
Definition: pgstat.c:3196
XLogRecPtr XactLastRecEnd
Definition: xlog.c:339
void AtEOXact_RelationCache(bool isCommit)
Definition: relcache.c:2761
ResourceOwner TopTransactionResourceOwner
Definition: resowner.c:142
PGPROC * MyProc
Definition: proc.c:67
void AtEOXact_Buffers(bool isCommit)
Definition: bufmgr.c:2415
ResourceOwner CurTransactionResourceOwner
Definition: resowner.c:141
ResourceOwner CurrentResourceOwner
Definition: resowner.c:140
void AtEOXact_RelationMap(bool isCommit)
Definition: relmapper.c:457
void ResourceOwnerDelete(ResourceOwner owner)
Definition: resowner.c:684
static void CallXactCallbacks(XactEvent event)
Definition: xact.c:3336
int nParallelCurrentXids
Definition: xact.c:107
void AtEOXact_on_commit_actions(bool isCommit)
Definition: tablecmds.c:13287
void ProcArrayEndTransaction(PGPROC *proc, TransactionId latestXid)
Definition: procarray.c:396
static TransactionId RecordTransactionCommit(void)
Definition: xact.c:1117
void AtEOXact_Files(bool isCommit)
Definition: fd.c:2905
TBlockState blockState
Definition: xact.c:177
TransactionId * childXids
Definition: xact.c:182
void PreCommit_CheckForSerializationFailure(void)
Definition: predicate.c:4666
#define RESUME_INTERRUPTS()
Definition: miscadmin.h:117
void PreCommit_Notify(void)
Definition: async.c:775
TransState state
Definition: xact.c:176
ResourceOwner curTransactionOwner
Definition: xact.c:181
void AtEOXact_SMgr(void)
Definition: smgr.c:798
bool IsInParallelMode(void)
Definition: xact.c:905
void AfterTriggerEndXact(bool isCommit)
Definition: trigger.c:4986
struct TransactionStateData * parent
Definition: xact.c:191
static void ShowTransactionState(const char *str)
Definition: xact.c:5074
void AtEOXact_GUC(bool isCommit, int nestLevel)
Definition: guc.c:5312
#define InvalidTransactionId
Definition: transam.h:31
SubTransactionId subTransactionId
Definition: xact.c:173
#define WARNING
Definition: elog.h:40
TransactionId transactionId
Definition: xact.c:172
void ParallelWorkerReportLastRecEnd(XLogRecPtr last_xlog_end)
Definition: parallel.c:1421
void AtEOXact_ComboCid(void)
Definition: combocid.c:183
void AfterTriggerFireDeferred(void)
Definition: trigger.c:4930
int parallelModeLevel
Definition: xact.c:190
#define Assert(condition)
Definition: c.h:699
void ResourceOwnerRelease(ResourceOwner owner, ResourceReleasePhase phase, bool isCommit, bool isTopLevel)
Definition: resowner.c:474
static const char * TransStateAsString(TransState state)
Definition: xact.c:5178
void AtEOXact_SPI(bool isCommit)
Definition: spi.c:281
void AtEOXact_MultiXact(void)
Definition: multixact.c:1662
void EnterParallelMode(void)
Definition: xact.c:872
#define InvalidSubTransactionId
Definition: c.h:480
bool PreCommit_Portals(bool isPrepare)
Definition: portalmem.c:670
void PreCommit_on_commit_actions(void)
Definition: tablecmds.c:13216
void AtCommit_Notify(void)
Definition: async.c:874
#define HOLD_INTERRUPTS()
Definition: miscadmin.h:115
#define elog
Definition: elog.h:219
void AtEOXact_HashTables(bool isCommit)
Definition: dynahash.c:1834
void AtEOXact_LargeObject(bool isCommit)
Definition: be-fsstubs.c:583
void AtEOXact_Parallel(bool isCommit)
Definition: parallel.c:1180
void AtEOXact_Namespace(bool isCommit, bool parallel)
Definition: namespace.c:3907
void AtEOXact_Snapshot(bool isCommit, bool resetXmin)
Definition: snapmgr.c:1059
void AtEOXact_PgStat(bool isCommit)
Definition: pgstat.c:2053
LocalTransactionId lxid
Definition: proc.h:106

◆ CommitTransactionCommand()

void CommitTransactionCommand ( void  )

Definition at line 2744 of file xact.c.

References AbortSubTransaction(), AbortTransaction(), Assert, AssertState, TransactionStateData::blockState, BlockStateAsString(), CleanupSubTransaction(), CleanupTransaction(), CommandCounterIncrement(), CommitSubTransaction(), CommitTransaction(), CommitTransactionCommand(), CurrentTransactionState, DefineSavepoint(), elog, ERROR, FATAL, TransactionStateData::name, TransactionStateData::parent, PrepareTransaction(), TransactionStateData::savepointLevel, StartSubTransaction(), TBLOCK_ABORT, TBLOCK_ABORT_END, TBLOCK_ABORT_PENDING, TBLOCK_BEGIN, TBLOCK_DEFAULT, TBLOCK_END, TBLOCK_IMPLICIT_INPROGRESS, TBLOCK_INPROGRESS, TBLOCK_PARALLEL_INPROGRESS, TBLOCK_PREPARE, TBLOCK_STARTED, TBLOCK_SUBABORT, TBLOCK_SUBABORT_END, TBLOCK_SUBABORT_PENDING, TBLOCK_SUBABORT_RESTART, TBLOCK_SUBBEGIN, TBLOCK_SUBCOMMIT, TBLOCK_SUBINPROGRESS, TBLOCK_SUBRELEASE, and TBLOCK_SUBRESTART.

Referenced by apply_handle_commit(), ApplyWorkerMain(), autoprewarm_database_main(), BeginInternalSubTransaction(), BootstrapModeMain(), cluster(), CommitTransactionCommand(), DefineIndex(), do_autovacuum(), finish_xact_command(), get_database_list(), get_subscription_list(), IdentifySystem(), index_drop(), initialize_worker_spi(), InitPostgres(), LogicalRepSyncTableStart(), maybe_reread_subscription(), movedb(), ParallelWorkerMain(), pg_attribute_noreturn(), process_syncing_tables_for_apply(), ProcessCatchupInterrupt(), ProcessCompletedNotifies(), ProcessIncomingNotify(), ReindexMultipleTables(), RemoveTempRelationsCallback(), SPI_commit(), vacuum(), and vacuum_rel().

2745 {
2747 
2748  switch (s->blockState)
2749  {
2750  /*
2751  * These shouldn't happen. TBLOCK_DEFAULT means the previous
2752  * StartTransactionCommand didn't set the STARTED state
2753  * appropriately, while TBLOCK_PARALLEL_INPROGRESS should be ended
2754  * by EndParallelWorkerTransaction(), not this function.
2755  */
2756  case TBLOCK_DEFAULT:
2758  elog(FATAL, "CommitTransactionCommand: unexpected state %s",
2760  break;
2761 
2762  /*
2763  * If we aren't in a transaction block, just do our usual
2764  * transaction commit, and return to the idle state.
2765  */
2766  case TBLOCK_STARTED:
2769  break;
2770 
2771  /*
2772  * We are completing a "BEGIN TRANSACTION" command, so we change
2773  * to the "transaction block in progress" state and return. (We
2774  * assume the BEGIN did nothing to the database, so we need no
2775  * CommandCounterIncrement.)
2776  */
2777  case TBLOCK_BEGIN:
2779  break;
2780 
2781  /*
2782  * This is the case when we have finished executing a command
2783  * someplace within a transaction block. We increment the command
2784  * counter and return.
2785  */
2786  case TBLOCK_INPROGRESS:
2788  case TBLOCK_SUBINPROGRESS:
2790  break;
2791 
2792  /*
2793  * We are completing a "COMMIT" command. Do it and return to the
2794  * idle state.
2795  */
2796  case TBLOCK_END:
2799  break;
2800 
2801  /*
2802  * Here we are in the middle of a transaction block but one of the
2803  * commands caused an abort so we do nothing but remain in the
2804  * abort state. Eventually we will get a ROLLBACK command.
2805  */
2806  case TBLOCK_ABORT:
2807  case TBLOCK_SUBABORT:
2808  break;
2809 
2810  /*
2811  * Here we were in an aborted transaction block and we just got
2812  * the ROLLBACK command from the user, so clean up the
2813  * already-aborted transaction and return to the idle state.
2814  */
2815  case TBLOCK_ABORT_END:
2818  break;
2819 
2820  /*
2821  * Here we were in a perfectly good transaction block but the user
2822  * told us to ROLLBACK anyway. We have to abort the transaction
2823  * and then clean up.
2824  */
2825  case TBLOCK_ABORT_PENDING:
2826  AbortTransaction();
2829  break;
2830 
2831  /*
2832  * We are completing a "PREPARE TRANSACTION" command. Do it and
2833  * return to the idle state.
2834  */
2835  case TBLOCK_PREPARE:
2838  break;
2839 
2840  /*
2841  * We were just issued a SAVEPOINT inside a transaction block.
2842  * Start a subtransaction. (DefineSavepoint already did
2843  * PushTransaction, so as to have someplace to put the SUBBEGIN
2844  * state.)
2845  */
2846  case TBLOCK_SUBBEGIN:
2849  break;
2850 
2851  /*
2852  * We were issued a RELEASE command, so we end the current
2853  * subtransaction and return to the parent transaction. The parent
2854  * might be ended too, so repeat till we find an INPROGRESS
2855  * transaction or subtransaction.
2856  */
2857  case TBLOCK_SUBRELEASE:
2858  do
2859  {
2861  s = CurrentTransactionState; /* changed by pop */
2862  } while (s->blockState == TBLOCK_SUBRELEASE);
2863 
2866  break;
2867 
2868  /*
2869  * We were issued a COMMIT, so we end the current subtransaction
2870  * hierarchy and perform final commit. We do this by rolling up
2871  * any subtransactions into their parent, which leads to O(N^2)
2872  * operations with respect to resource owners - this isn't that
2873  * bad until we approach a thousands of savepoints but is
2874  * necessary for correctness should after triggers create new
2875  * resource owners.
2876  */
2877  case TBLOCK_SUBCOMMIT:
2878  do
2879  {
2881  s = CurrentTransactionState; /* changed by pop */
2882  } while (s->blockState == TBLOCK_SUBCOMMIT);
2883  /* If we had a COMMIT command, finish off the main xact too */
2884  if (s->blockState == TBLOCK_END)
2885  {
2886  Assert(s->parent == NULL);
2889  }
2890  else if (s->blockState == TBLOCK_PREPARE)
2891  {
2892  Assert(s->parent == NULL);
2895  }
2896  else
2897  elog(ERROR, "CommitTransactionCommand: unexpected state %s",
2899  break;
2900 
2901  /*
2902  * The current already-failed subtransaction is ending due to a
2903  * ROLLBACK or ROLLBACK TO command, so pop it and recursively
2904  * examine the parent (which could be in any of several states).
2905  */
2906  case TBLOCK_SUBABORT_END:
2909  break;
2910 
2911  /*
2912  * As above, but it's not dead yet, so abort first.
2913  */
2918  break;
2919 
2920  /*
2921  * The current subtransaction is the target of a ROLLBACK TO
2922  * command. Abort and pop it, then start a new subtransaction
2923  * with the same name.
2924  */
2925  case TBLOCK_SUBRESTART:
2926  {
2927  char *name;
2928  int savepointLevel;
2929 
2930  /* save name and keep Cleanup from freeing it */
2931  name = s->name;
2932  s->name = NULL;
2933  savepointLevel = s->savepointLevel;
2934 
2937 
2938  DefineSavepoint(NULL);
2939  s = CurrentTransactionState; /* changed by push */
2940  s->name = name;
2941  s->savepointLevel = savepointLevel;
2942 
2943  /* This is the same as TBLOCK_SUBBEGIN case */
2947  }
2948  break;
2949 
2950  /*
2951  * Same as above, but the subtransaction had already failed, so we
2952  * don't need AbortSubTransaction.
2953  */
2955  {
2956  char *name;
2957  int savepointLevel;
2958 
2959  /* save name and keep Cleanup from freeing it */
2960  name = s->name;
2961  s->name = NULL;
2962  savepointLevel = s->savepointLevel;
2963 
2965 
2966  DefineSavepoint(NULL);
2967  s = CurrentTransactionState; /* changed by push */
2968  s->name = name;
2969  s->savepointLevel = savepointLevel;
2970 
2971  /* This is the same as TBLOCK_SUBBEGIN case */
2975  }
2976  break;
2977  }
2978 }
static TransactionState CurrentTransactionState
Definition: xact.c:232
#define AssertState(condition)
Definition: c.h:702
void CommitTransactionCommand(void)
Definition: xact.c:2744
void DefineSavepoint(const char *name)
Definition: xact.c:3825
TBlockState blockState
Definition: xact.c:177
static void PrepareTransaction(void)
Definition: xact.c:2169
#define ERROR
Definition: elog.h:43
static void CommitSubTransaction(void)
Definition: xact.c:4556
#define FATAL
Definition: elog.h:52
static void CleanupTransaction(void)
Definition: xact.c:2624
struct TransactionStateData * parent
Definition: xact.c:191
static const char * BlockStateAsString(TBlockState blockState)
Definition: xact.c:5125
static void AbortSubTransaction(void)
Definition: xact.c:4664
void CommandCounterIncrement(void)
Definition: xact.c:914
static void AbortTransaction(void)
Definition: xact.c:2444
#define Assert(condition)
Definition: c.h:699
static void CleanupSubTransaction(void)
Definition: xact.c:4812
const char * name
Definition: encode.c:521
static void CommitTransaction(void)
Definition: xact.c:1933
#define elog
Definition: elog.h:219
static void StartSubTransaction(void)
Definition: xact.c:4518

◆ DefineSavepoint()

void DefineSavepoint ( const char *  name)

Definition at line 3825 of file xact.c.

References TransactionStateData::blockState, BlockStateAsString(), CurrentTransactionState, elog, ereport, errcode(), errmsg(), ERROR, FATAL, IsInParallelMode(), MemoryContextStrdup(), TransactionStateData::name, PushTransaction(), TBLOCK_ABORT, TBLOCK_ABORT_END, TBLOCK_ABORT_PENDING, TBLOCK_BEGIN, TBLOCK_DEFAULT, TBLOCK_END, TBLOCK_IMPLICIT_INPROGRESS, TBLOCK_INPROGRESS, TBLOCK_PARALLEL_INPROGRESS, TBLOCK_PREPARE, TBLOCK_STARTED, TBLOCK_SUBABORT, TBLOCK_SUBABORT_END, TBLOCK_SUBABORT_PENDING, TBLOCK_SUBABORT_RESTART, TBLOCK_SUBBEGIN, TBLOCK_SUBCOMMIT, TBLOCK_SUBINPROGRESS, TBLOCK_SUBRELEASE, TBLOCK_SUBRESTART, and TopTransactionContext.

Referenced by CommitTransactionCommand(), and standard_ProcessUtility().

3826 {
3828 
3829  /*
3830  * Workers synchronize transaction state at the beginning of each parallel
3831  * operation, so we can't account for new subtransactions after that
3832  * point. (Note that this check will certainly error out if s->blockState
3833  * is TBLOCK_PARALLEL_INPROGRESS, so we can treat that as an invalid case
3834  * below.)
3835  */
3836  if (IsInParallelMode())
3837  ereport(ERROR,
3838  (errcode(ERRCODE_INVALID_TRANSACTION_STATE),
3839  errmsg("cannot define savepoints during a parallel operation")));
3840 
3841  switch (s->blockState)
3842  {
3843  case TBLOCK_INPROGRESS:
3844  case TBLOCK_SUBINPROGRESS:
3845  /* Normal subtransaction start */
3846  PushTransaction();
3847  s = CurrentTransactionState; /* changed by push */
3848 
3849  /*
3850  * Savepoint names, like the TransactionState block itself, live
3851  * in TopTransactionContext.
3852  */
3853  if (name)
3855  break;
3856 
3857  /*
3858  * We disallow savepoint commands in implicit transaction blocks.
3859  * There would be no great difficulty in allowing them so far as
3860  * this module is concerned, but a savepoint seems inconsistent
3861  * with exec_simple_query's behavior of abandoning the whole query
3862  * string upon error. Also, the point of an implicit transaction
3863  * block (as opposed to a regular one) is to automatically close
3864  * after an error, so it's hard to see how a savepoint would fit
3865  * into that.
3866  *
3867  * The error messages for this are phrased as if there were no
3868  * active transaction block at all, which is historical but
3869  * perhaps could be improved.
3870  */
3872  ereport(ERROR,
3873  (errcode(ERRCODE_NO_ACTIVE_SQL_TRANSACTION),
3874  /* translator: %s represents an SQL statement name */
3875  errmsg("%s can only be used in transaction blocks",
3876  "SAVEPOINT")));
3877  break;
3878 
3879  /* These cases are invalid. */
3880  case TBLOCK_DEFAULT:
3881  case TBLOCK_STARTED:
3882  case TBLOCK_BEGIN:
3884  case TBLOCK_SUBBEGIN:
3885  case TBLOCK_END:
3886  case TBLOCK_SUBRELEASE:
3887  case TBLOCK_SUBCOMMIT:
3888  case TBLOCK_ABORT:
3889  case TBLOCK_SUBABORT:
3890  case TBLOCK_ABORT_END:
3891  case TBLOCK_SUBABORT_END:
3892  case TBLOCK_ABORT_PENDING:
3894  case TBLOCK_SUBRESTART:
3896  case TBLOCK_PREPARE:
3897  elog(FATAL, "DefineSavepoint: unexpected state %s",
3899  break;
3900  }
3901 }
static TransactionState CurrentTransactionState
Definition: xact.c:232
MemoryContext TopTransactionContext
Definition: mcxt.c:49
int errcode(int sqlerrcode)
Definition: elog.c:575
TBlockState blockState
Definition: xact.c:177
bool IsInParallelMode(void)
Definition: xact.c:905
#define ERROR
Definition: elog.h:43
#define FATAL
Definition: elog.h:52
static const char * BlockStateAsString(TBlockState blockState)
Definition: xact.c:5125
#define ereport(elevel, rest)
Definition: elog.h:122
static void PushTransaction(void)
Definition: xact.c:4845
const char * name
Definition: encode.c:521
int errmsg(const char *fmt,...)
Definition: elog.c:797
char * MemoryContextStrdup(MemoryContext context, const char *string)
Definition: mcxt.c:1148
#define elog
Definition: elog.h:219

◆ EndImplicitTransactionBlock()

void EndImplicitTransactionBlock ( void  )

Definition at line 3803 of file xact.c.

References TransactionStateData::blockState, CurrentTransactionState, TBLOCK_IMPLICIT_INPROGRESS, and TBLOCK_STARTED.

Referenced by exec_simple_query().

3804 {
3806 
3807  /*
3808  * If we are in IMPLICIT_INPROGRESS state, switch back to STARTED state,
3809  * allowing CommitTransactionCommand to commit whatever happened during
3810  * the implicit transaction block as though it were a single statement.
3811  *
3812  * For caller convenience, we consider all other transaction states as
3813  * legal here; otherwise the caller would need its own state check, which
3814  * seems rather pointless.
3815  */
3818 }
static TransactionState CurrentTransactionState
Definition: xact.c:232
TBlockState blockState
Definition: xact.c:177

◆ EndParallelWorkerTransaction()

void EndParallelWorkerTransaction ( void  )

Definition at line 5062 of file xact.c.

References Assert, TransactionStateData::blockState, CommitTransaction(), TBLOCK_DEFAULT, and TBLOCK_PARALLEL_INPROGRESS.

Referenced by ParallelWorkerMain().

5063 {
5067 }
static TransactionState CurrentTransactionState
Definition: xact.c:232
TBlockState blockState
Definition: xact.c:177
#define Assert(condition)
Definition: c.h:699
static void CommitTransaction(void)
Definition: xact.c:1933

◆ EndTransactionBlock()

bool EndTransactionBlock ( void  )

Definition at line 3532 of file xact.c.

References TransactionStateData::blockState, BlockStateAsString(), CurrentTransactionState, elog, ereport, errcode(), errmsg(), FATAL, TransactionStateData::parent, TBLOCK_ABORT, TBLOCK_ABORT_END, TBLOCK_ABORT_PENDING, TBLOCK_BEGIN, TBLOCK_DEFAULT, TBLOCK_END, TBLOCK_IMPLICIT_INPROGRESS, TBLOCK_INPROGRESS, TBLOCK_PARALLEL_INPROGRESS, TBLOCK_PREPARE, TBLOCK_STARTED, TBLOCK_SUBABORT, TBLOCK_SUBABORT_END, TBLOCK_SUBABORT_PENDING, TBLOCK_SUBABORT_RESTART, TBLOCK_SUBBEGIN, TBLOCK_SUBCOMMIT, TBLOCK_SUBINPROGRESS, TBLOCK_SUBRELEASE, TBLOCK_SUBRESTART, and WARNING.

Referenced by PrepareTransactionBlock(), and standard_ProcessUtility().

3533 {
3535  bool result = false;
3536 
3537  switch (s->blockState)
3538  {
3539  /*
3540  * We are in a transaction block, so tell CommitTransactionCommand
3541  * to COMMIT.
3542  */
3543  case TBLOCK_INPROGRESS:
3544  s->blockState = TBLOCK_END;
3545  result = true;
3546  break;
3547 
3548  /*
3549  * In an implicit transaction block, commit, but issue a warning
3550  * because there was no explicit BEGIN before this.
3551  */
3553  ereport(WARNING,
3554  (errcode(ERRCODE_NO_ACTIVE_SQL_TRANSACTION),
3555  errmsg("there is no transaction in progress")));
3556  s->blockState = TBLOCK_END;
3557  result = true;
3558  break;
3559 
3560  /*
3561  * We are in a failed transaction block. Tell
3562  * CommitTransactionCommand it's time to exit the block.
3563  */
3564  case TBLOCK_ABORT:
3566  break;
3567 
3568  /*
3569  * We are in a live subtransaction block. Set up to subcommit all
3570  * open subtransactions and then commit the main transaction.
3571  */
3572  case TBLOCK_SUBINPROGRESS:
3573  while (s->parent != NULL)
3574  {
3575  if (s->blockState == TBLOCK_SUBINPROGRESS)
3577  else
3578  elog(FATAL, "EndTransactionBlock: unexpected state %s",
3580  s = s->parent;
3581  }
3582  if (s->blockState == TBLOCK_INPROGRESS)
3583  s->blockState = TBLOCK_END;
3584  else
3585  elog(FATAL, "EndTransactionBlock: unexpected state %s",
3587  result = true;
3588  break;
3589 
3590  /*
3591  * Here we are inside an aborted subtransaction. Treat the COMMIT
3592  * as ROLLBACK: set up to abort everything and exit the main
3593  * transaction.
3594  */
3595  case TBLOCK_SUBABORT:
3596  while (s->parent != NULL)
3597  {
3598  if (s->blockState == TBLOCK_SUBINPROGRESS)
3600  else if (s->blockState == TBLOCK_SUBABORT)
3602  else
3603  elog(FATAL, "EndTransactionBlock: unexpected state %s",
3605  s = s->parent;
3606  }
3607  if (s->blockState == TBLOCK_INPROGRESS)
3609  else if (s->blockState == TBLOCK_ABORT)
3611  else
3612  elog(FATAL, "EndTransactionBlock: unexpected state %s",
3614  break;
3615 
3616  /*
3617  * The user issued COMMIT when not inside a transaction. Issue a
3618  * WARNING, staying in TBLOCK_STARTED state. The upcoming call to
3619  * CommitTransactionCommand() will then close the transaction and
3620  * put us back into the default state.
3621  */
3622  case TBLOCK_STARTED:
3623  ereport(WARNING,
3624  (errcode(ERRCODE_NO_ACTIVE_SQL_TRANSACTION),
3625  errmsg("there is no transaction in progress")));
3626  result = true;
3627  break;
3628 
3629  /*
3630  * The user issued a COMMIT that somehow ran inside a parallel
3631  * worker. We can't cope with that.
3632  */
3634  ereport(FATAL,
3635  (errcode(ERRCODE_INVALID_TRANSACTION_STATE),
3636  errmsg("cannot commit during a parallel operation")));
3637  break;
3638 
3639  /* These cases are invalid. */
3640  case TBLOCK_DEFAULT:
3641  case TBLOCK_BEGIN:
3642  case TBLOCK_SUBBEGIN:
3643  case TBLOCK_END:
3644  case TBLOCK_SUBRELEASE:
3645  case TBLOCK_SUBCOMMIT:
3646  case TBLOCK_ABORT_END:
3647  case TBLOCK_SUBABORT_END:
3648  case TBLOCK_ABORT_PENDING:
3650  case TBLOCK_SUBRESTART:
3652  case TBLOCK_PREPARE:
3653  elog(FATAL, "EndTransactionBlock: unexpected state %s",
3655  break;
3656  }
3657 
3658  return result;
3659 }
static TransactionState CurrentTransactionState
Definition: xact.c:232
int errcode(int sqlerrcode)
Definition: elog.c:575
TBlockState blockState
Definition: xact.c:177
#define FATAL
Definition: elog.h:52
struct TransactionStateData * parent
Definition: xact.c:191
static const char * BlockStateAsString(TBlockState blockState)
Definition: xact.c:5125
#define ereport(elevel, rest)
Definition: elog.h:122
#define WARNING
Definition: elog.h:40
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define elog
Definition: elog.h:219

◆ EnterParallelMode()

void EnterParallelMode ( void  )

Definition at line 872 of file xact.c.

References Assert, CurrentTransactionState, and TransactionStateData::parallelModeLevel.

Referenced by _bt_begin_parallel(), CommitTransaction(), ExecutePlan(), and ParallelWorkerMain().

873 {
875 
876  Assert(s->parallelModeLevel >= 0);
877 
878  ++s->parallelModeLevel;
879 }
static TransactionState CurrentTransactionState
Definition: xact.c:232
int parallelModeLevel
Definition: xact.c:190
#define Assert(condition)
Definition: c.h:699

◆ EstimateTransactionStateSpace()

Size EstimateTransactionStateSpace ( void  )

Definition at line 4938 of file xact.c.

References add_size(), mul_size(), TransactionStateData::nChildXids, nParallelCurrentXids, TransactionStateData::parent, TransactionStateData::transactionId, and TransactionIdIsValid.

Referenced by InitializeParallelDSM().

4939 {
4940  TransactionState s;
4941  Size nxids = 6; /* iso level, deferrable, top & current XID,
4942  * command counter, XID count */
4943 
4944  for (s = CurrentTransactionState; s != NULL; s = s->parent)
4945  {
4947  nxids = add_size(nxids, 1);
4948  nxids = add_size(nxids, s->nChildXids);
4949  }
4950 
4951  nxids = add_size(nxids, nParallelCurrentXids);
4952  return mul_size(nxids, sizeof(TransactionId));
4953 }
static TransactionState CurrentTransactionState
Definition: xact.c:232
uint32 TransactionId
Definition: c.h:474
int nParallelCurrentXids
Definition: xact.c:107
struct TransactionStateData * parent
Definition: xact.c:191
Size mul_size(Size s1, Size s2)
Definition: shmem.c:492
Size add_size(Size s1, Size s2)
Definition: shmem.c:475
TransactionId transactionId
Definition: xact.c:172
size_t Size
Definition: c.h:433
#define TransactionIdIsValid(xid)
Definition: transam.h:41

◆ ExitParallelMode()

void ExitParallelMode ( void  )

Definition at line 885 of file xact.c.

References Assert, CurrentTransactionState, ParallelContextActive(), and TransactionStateData::parallelModeLevel.

Referenced by _bt_end_parallel(), ExecutePlan(), and ParallelWorkerMain().

886 {
888 
889  Assert(s->parallelModeLevel > 0);
891 
892  --s->parallelModeLevel;
893 }
static TransactionState CurrentTransactionState
Definition: xact.c:232
bool ParallelContextActive(void)
Definition: parallel.c:936
int parallelModeLevel
Definition: xact.c:190
#define Assert(condition)
Definition: c.h:699

◆ ForceSyncCommit()

void ForceSyncCommit ( void  )

Definition at line 962 of file xact.c.

References forceSyncCommit.

Referenced by createdb(), CreateTableSpace(), dropdb(), DropTableSpace(), and movedb().

963 {
964  forceSyncCommit = true;
965 }
static bool forceSyncCommit
Definition: xact.c:262

◆ GetCurrentCommandId()

CommandId GetCurrentCommandId ( bool  used)

Definition at line 679 of file xact.c.

References Assert, currentCommandId, currentCommandIdUsed, and IsParallelWorker.

Referenced by ATRewriteTable(), CopyFrom(), create_estate_for_relation(), GetSnapshotData(), intorel_startup(), pgrowlocks(), RegisterRelcacheInvalidation(), RelationFindReplTupleByIndex(), RelationFindReplTupleSeq(), simple_heap_delete(), simple_heap_insert(), simple_heap_update(), standard_ExecutorStart(), toast_save_datum(), transientrel_startup(), and UpdateActiveSnapshotCommandId().

680 {
681  /* this is global to a transaction, not subtransaction-local */
682  if (used)
683  {
684  /*
685  * Forbid setting currentCommandIdUsed in a parallel worker, because
686  * we have no provision for communicating this back to the master. We
687  * could relax this restriction when currentCommandIdUsed was already
688  * true at the start of the parallel operation.
689  */
691  currentCommandIdUsed = true;
692  }
693  return currentCommandId;
694 }
#define IsParallelWorker()
Definition: parallel.h:60
#define Assert(condition)
Definition: c.h:699
static CommandId currentCommandId
Definition: xact.c:239
static bool currentCommandIdUsed
Definition: xact.c:240

◆ GetCurrentStatementStartTimestamp()

TimestampTz GetCurrentStatementStartTimestamp ( void  )

Definition at line 709 of file xact.c.

References stmtStartTimestamp.

Referenced by check_log_duration(), CreatePortal(), pgstat_report_activity(), statement_timestamp(), and StorePreparedStatement().

710 {
711  return stmtStartTimestamp;
712 }
static TimestampTz stmtStartTimestamp
Definition: xact.c:250

◆ GetCurrentSubTransactionId()

◆ GetCurrentTransactionId()

◆ GetCurrentTransactionIdIfAny()

TransactionId GetCurrentTransactionIdIfAny ( void  )

Definition at line 434 of file xact.c.

References TransactionStateData::transactionId.

Referenced by RecordTransactionAbort(), ReorderBufferCommit(), and XLogRecordAssemble().

435 {
437 }
static TransactionState CurrentTransactionState
Definition: xact.c:232
TransactionId transactionId
Definition: xact.c:172

◆ GetCurrentTransactionNestLevel()

◆ GetCurrentTransactionStartTimestamp()

TimestampTz GetCurrentTransactionStartTimestamp ( void  )

◆ GetCurrentTransactionStopTimestamp()

TimestampTz GetCurrentTransactionStopTimestamp ( void  )

Definition at line 721 of file xact.c.

References GetCurrentTimestamp(), and xactStopTimestamp.

Referenced by pgstat_report_stat().

722 {
723  if (xactStopTimestamp != 0)
724  return xactStopTimestamp;
725  return GetCurrentTimestamp();
726 }
static TimestampTz xactStopTimestamp
Definition: xact.c:251
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1570

◆ GetStableLatestTransactionId()

TransactionId GetStableLatestTransactionId ( void  )

Definition at line 461 of file xact.c.

References Assert, GetTopTransactionIdIfAny(), InvalidLocalTransactionId, InvalidTransactionId, PGPROC::lxid, MyProc, ReadNewTransactionId(), and TransactionIdIsValid.

Referenced by xid_age().

462 {
464  static TransactionId stablexid = InvalidTransactionId;
465 
466  if (lxid != MyProc->lxid)
467  {
468  lxid = MyProc->lxid;
469  stablexid = GetTopTransactionIdIfAny();
470  if (!TransactionIdIsValid(stablexid))
471  stablexid = ReadNewTransactionId();
472  }
473 
474  Assert(TransactionIdIsValid(stablexid));
475 
476  return stablexid;
477 }
uint32 TransactionId
Definition: c.h:474
PGPROC * MyProc
Definition: proc.c:67
#define InvalidTransactionId
Definition: transam.h:31
TransactionId ReadNewTransactionId(void)
Definition: varsup.c:250
uint32 LocalTransactionId
Definition: c.h:476
TransactionId GetTopTransactionIdIfAny(void)
Definition: xact.c:404
#define Assert(condition)
Definition: c.h:699
#define InvalidLocalTransactionId
Definition: lock.h:69
#define TransactionIdIsValid(xid)
Definition: transam.h:41
LocalTransactionId lxid
Definition: proc.h:106

◆ GetTopTransactionId()

TransactionId GetTopTransactionId ( void  )

Definition at line 389 of file xact.c.

References AssignTransactionId(), TransactionIdIsValid, and XactTopTransactionId.

Referenced by AlterSequence(), AssignTransactionId(), do_setval(), fill_seq_with_data(), log_heap_new_cid(), nextval_internal(), and txid_current().

390 {
393  return XactTopTransactionId;
394 }
TransactionId XactTopTransactionId
Definition: xact.c:106
static TransactionStateData TopTransactionStateData
Definition: xact.c:201
#define TransactionIdIsValid(xid)
Definition: transam.h:41
static void AssignTransactionId(TransactionState s)
Definition: xact.c:489

◆ GetTopTransactionIdIfAny()

◆ IsAbortedTransactionBlockState()

◆ IsInParallelMode()

◆ IsInTransactionBlock()

bool IsInTransactionBlock ( bool  isTopLevel)

Definition at line 3267 of file xact.c.

References TransactionStateData::blockState, IsSubTransaction(), IsTransactionBlock(), TBLOCK_DEFAULT, and TBLOCK_STARTED.

Referenced by vacuum().

3268 {
3269  /*
3270  * Return true on same conditions that would make
3271  * PreventInTransactionBlock error out
3272  */
3273  if (IsTransactionBlock())
3274  return true;
3275 
3276  if (IsSubTransaction())
3277  return true;
3278 
3279  if (!isTopLevel)
3280  return true;
3281 
3284  return true;
3285 
3286  return false;
3287 }
static TransactionState CurrentTransactionState
Definition: xact.c:232
TBlockState blockState
Definition: xact.c:177
bool IsTransactionBlock(void)
Definition: xact.c:4422
bool IsSubTransaction(void)
Definition: xact.c:4495

◆ IsSubTransaction()

◆ IsTransactionBlock()

bool IsTransactionBlock ( void  )

Definition at line 4422 of file xact.c.

References TransactionStateData::blockState, CurrentTransactionState, TBLOCK_DEFAULT, and TBLOCK_STARTED.

Referenced by CheckTransactionBlock(), CreateReplicationSlot(), exec_replication_command(), IsInTransactionBlock(), PreventInTransactionBlock(), and standard_ProcessUtility().

4423 {
4425 
4427  return false;
4428 
4429  return true;
4430 }
static TransactionState CurrentTransactionState
Definition: xact.c:232
TBlockState blockState
Definition: xact.c:177

◆ IsTransactionOrTransactionBlock()

bool IsTransactionOrTransactionBlock ( void  )

◆ IsTransactionState()

bool IsTransactionState ( void  )

Definition at line 350 of file xact.c.

References CurrentTransactionState, TransactionStateData::state, and TRANS_INPROGRESS.

Referenced by apply_handle_commit(), apply_handle_origin(), check_client_encoding(), check_default_tablespace(), check_role(), check_session_authorization(), check_temp_tablespaces(), check_transaction_read_only(), check_TSCurrentConfig(), check_XactIsoLevel(), CreateInitDecodingContext(), ensure_transaction(), GetMessageEncoding(), LogLogicalMessage(), maybe_reread_subscription(), pg_attribute_noreturn(), pg_do_encoding_conversion(), PrepareClientEncoding(), PrepareTempTablespaces(), process_syncing_tables_for_apply(), process_syncing_tables_for_sync(), RelationClearRelation(), RelationIdGetRelation(), RelationInitPhysicalAddr(), replorigin_create(), replorigin_drop(), SearchCatCacheInternal(), SetMultiXactIdLimit(), SetTransactionIdLimit(), SnapBuildClearExportedSnapshot(), and SocketBackend().

351 {
353 
354  /*
355  * TRANS_DEFAULT and TRANS_ABORT are obviously unsafe states. However, we
356  * also reject the startup/shutdown states TRANS_START, TRANS_COMMIT,
357  * TRANS_PREPARE since it might be too soon or too late within those
358  * transition states to do anything interesting. Hence, the only "valid"
359  * state is TRANS_INPROGRESS.
360  */
361  return (s->state == TRANS_INPROGRESS);
362 }
static TransactionState CurrentTransactionState
Definition: xact.c:232
TransState state
Definition: xact.c:176

◆ MarkCurrentTransactionIdLoggedIfAny()

void MarkCurrentTransactionIdLoggedIfAny ( void  )

Definition at line 445 of file xact.c.

References TransactionStateData::didLogXid, TransactionStateData::transactionId, and TransactionIdIsValid.

Referenced by XLogInsertRecord().

446 {
449 }
static TransactionState CurrentTransactionState
Definition: xact.c:232
TransactionId transactionId
Definition: xact.c:172
#define TransactionIdIsValid(xid)
Definition: transam.h:41

◆ PopTransaction()

static void PopTransaction ( void  )
static

Definition at line 4904 of file xact.c.

References CurrentResourceOwner, CurrentTransactionState, CurTransactionContext, TransactionStateData::curTransactionContext, TransactionStateData::curTransactionOwner, CurTransactionResourceOwner, elog, FATAL, MemoryContextSwitchTo(), TransactionStateData::name, TransactionStateData::parent, pfree(), TransactionStateData::state, TRANS_DEFAULT, TransStateAsString(), and WARNING.

Referenced by CleanupSubTransaction(), and CommitSubTransaction().

4905 {
4907 
4908  if (s->state != TRANS_DEFAULT)
4909  elog(WARNING, "PopTransaction while in %s state",
4911 
4912  if (s->parent == NULL)
4913  elog(FATAL, "PopTransaction with no parent");
4914 
4916 
4917  /* Let's just make sure CurTransactionContext is good */
4920 
4921  /* Ditto for ResourceOwner links */
4924 
4925  /* Free the old child structure */
4926  if (s->name)
4927  pfree(s->name);
4928  pfree(s);
4929 }
static TransactionState CurrentTransactionState
Definition: xact.c:232
ResourceOwner CurTransactionResourceOwner
Definition: resowner.c:141
ResourceOwner CurrentResourceOwner
Definition: resowner.c:140
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
MemoryContext CurTransactionContext
Definition: mcxt.c:50
TransState state
Definition: xact.c:176
ResourceOwner curTransactionOwner
Definition: xact.c:181
void pfree(void *pointer)
Definition: mcxt.c:1031
#define FATAL
Definition: elog.h:52
struct TransactionStateData * parent
Definition: xact.c:191
MemoryContext curTransactionContext
Definition: xact.c:180
#define WARNING
Definition: elog.h:40
static const char * TransStateAsString(TransState state)
Definition: xact.c:5178
#define elog
Definition: elog.h:219

◆ PrepareTransaction()

static void PrepareTransaction ( void  )
static

Definition at line 2169 of file xact.c.

References AfterTriggerEndXact(), AfterTriggerFireDeferred(), Assert, AtCommit_Memory(), AtEOXact_Buffers(), AtEOXact_ComboCid(), AtEOXact_Files(), AtEOXact_GUC(), AtEOXact_HashTables(), AtEOXact_LargeObject(), AtEOXact_Namespace(), AtEOXact_on_commit_actions(), AtEOXact_RelationCache(), AtEOXact_SMgr(), AtEOXact_Snapshot(), AtEOXact_SPI(), AtPrepare_Locks(), AtPrepare_MultiXact(), AtPrepare_Notify(), AtPrepare_PgStat(), AtPrepare_PredicateLocks(), AtPrepare_RelationMap(), BufmgrCommit(), CallXactCallbacks(), TransactionStateData::childXids, CurrentResourceOwner, CurrentTransactionState, TransactionStateData::curTransactionOwner, CurTransactionResourceOwner, elog, EndPrepare(), ereport, errcode(), errmsg(), ERROR, GetCurrentTimestamp(), GetCurrentTransactionId(), GetUserId(), TransactionStateData::gucNestLevel, HOLD_INTERRUPTS, InvalidSubTransactionId, InvalidTransactionId, IsInParallelMode(), MarkAsPreparing(), TransactionStateData::maxChildXids, MyDatabaseId, MyProc, MyXactFlags, TransactionStateData::nChildXids, TransactionStateData::nestingLevel, nParallelCurrentXids, TransactionStateData::parent, pgstat_report_xact_timestamp(), PostPrepare_Inval(), PostPrepare_Locks(), PostPrepare_MultiXact(), PostPrepare_PgStat(), PostPrepare_PredicateLocks(), PostPrepare_smgr(), PostPrepare_Twophase(), PreCommit_CheckForSerializationFailure(), PreCommit_on_commit_actions(), PreCommit_Portals(), prepareGID, ProcArrayClearTransaction(), RESOURCE_RELEASE_AFTER_LOCKS, RESOURCE_RELEASE_BEFORE_LOCKS, RESOURCE_RELEASE_LOCKS, ResourceOwnerDelete(), ResourceOwnerRelease(), RESUME_INTERRUPTS, ShowTransactionState(), StartPrepare(), TransactionStateData::state, TransactionStateData::subTransactionId, TopTransactionResourceOwner, TRANS_DEFAULT, TRANS_INPROGRESS, TRANS_PREPARE, TransactionStateData::transactionId, TransStateAsString(), WARNING, XACT_EVENT_PRE_PREPARE, XACT_EVENT_PREPARE, XACT_FLAGS_ACCESSEDTEMPREL, XactHasExportedSnapshots(), XactLastRecEnd, XactManipulatesLogicalReplicationWorkers(), and XactTopTransactionId.

Referenced by CommitTransactionCommand().

2170 {
2173  GlobalTransaction gxact;
2174  TimestampTz prepared_at;
2175 
2177 
2178  ShowTransactionState("PrepareTransaction");
2179 
2180  /*
2181  * check the current transaction state
2182  */
2183  if (s->state != TRANS_INPROGRESS)
2184  elog(WARNING, "PrepareTransaction while in %s state",
2186  Assert(s->parent == NULL);
2187 
2188  /*
2189  * Do pre-commit processing that involves calling user-defined code, such
2190  * as triggers. Since closing cursors could queue trigger actions,
2191  * triggers could open cursors, etc, we have to keep looping until there's
2192  * nothing left to do.
2193  */
2194  for (;;)
2195  {
2196  /*
2197  * Fire all currently pending deferred triggers.
2198  */
2200 
2201  /*
2202  * Close open portals (converting holdable ones into static portals).
2203  * If there weren't any, we are done ... otherwise loop back to check
2204  * if they queued deferred triggers. Lather, rinse, repeat.
2205  */
2206  if (!PreCommit_Portals(true))
2207  break;
2208  }
2209 
2211 
2212  /*
2213  * The remaining actions cannot call any user-defined code, so it's safe
2214  * to start shutting down within-transaction services. But note that most
2215  * of this stuff could still throw an error, which would switch us into
2216  * the transaction-abort path.
2217  */
2218 
2219  /* Shut down the deferred-trigger manager */
2220  AfterTriggerEndXact(true);
2221 
2222  /*
2223  * Let ON COMMIT management do its thing (must happen after closing
2224  * cursors, to avoid dangling-reference problems)
2225  */
2227 
2228  /* close large objects before lower-level cleanup */
2229  AtEOXact_LargeObject(true);
2230 
2231  /*
2232  * Mark serializable transaction as complete for predicate locking
2233  * purposes. This should be done as late as we can put it and still allow
2234  * errors to be raised for failure patterns found at commit.
2235  */
2237 
2238  /* NOTIFY will be handled below */
2239 
2240  /*
2241  * Don't allow PREPARE TRANSACTION if we've accessed a temporary table in
2242  * this transaction. Having the prepared xact hold locks on another
2243  * backend's temp table seems a bad idea --- for instance it would prevent
2244  * the backend from exiting. There are other problems too, such as how to
2245  * clean up the source backend's local buffers and ON COMMIT state if the
2246  * prepared xact includes a DROP of a temp table.
2247  *
2248  * We must check this after executing any ON COMMIT actions, because they
2249  * might still access a temp relation.
2250  *
2251  * XXX In principle this could be relaxed to allow some useful special
2252  * cases, such as a temp table created and dropped all within the
2253  * transaction. That seems to require much more bookkeeping though.
2254  */
2256  ereport(ERROR,
2257  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2258  errmsg("cannot PREPARE a transaction that has operated on temporary tables")));
2259 
2260  /*
2261  * Likewise, don't allow PREPARE after pg_export_snapshot. This could be
2262  * supported if we added cleanup logic to twophase.c, but for now it
2263  * doesn't seem worth the trouble.
2264  */
2266  ereport(ERROR,
2267  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2268  errmsg("cannot PREPARE a transaction that has exported snapshots")));
2269 
2270  /*
2271  * Don't allow PREPARE but for transaction that has/might kill logical
2272  * replication workers.
2273  */
2275  ereport(ERROR,
2276  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2277  errmsg("cannot PREPARE a transaction that has manipulated logical replication workers")));
2278 
2279  /* Prevent cancel/die interrupt while cleaning up */
2280  HOLD_INTERRUPTS();
2281 
2282  /*
2283  * set the current transaction state information appropriately during
2284  * prepare processing
2285  */
2286  s->state = TRANS_PREPARE;
2287 
2288  prepared_at = GetCurrentTimestamp();
2289 
2290  /* Tell bufmgr and smgr to prepare for commit */
2291  BufmgrCommit();
2292 
2293  /*
2294  * Reserve the GID for this transaction. This could fail if the requested
2295  * GID is invalid or already in use.
2296  */
2297  gxact = MarkAsPreparing(xid, prepareGID, prepared_at,
2298  GetUserId(), MyDatabaseId);
2299  prepareGID = NULL;
2300 
2301  /*
2302