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/xlogrecovery.h"
#include "access/xlogutils.h"
#include "catalog/index.h"
#include "catalog/namespace.h"
#include "catalog/pg_enum.h"
#include "catalog/storage.h"
#include "commands/async.h"
#include "commands/tablecmds.h"
#include "commands/trigger.h"
#include "common/pg_prng.h"
#include "executor/spi.h"
#include "libpq/be-fsstubs.h"
#include "libpq/pqsignal.h"
#include "miscadmin.h"
#include "pg_trace.h"
#include "pgstat.h"
#include "replication/logical.h"
#include "replication/logicallauncher.h"
#include "replication/logicalworker.h"
#include "replication/origin.h"
#include "replication/snapbuild.h"
#include "replication/syncrep.h"
#include "replication/walsender.h"
#include "storage/condition_variable.h"
#include "storage/fd.h"
#include "storage/lmgr.h"
#include "storage/md.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 dependency graph for xact.c:

Go to the source code of this file.

Data Structures

struct  TransactionStateData
 
struct  SerializedTransactionState
 
struct  XactCallbackItem
 
struct  SubXactCallbackItem
 

Macros

#define SerializedTransactionStateHeaderSize    offsetof(SerializedTransactionState, parallelCurrentXids)
 

Typedefs

typedef enum TransState TransState
 
typedef enum TBlockState TBlockState
 
typedef struct TransactionStateData TransactionStateData
 
typedef TransactionStateDataTransactionState
 
typedef struct SerializedTransactionState SerializedTransactionState
 
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 s)
 
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)
 
FullTransactionId GetTopFullTransactionId (void)
 
FullTransactionId GetTopFullTransactionIdIfAny (void)
 
FullTransactionId GetCurrentFullTransactionId (void)
 
FullTransactionId GetCurrentFullTransactionIdIfAny (void)
 
void MarkCurrentTransactionIdLoggedIfAny (void)
 
bool IsSubxactTopXidLogPending (void)
 
void MarkSubxactTopXidLogged (void)
 
TransactionId GetStableLatestTransactionId (void)
 
SubTransactionId GetCurrentSubTransactionId (void)
 
bool SubTransactionIsActive (SubTransactionId subxid)
 
CommandId GetCurrentCommandId (bool used)
 
void SetParallelStartTimestamps (TimestampTz xact_ts, TimestampTz stmt_ts)
 
TimestampTz GetCurrentTransactionStartTimestamp (void)
 
TimestampTz GetCurrentStatementStartTimestamp (void)
 
TimestampTz GetCurrentTransactionStopTimestamp (void)
 
void SetCurrentStatementStartTimestamp (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 SaveTransactionCharacteristics (SavedTransactionCharacteristics *s)
 
void RestoreTransactionCharacteristics (const SavedTransactionCharacteristics *s)
 
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 (bool chain)
 
void UserAbortTransactionBlock (bool chain)
 
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, RelFileLocator *rels, int ndroppedstats, xl_xact_stats_item *droppedstats, int nmsgs, SharedInvalidationMessage *msgs, bool relcacheInval, int xactflags, TransactionId twophase_xid, const char *twophase_gid)
 
XLogRecPtr XactLogAbortRecord (TimestampTz abort_time, int nsubxacts, TransactionId *subxacts, int nrels, RelFileLocator *rels, int ndroppedstats, xl_xact_stats_item *droppedstats, 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, XLogRecPtr lsn, RepOriginId origin_id)
 
void xact_redo (XLogReaderState *record)
 

Variables

int DefaultXactIsoLevel = XACT_READ_COMMITTED
 
int XactIsoLevel = XACT_READ_COMMITTED
 
bool DefaultXactReadOnly = false
 
bool XactReadOnly
 
bool DefaultXactDeferrable = false
 
bool XactDeferrable
 
int synchronous_commit = SYNCHRONOUS_COMMIT_ON
 
TransactionId CheckXidAlive = InvalidTransactionId
 
bool bsysscan = false
 
static FullTransactionId XactTopFullTransactionId = {InvalidTransactionId}
 
static int nParallelCurrentXids = 0
 
static 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
 
bool xact_is_sampled = false
 
static MemoryContext TransactionAbortContext = NULL
 
static XactCallbackItemXact_callbacks = NULL
 
static SubXactCallbackItemSubXact_callbacks = NULL
 

Macro Definition Documentation

◆ SerializedTransactionStateHeaderSize

#define SerializedTransactionStateHeaderSize    offsetof(SerializedTransactionState, parallelCurrentXids)

Definition at line 233 of file xact.c.

Typedef Documentation

◆ SerializedTransactionState

◆ SubXactCallbackItem

◆ TBlockState

typedef enum TBlockState TBlockState

◆ TransactionState

Definition at line 215 of file xact.c.

◆ TransactionStateData

◆ TransState

typedef enum TransState 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 157 of file xact.c.

158 {
159  /* not-in-transaction-block states */
160  TBLOCK_DEFAULT, /* idle */
161  TBLOCK_STARTED, /* running single-query transaction */
162 
163  /* transaction block states */
164  TBLOCK_BEGIN, /* starting transaction block */
165  TBLOCK_INPROGRESS, /* live transaction */
166  TBLOCK_IMPLICIT_INPROGRESS, /* live transaction after implicit BEGIN */
167  TBLOCK_PARALLEL_INPROGRESS, /* live transaction inside parallel worker */
168  TBLOCK_END, /* COMMIT received */
169  TBLOCK_ABORT, /* failed xact, awaiting ROLLBACK */
170  TBLOCK_ABORT_END, /* failed xact, ROLLBACK received */
171  TBLOCK_ABORT_PENDING, /* live xact, ROLLBACK received */
172  TBLOCK_PREPARE, /* live xact, PREPARE received */
173 
174  /* subtransaction states */
175  TBLOCK_SUBBEGIN, /* starting a subtransaction */
176  TBLOCK_SUBINPROGRESS, /* live subtransaction */
177  TBLOCK_SUBRELEASE, /* RELEASE received */
178  TBLOCK_SUBCOMMIT, /* COMMIT received while TBLOCK_SUBINPROGRESS */
179  TBLOCK_SUBABORT, /* failed subxact, awaiting ROLLBACK */
180  TBLOCK_SUBABORT_END, /* failed subxact, ROLLBACK received */
181  TBLOCK_SUBABORT_PENDING, /* live subxact, ROLLBACK received */
182  TBLOCK_SUBRESTART, /* live subxact, ROLLBACK TO received */
183  TBLOCK_SUBABORT_RESTART, /* failed subxact, ROLLBACK TO received */
184 } TBlockState;
TBlockState
Definition: xact.c:158
@ TBLOCK_DEFAULT
Definition: xact.c:160
@ TBLOCK_SUBABORT_END
Definition: xact.c:180
@ TBLOCK_STARTED
Definition: xact.c:161
@ TBLOCK_SUBCOMMIT
Definition: xact.c:178
@ TBLOCK_IMPLICIT_INPROGRESS
Definition: xact.c:166
@ TBLOCK_ABORT_END
Definition: xact.c:170
@ TBLOCK_PREPARE
Definition: xact.c:172
@ TBLOCK_ABORT_PENDING
Definition: xact.c:171
@ TBLOCK_ABORT
Definition: xact.c:169
@ TBLOCK_SUBRELEASE
Definition: xact.c:177
@ TBLOCK_SUBBEGIN
Definition: xact.c:175
@ TBLOCK_SUBABORT
Definition: xact.c:179
@ TBLOCK_SUBRESTART
Definition: xact.c:182
@ TBLOCK_INPROGRESS
Definition: xact.c:165
@ TBLOCK_END
Definition: xact.c:168
@ TBLOCK_PARALLEL_INPROGRESS
Definition: xact.c:167
@ TBLOCK_SUBABORT_RESTART
Definition: xact.c:183
@ TBLOCK_SUBABORT_PENDING
Definition: xact.c:181
@ TBLOCK_BEGIN
Definition: xact.c:164
@ TBLOCK_SUBINPROGRESS
Definition: xact.c:176

◆ TransState

enum TransState
Enumerator
TRANS_DEFAULT 
TRANS_START 
TRANS_INPROGRESS 
TRANS_COMMIT 
TRANS_ABORT 
TRANS_PREPARE 

Definition at line 141 of file xact.c.

142 {
143  TRANS_DEFAULT, /* idle */
144  TRANS_START, /* transaction starting */
145  TRANS_INPROGRESS, /* inside a valid transaction */
146  TRANS_COMMIT, /* commit in progress */
147  TRANS_ABORT, /* abort in progress */
148  TRANS_PREPARE, /* prepare in progress */
149 } TransState;
TransState
Definition: xact.c:142
@ TRANS_INPROGRESS
Definition: xact.c:145
@ TRANS_START
Definition: xact.c:144
@ TRANS_COMMIT
Definition: xact.c:146
@ TRANS_ABORT
Definition: xact.c:147
@ TRANS_DEFAULT
Definition: xact.c:143
@ TRANS_PREPARE
Definition: xact.c:148

Function Documentation

◆ AbortCurrentTransaction()

void AbortCurrentTransaction ( void  )

Definition at line 3322 of file xact.c.

3323 {
3325 
3326  switch (s->blockState)
3327  {
3328  case TBLOCK_DEFAULT:
3329  if (s->state == TRANS_DEFAULT)
3330  {
3331  /* we are idle, so nothing to do */
3332  }
3333  else
3334  {
3335  /*
3336  * We can get here after an error during transaction start
3337  * (state will be TRANS_START). Need to clean up the
3338  * incompletely started transaction. First, adjust the
3339  * low-level state to suppress warning message from
3340  * AbortTransaction.
3341  */
3342  if (s->state == TRANS_START)
3343  s->state = TRANS_INPROGRESS;
3344  AbortTransaction();
3346  }
3347  break;
3348 
3349  /*
3350  * If we aren't in a transaction block, we just do the basic abort
3351  * & cleanup transaction. For this purpose, we treat an implicit
3352  * transaction block as if it were a simple statement.
3353  */
3354  case TBLOCK_STARTED:
3356  AbortTransaction();
3359  break;
3360 
3361  /*
3362  * If we are in TBLOCK_BEGIN it means something screwed up right
3363  * after reading "BEGIN TRANSACTION". We assume that the user
3364  * will interpret the error as meaning the BEGIN failed to get him
3365  * into a transaction block, so we should abort and return to idle
3366  * state.
3367  */
3368  case TBLOCK_BEGIN:
3369  AbortTransaction();
3372  break;
3373 
3374  /*
3375  * We are somewhere in a transaction block and we've gotten a
3376  * failure, so we abort the transaction and set up the persistent
3377  * ABORT state. We will stay in ABORT until we get a ROLLBACK.
3378  */
3379  case TBLOCK_INPROGRESS:
3381  AbortTransaction();
3382  s->blockState = TBLOCK_ABORT;
3383  /* CleanupTransaction happens when we exit TBLOCK_ABORT_END */
3384  break;
3385 
3386  /*
3387  * Here, we failed while trying to COMMIT. Clean up the
3388  * transaction and return to idle state (we do not want to stay in
3389  * the transaction).
3390  */
3391  case TBLOCK_END:
3392  AbortTransaction();
3395  break;
3396 
3397  /*
3398  * Here, we are already in an aborted transaction state and are
3399  * waiting for a ROLLBACK, but for some reason we failed again! So
3400  * we just remain in the abort state.
3401  */
3402  case TBLOCK_ABORT:
3403  case TBLOCK_SUBABORT:
3404  break;
3405 
3406  /*
3407  * We are in a failed transaction and we got the ROLLBACK command.
3408  * We have already aborted, we just need to cleanup and go to idle
3409  * state.
3410  */
3411  case TBLOCK_ABORT_END:
3414  break;
3415 
3416  /*
3417  * We are in a live transaction and we got a ROLLBACK command.
3418  * Abort, cleanup, go to idle state.
3419  */
3420  case TBLOCK_ABORT_PENDING:
3421  AbortTransaction();
3424  break;
3425 
3426  /*
3427  * Here, we failed while trying to PREPARE. Clean up the
3428  * transaction and return to idle state (we do not want to stay in
3429  * the transaction).
3430  */
3431  case TBLOCK_PREPARE:
3432  AbortTransaction();
3435  break;
3436 
3437  /*
3438  * We got an error inside a subtransaction. Abort just the
3439  * subtransaction, and go to the persistent SUBABORT state until
3440  * we get ROLLBACK.
3441  */
3442  case TBLOCK_SUBINPROGRESS:
3445  break;
3446 
3447  /*
3448  * If we failed while trying to create a subtransaction, clean up
3449  * the broken subtransaction and abort the parent. The same
3450  * applies if we get a failure while ending a subtransaction.
3451  */
3452  case TBLOCK_SUBBEGIN:
3453  case TBLOCK_SUBRELEASE:
3454  case TBLOCK_SUBCOMMIT:
3456  case TBLOCK_SUBRESTART:
3460  break;
3461 
3462  /*
3463  * Same as above, except the Abort() was already done.
3464  */
3465  case TBLOCK_SUBABORT_END:
3469  break;
3470  }
3471 }
TransState state
Definition: xact.c:195
TBlockState blockState
Definition: xact.c:196
static void CleanupSubTransaction(void)
Definition: xact.c:5247
static void CleanupTransaction(void)
Definition: xact.c:2905
static void AbortSubTransaction(void)
Definition: xact.c:5075
static void AbortTransaction(void)
Definition: xact.c:2710
static TransactionState CurrentTransactionState
Definition: xact.c:254
void AbortCurrentTransaction(void)
Definition: xact.c:3322

References 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 _SPI_commit(), _SPI_rollback(), AutoVacLauncherMain(), pa_stream_abort(), PostgresMain(), ReorderBufferImmediateInvalidation(), ReorderBufferProcessTXN(), and SnapBuildClearExportedSnapshot().

◆ AbortOutOfAnyTransaction()

void AbortOutOfAnyTransaction ( void  )

Definition at line 4729 of file xact.c.

4730 {
4732 
4733  /* Ensure we're not running in a doomed memory context */
4734  AtAbort_Memory();
4735 
4736  /*
4737  * Get out of any transaction or nested transaction
4738  */
4739  do
4740  {
4741  switch (s->blockState)
4742  {
4743  case TBLOCK_DEFAULT:
4744  if (s->state == TRANS_DEFAULT)
4745  {
4746  /* Not in a transaction, do nothing */
4747  }
4748  else
4749  {
4750  /*
4751  * We can get here after an error during transaction start
4752  * (state will be TRANS_START). Need to clean up the
4753  * incompletely started transaction. First, adjust the
4754  * low-level state to suppress warning message from
4755  * AbortTransaction.
4756  */
4757  if (s->state == TRANS_START)
4758  s->state = TRANS_INPROGRESS;
4759  AbortTransaction();
4761  }
4762  break;
4763  case TBLOCK_STARTED:
4764  case TBLOCK_BEGIN:
4765  case TBLOCK_INPROGRESS:
4768  case TBLOCK_END:
4769  case TBLOCK_ABORT_PENDING:
4770  case TBLOCK_PREPARE:
4771  /* In a transaction, so clean up */
4772  AbortTransaction();
4775  break;
4776  case TBLOCK_ABORT:
4777  case TBLOCK_ABORT_END:
4778 
4779  /*
4780  * AbortTransaction is already done, still need Cleanup.
4781  * However, if we failed partway through running ROLLBACK,
4782  * there will be an active portal running that command, which
4783  * we need to shut down before doing CleanupTransaction.
4784  */
4785  AtAbort_Portals();
4788  break;
4789 
4790  /*
4791  * In a subtransaction, so clean it up and abort parent too
4792  */
4793  case TBLOCK_SUBBEGIN:
4794  case TBLOCK_SUBINPROGRESS:
4795  case TBLOCK_SUBRELEASE:
4796  case TBLOCK_SUBCOMMIT:
4798  case TBLOCK_SUBRESTART:
4801  s = CurrentTransactionState; /* changed by pop */
4802  break;
4803 
4804  case TBLOCK_SUBABORT:
4805  case TBLOCK_SUBABORT_END:
4807  /* As above, but AbortSubTransaction already done */
4808  if (s->curTransactionOwner)
4809  {
4810  /* As in TBLOCK_ABORT, might have a live portal to zap */
4815  }
4817  s = CurrentTransactionState; /* changed by pop */
4818  break;
4819  }
4820  } while (s->blockState != TBLOCK_DEFAULT);
4821 
4822  /* Should be out of all subxacts now */
4823  Assert(s->parent == NULL);
4824 
4825  /* If we didn't actually have anything to do, revert to TopMemoryContext */
4826  AtCleanup_Memory();
4827 }
Assert(fmt[strlen(fmt) - 1] !='\n')
void AtAbort_Portals(void)
Definition: portalmem.c:782
void AtSubAbort_Portals(SubTransactionId mySubid, SubTransactionId parentSubid, ResourceOwner myXactOwner, ResourceOwner parentXactOwner)
Definition: portalmem.c:980
SubTransactionId subTransactionId
Definition: xact.c:192
struct TransactionStateData * parent
Definition: xact.c:212
ResourceOwner curTransactionOwner
Definition: xact.c:200
static void AtCleanup_Memory(void)
Definition: xact.c:1922
static void AtAbort_Memory(void)
Definition: xact.c:1832

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 DisableSubscriptionAndExit(), do_autovacuum(), perform_work_item(), RemoveTempRelationsCallback(), ShutdownPostgres(), start_apply(), and start_table_sync().

◆ AbortSubTransaction()

static void AbortSubTransaction ( void  )
static

Definition at line 5075 of file xact.c.

5076 {
5078 
5079  /* Prevent cancel/die interrupt while cleaning up */
5080  HOLD_INTERRUPTS();
5081 
5082  /* Make sure we have a valid memory context and resource owner */
5085 
5086  /*
5087  * Release any LW locks we might be holding as quickly as possible.
5088  * (Regular locks, however, must be held till we finish aborting.)
5089  * Releasing LW locks is critical since we might try to grab them again
5090  * while cleaning up!
5091  *
5092  * FIXME This may be incorrect --- Are there some locks we should keep?
5093  * Buffer locks, for example? I don't think so but I'm not sure.
5094  */
5095  LWLockReleaseAll();
5096 
5099  UnlockBuffers();
5100 
5101  /* Reset WAL record construction state */
5103 
5104  /* Cancel condition variable sleep */
5106 
5107  /*
5108  * Also clean up any open wait for lock, since the lock manager will choke
5109  * if we try to wait for another lock before doing this.
5110  */
5111  LockErrorCleanup();
5112 
5113  /*
5114  * If any timeout events are still active, make sure the timeout interrupt
5115  * is scheduled. This covers possible loss of a timeout interrupt due to
5116  * longjmp'ing out of the SIGINT handler (see notes in handle_sig_alarm).
5117  * We delay this till after LockErrorCleanup so that we don't uselessly
5118  * reschedule lock or deadlock check timeouts.
5119  */
5121 
5122  /*
5123  * Re-enable signals, in case we got here by longjmp'ing out of a signal
5124  * handler. We do this fairly early in the sequence so that the timeout
5125  * infrastructure will be functional if needed while aborting.
5126  */
5127  sigprocmask(SIG_SETMASK, &UnBlockSig, NULL);
5128 
5129  /*
5130  * check the current transaction state
5131  */
5132  ShowTransactionState("AbortSubTransaction");
5133 
5134  if (s->state != TRANS_INPROGRESS)
5135  elog(WARNING, "AbortSubTransaction while in %s state",
5137 
5138  s->state = TRANS_ABORT;
5139 
5140  /*
5141  * Reset user ID which might have been changed transiently. (See notes in
5142  * AbortTransaction.)
5143  */
5145 
5146  /* Forget about any active REINDEX. */
5148 
5149  /* Reset logical streaming state. */
5151 
5152  /*
5153  * No need for SnapBuildResetExportedSnapshotState() here, snapshot
5154  * exports are not supported in subtransactions.
5155  */
5156 
5157  /* Exit from parallel mode, if necessary. */
5158  if (IsInParallelMode())
5159  {
5161  s->parallelModeLevel = 0;
5162  }
5163 
5164  /*
5165  * We can skip all this stuff if the subxact failed before creating a
5166  * ResourceOwner...
5167  */
5168  if (s->curTransactionOwner)
5169  {
5170  AfterTriggerEndSubXact(false);
5176  s->parent->subTransactionId);
5178 
5179  /* Advertise the fact that we aborted in pg_xact. */
5180  (void) RecordTransactionAbort(true);
5181 
5182  /* Post-abort cleanup */
5185 
5187  s->parent->subTransactionId);
5188 
5191  false, false);
5192 
5194  s->parent->subTransactionId);
5195 
5196 
5197  /*
5198  * AtEOSubXact_Inval sometimes needs to temporarily bump the refcount
5199  * on the relcache entries that it processes. We cannot use the
5200  * subtransaction's resource owner anymore, because we've already
5201  * started releasing it. But we can use the parent resource owner.
5202  */
5204 
5205  AtEOSubXact_Inval(false);
5206 
5208 
5211  false, false);
5214  false, false);
5215  AtSubAbort_smgr();
5216 
5217  AtEOXact_GUC(false, s->gucNestLevel);
5218  AtEOSubXact_SPI(false, s->subTransactionId);
5220  s->parent->subTransactionId);
5222  s->parent->subTransactionId);
5224  s->parent->subTransactionId);
5226  AtEOSubXact_PgStat(false, s->nestingLevel);
5228  }
5229 
5230  /*
5231  * Restore the upper transaction's read-only state, too. This should be
5232  * redundant with GUC's cleanup but we may as well do it for consistency
5233  * with the commit case.
5234  */
5236 
5238 }
void AtSubAbort_Notify(void)
Definition: async.c:1764
void AtEOSubXact_Parallel(bool isCommit, SubTransactionId mySubId)
Definition: parallel.c:1248
sigset_t UnBlockSig
Definition: pqsignal.c:22
void pgstat_progress_end_command(void)
void AtEOSubXact_LargeObject(bool isCommit, SubTransactionId mySubid, SubTransactionId parentSubid)
Definition: be-fsstubs.c:648
void UnlockBuffers(void)
Definition: bufmgr.c:4768
bool ConditionVariableCancelSleep(void)
void AtEOSubXact_HashTables(bool isCommit, int nestDepth)
Definition: dynahash.c:1904
#define WARNING
Definition: elog.h:36
#define elog(elevel,...)
Definition: elog.h:224
void AtEOSubXact_Files(bool isCommit, SubTransactionId mySubid, SubTransactionId parentSubid)
Definition: fd.c:3132
void AtEOXact_GUC(bool isCommit, int nestLevel)
Definition: guc.c:2245
void ResetReindexState(int nestLevel)
Definition: index.c:4170
void AtEOSubXact_Inval(bool isCommit)
Definition: inval.c:1083
void ResetLogicalStreamingState(void)
Definition: logical.c:1916
void LWLockReleaseAll(void)
Definition: lwlock.c:1883
#define RESUME_INTERRUPTS()
Definition: miscadmin.h:135
#define HOLD_INTERRUPTS()
Definition: miscadmin.h:133
void SetUserIdAndSecContext(Oid userid, int sec_context)
Definition: miscinit.c:643
void AtEOSubXact_Namespace(bool isCommit, SubTransactionId mySubid, SubTransactionId parentSubid)
Definition: namespace.c:4543
void AtEOSubXact_PgStat(bool isCommit, int nestDepth)
Definition: pgstat_xact.c:113
void AtEOSubXact_RelationCache(bool isCommit, SubTransactionId mySubid, SubTransactionId parentSubid)
Definition: relcache.c:3345
ResourceOwner CurrentResourceOwner
Definition: resowner.c:165
void ResourceOwnerRelease(ResourceOwner owner, ResourceReleasePhase phase, bool isCommit, bool isTopLevel)
Definition: resowner.c:648
@ RESOURCE_RELEASE_LOCKS
Definition: resowner.h:55
@ RESOURCE_RELEASE_BEFORE_LOCKS
Definition: resowner.h:54
@ RESOURCE_RELEASE_AFTER_LOCKS
Definition: resowner.h:56
void AtSubAbort_Snapshot(int level)
Definition: snapmgr.c:966
void AtEOSubXact_SPI(bool isCommit, SubTransactionId mySubid)
Definition: spi.c:483
void LockErrorCleanup(void)
Definition: proc.c:732
void AtSubAbort_smgr(void)
Definition: storage.c:934
int parallelModeLevel
Definition: xact.c:209
FullTransactionId fullTransactionId
Definition: xact.c:191
bool prevXactReadOnly
Definition: xact.c:206
void AtEOSubXact_on_commit_actions(bool isCommit, SubTransactionId mySubid, SubTransactionId parentSubid)
Definition: tablecmds.c:18070
void reschedule_timeouts(void)
Definition: timeout.c:540
#define FullTransactionIdIsValid(x)
Definition: transam.h:55
void AfterTriggerEndSubXact(bool isCommit)
Definition: trigger.c:5356
static void pgstat_report_wait_end(void)
Definition: wait_event.h:104
static void CallSubXactCallbacks(SubXactEvent event, SubTransactionId mySubid, SubTransactionId parentSubid)
Definition: xact.c:3761
static void AtSubAbort_Memory(void)
Definition: xact.c:1852
static const char * TransStateAsString(TransState state)
Definition: xact.c:5614
bool XactReadOnly
Definition: xact.c:82
static void AtSubAbort_childXids(void)
Definition: xact.c:1890
static void AtSubAbort_ResourceOwner(void)
Definition: xact.c:1877
static void ShowTransactionState(const char *str)
Definition: xact.c:5511
static TransactionId RecordTransactionAbort(bool isSubXact)
Definition: xact.c:1702
bool IsInParallelMode(void)
Definition: xact.c:1069
@ SUBXACT_EVENT_ABORT_SUB
Definition: xact.h:144
void XLogResetInsertion(void)
Definition: xloginsert.c:223

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(), AtSubAbort_childXids(), AtSubAbort_Memory(), AtSubAbort_Notify(), AtSubAbort_Portals(), AtSubAbort_ResourceOwner(), AtSubAbort_smgr(), AtSubAbort_Snapshot(), CallSubXactCallbacks(), ConditionVariableCancelSleep(), CurrentResourceOwner, CurrentTransactionState, TransactionStateData::curTransactionOwner, elog, TransactionStateData::fullTransactionId, FullTransactionIdIsValid, TransactionStateData::gucNestLevel, HOLD_INTERRUPTS, IsInParallelMode(), LockErrorCleanup(), LWLockReleaseAll(), TransactionStateData::nestingLevel, TransactionStateData::parallelModeLevel, TransactionStateData::parent, pgstat_progress_end_command(), pgstat_report_wait_end(), TransactionStateData::prevSecContext, TransactionStateData::prevUser, TransactionStateData::prevXactReadOnly, RecordTransactionAbort(), reschedule_timeouts(), ResetLogicalStreamingState(), ResetReindexState(), 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, TransStateAsString(), UnBlockSig, UnlockBuffers(), WARNING, XactReadOnly, and XLogResetInsertion().

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

◆ AbortTransaction()

static void AbortTransaction ( void  )
static

Definition at line 2710 of file xact.c.

2711 {
2713  TransactionId latestXid;
2714  bool is_parallel_worker;
2715 
2716  /* Prevent cancel/die interrupt while cleaning up */
2717  HOLD_INTERRUPTS();
2718 
2719  /* Disable transaction timeout */
2720  if (TransactionTimeout > 0)
2722 
2723  /* Make sure we have a valid memory context and resource owner */
2724  AtAbort_Memory();
2726 
2727  /*
2728  * Release any LW locks we might be holding as quickly as possible.
2729  * (Regular locks, however, must be held till we finish aborting.)
2730  * Releasing LW locks is critical since we might try to grab them again
2731  * while cleaning up!
2732  */
2733  LWLockReleaseAll();
2734 
2735  /* Clear wait information and command progress indicator */
2738 
2739  /* Clean up buffer context locks, too */
2740  UnlockBuffers();
2741 
2742  /* Reset WAL record construction state */
2744 
2745  /* Cancel condition variable sleep */
2747 
2748  /*
2749  * Also clean up any open wait for lock, since the lock manager will choke
2750  * if we try to wait for another lock before doing this.
2751  */
2752  LockErrorCleanup();
2753 
2754  /*
2755  * If any timeout events are still active, make sure the timeout interrupt
2756  * is scheduled. This covers possible loss of a timeout interrupt due to
2757  * longjmp'ing out of the SIGINT handler (see notes in handle_sig_alarm).
2758  * We delay this till after LockErrorCleanup so that we don't uselessly
2759  * reschedule lock or deadlock check timeouts.
2760  */
2762 
2763  /*
2764  * Re-enable signals, in case we got here by longjmp'ing out of a signal
2765  * handler. We do this fairly early in the sequence so that the timeout
2766  * infrastructure will be functional if needed while aborting.
2767  */
2768  sigprocmask(SIG_SETMASK, &UnBlockSig, NULL);
2769 
2770  /*
2771  * check the current transaction state
2772  */
2773  is_parallel_worker = (s->blockState == TBLOCK_PARALLEL_INPROGRESS);
2774  if (s->state != TRANS_INPROGRESS && s->state != TRANS_PREPARE)
2775  elog(WARNING, "AbortTransaction while in %s state",
2777  Assert(s->parent == NULL);
2778 
2779  /*
2780  * set the current transaction state information appropriately during the
2781  * abort processing
2782  */
2783  s->state = TRANS_ABORT;
2784 
2785  /*
2786  * Reset user ID which might have been changed transiently. We need this
2787  * to clean up in case control escaped out of a SECURITY DEFINER function
2788  * or other local change of CurrentUserId; therefore, the prior value of
2789  * SecurityRestrictionContext also needs to be restored.
2790  *
2791  * (Note: it is not necessary to restore session authorization or role
2792  * settings here because those can only be changed via GUC, and GUC will
2793  * take care of rolling them back if need be.)
2794  */
2796 
2797  /* Forget about any active REINDEX. */
2799 
2800  /* Reset logical streaming state. */
2802 
2803  /* Reset snapshot export state. */
2805 
2806  /* If in parallel mode, clean up workers and exit parallel mode. */
2807  if (IsInParallelMode())
2808  {
2809  AtEOXact_Parallel(false);
2810  s->parallelModeLevel = 0;
2811  }
2812 
2813  /*
2814  * do abort processing
2815  */
2816  AfterTriggerEndXact(false); /* 'false' means it's abort */
2817  AtAbort_Portals();
2818  smgrDoPendingSyncs(false, is_parallel_worker);
2819  AtEOXact_LargeObject(false);
2820  AtAbort_Notify();
2821  AtEOXact_RelationMap(false, is_parallel_worker);
2822  AtAbort_Twophase();
2823 
2824  /*
2825  * Advertise the fact that we aborted in pg_xact (assuming that we got as
2826  * far as assigning an XID to advertise). But if we're inside a parallel
2827  * worker, skip this; the user backend must be the one to write the abort
2828  * record.
2829  */
2830  if (!is_parallel_worker)
2831  latestXid = RecordTransactionAbort(false);
2832  else
2833  {
2834  latestXid = InvalidTransactionId;
2835 
2836  /*
2837  * Since the parallel leader won't get our value of XactLastRecEnd in
2838  * this case, we nudge WAL-writer ourselves in this case. See related
2839  * comments in RecordTransactionAbort for why this matters.
2840  */
2842  }
2843 
2844  TRACE_POSTGRESQL_TRANSACTION_ABORT(MyProc->vxid.lxid);
2845 
2846  /*
2847  * Let others know about no transaction in progress by me. Note that this
2848  * must be done _before_ releasing locks we hold and _after_
2849  * RecordTransactionAbort.
2850  */
2851  ProcArrayEndTransaction(MyProc, latestXid);
2852 
2853  /*
2854  * Post-abort cleanup. See notes in CommitTransaction() concerning
2855  * ordering. We can skip all of it if the transaction failed before
2856  * creating a resource owner.
2857  */
2858  if (TopTransactionResourceOwner != NULL)
2859  {
2860  if (is_parallel_worker)
2862  else
2864 
2867  false, true);
2868  AtEOXact_Buffers(false);
2869  AtEOXact_RelationCache(false);
2870  AtEOXact_Inval(false);
2874  false, true);
2877  false, true);
2878  smgrDoPendingDeletes(false);
2879 
2880  AtEOXact_GUC(false, 1);
2881  AtEOXact_SPI(false);
2882  AtEOXact_Enum();
2884  AtEOXact_Namespace(false, is_parallel_worker);
2885  AtEOXact_SMgr();
2886  AtEOXact_Files(false);
2888  AtEOXact_HashTables(false);
2889  AtEOXact_PgStat(false, is_parallel_worker);
2890  AtEOXact_ApplyLauncher(false);
2893  }
2894 
2895  /*
2896  * State remains TRANS_ABORT until CleanupTransaction().
2897  */
2899 }
void AtAbort_Notify(void)
Definition: async.c:1674
void AtEOXact_Parallel(bool isCommit)
Definition: parallel.c:1267
void AtEOXact_LogicalRepWorkers(bool isCommit)
Definition: worker.c:5028
void pgstat_report_xact_timestamp(TimestampTz tstamp)
void AtEOXact_LargeObject(bool isCommit)
Definition: be-fsstubs.c:602
void AtEOXact_Buffers(bool isCommit)
Definition: bufmgr.c:3213
uint32 TransactionId
Definition: c.h:639
void AtEOXact_ComboCid(void)
Definition: combocid.c:182
void AtEOXact_HashTables(bool isCommit)
Definition: dynahash.c:1878
void AtEOXact_Files(bool isCommit)
Definition: fd.c:3165
void AtEOXact_Inval(bool isCommit)
Definition: inval.c:1026
void AtEOXact_ApplyLauncher(bool isCommit)
Definition: launcher.c:1093
void AtEOXact_MultiXact(void)
Definition: multixact.c:1745
void AtEOXact_Namespace(bool isCommit, bool parallel)
Definition: namespace.c:4497
void AtEOXact_Enum(void)
Definition: pg_enum.c:638
void AtEOXact_PgStat(bool isCommit, bool parallel)
Definition: pgstat_xact.c:41
void ProcArrayEndTransaction(PGPROC *proc, TransactionId latestXid)
Definition: procarray.c:668
void AtEOXact_RelationCache(bool isCommit)
Definition: relcache.c:3193
void AtEOXact_RelationMap(bool isCommit, bool isParallelWorker)
Definition: relmapper.c:542
ResourceOwner TopTransactionResourceOwner
Definition: resowner.c:167
void AtEOXact_SMgr(void)
Definition: smgr.c:809
void SnapBuildResetExportedSnapshotState(void)
Definition: snapbuild.c:757
void AtEOXact_SPI(bool isCommit)
Definition: spi.c:429
PGPROC * MyProc
Definition: proc.c:68
int TransactionTimeout
Definition: proc.c:63
void smgrDoPendingSyncs(bool isCommit, bool isParallelWorker)
Definition: storage.c:700
void smgrDoPendingDeletes(bool isCommit)
Definition: storage.c:632
LocalTransactionId lxid
Definition: proc.h:196
struct PGPROC::@112 vxid
void AtEOXact_on_commit_actions(bool isCommit)
Definition: tablecmds.c:18038
void disable_timeout(TimeoutId id, bool keep_indicator)
Definition: timeout.c:685
@ TRANSACTION_TIMEOUT
Definition: timeout.h:34
#define InvalidTransactionId
Definition: transam.h:31
void AfterTriggerEndXact(bool isCommit)
Definition: trigger.c:5260
void AtAbort_Twophase(void)
Definition: twophase.c:307
static void AtAbort_ResourceOwner(void)
Definition: xact.c:1864
static void CallXactCallbacks(XactEvent event)
Definition: xact.c:3701
@ XACT_EVENT_ABORT
Definition: xact.h:130
@ XACT_EVENT_PARALLEL_ABORT
Definition: xact.h:131
XLogRecPtr XactLastRecEnd
Definition: xlog.c:259
void XLogSetAsyncXactLSN(XLogRecPtr asyncXactLSN)
Definition: xlog.c:2569

References AfterTriggerEndXact(), Assert(), AtAbort_Memory(), AtAbort_Notify(), AtAbort_Portals(), AtAbort_ResourceOwner(), AtAbort_Twophase(), AtEOXact_ApplyLauncher(), AtEOXact_Buffers(), AtEOXact_ComboCid(), AtEOXact_Enum(), AtEOXact_Files(), AtEOXact_GUC(), AtEOXact_HashTables(), AtEOXact_Inval(), AtEOXact_LargeObject(), AtEOXact_LogicalRepWorkers(), 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, disable_timeout(), elog, HOLD_INTERRUPTS, InvalidTransactionId, IsInParallelMode(), LockErrorCleanup(), LWLockReleaseAll(), PGPROC::lxid, MyProc, TransactionStateData::nestingLevel, TransactionStateData::parallelModeLevel, TransactionStateData::parent, pgstat_progress_end_command(), pgstat_report_wait_end(), pgstat_report_xact_timestamp(), TransactionStateData::prevSecContext, TransactionStateData::prevUser, ProcArrayEndTransaction(), RecordTransactionAbort(), reschedule_timeouts(), ResetLogicalStreamingState(), ResetReindexState(), RESOURCE_RELEASE_AFTER_LOCKS, RESOURCE_RELEASE_BEFORE_LOCKS, RESOURCE_RELEASE_LOCKS, ResourceOwnerRelease(), RESUME_INTERRUPTS, SetUserIdAndSecContext(), smgrDoPendingDeletes(), smgrDoPendingSyncs(), SnapBuildResetExportedSnapshotState(), TransactionStateData::state, TBLOCK_PARALLEL_INPROGRESS, TopTransactionResourceOwner, TRANS_ABORT, TRANS_INPROGRESS, TRANS_PREPARE, TRANSACTION_TIMEOUT, TransactionTimeout, TransStateAsString(), UnBlockSig, UnlockBuffers(), PGPROC::vxid, WARNING, XACT_EVENT_ABORT, XACT_EVENT_PARALLEL_ABORT, XactLastRecEnd, XLogResetInsertion(), and XLogSetAsyncXactLSN().

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

◆ AssignTransactionId()

static void AssignTransactionId ( TransactionState  s)
static

Definition at line 626 of file xact.c.

627 {
628  bool isSubXact = (s->parent != NULL);
629  ResourceOwner currentOwner;
630  bool log_unknown_top = false;
631 
632  /* Assert that caller didn't screw up */
635 
636  /*
637  * Workers synchronize transaction state at the beginning of each parallel
638  * operation, so we can't account for new XIDs at this point.
639  */
641  elog(ERROR, "cannot assign XIDs during a parallel operation");
642 
643  /*
644  * Ensure parent(s) have XIDs, so that a child always has an XID later
645  * than its parent. Mustn't recurse here, or we might get a stack
646  * overflow if we're at the bottom of a huge stack of subtransactions none
647  * of which have XIDs yet.
648  */
649  if (isSubXact && !FullTransactionIdIsValid(s->parent->fullTransactionId))
650  {
651  TransactionState p = s->parent;
652  TransactionState *parents;
653  size_t parentOffset = 0;
654 
655  parents = palloc(sizeof(TransactionState) * s->nestingLevel);
656  while (p != NULL && !FullTransactionIdIsValid(p->fullTransactionId))
657  {
658  parents[parentOffset++] = p;
659  p = p->parent;
660  }
661 
662  /*
663  * This is technically a recursive call, but the recursion will never
664  * be more than one layer deep.
665  */
666  while (parentOffset != 0)
667  AssignTransactionId(parents[--parentOffset]);
668 
669  pfree(parents);
670  }
671 
672  /*
673  * When wal_level=logical, guarantee that a subtransaction's xid can only
674  * be seen in the WAL stream if its toplevel xid has been logged before.
675  * If necessary we log an xact_assignment record with fewer than
676  * PGPROC_MAX_CACHED_SUBXIDS. Note that it is fine if didLogXid isn't set
677  * for a transaction even though it appears in a WAL record, we just might
678  * superfluously log something. That can happen when an xid is included
679  * somewhere inside a wal record, but not in XLogRecord->xl_xid, like in
680  * xl_standby_locks.
681  */
682  if (isSubXact && XLogLogicalInfoActive() &&
684  log_unknown_top = true;
685 
686  /*
687  * Generate a new FullTransactionId and record its xid in PGPROC and
688  * pg_subtrans.
689  *
690  * NB: we must make the subtrans entry BEFORE the Xid appears anywhere in
691  * shared storage other than PGPROC; because if there's no room for it in
692  * PGPROC, the subtrans entry is needed to ensure that other backends see
693  * the Xid as "running". See GetNewTransactionId.
694  */
695  s->fullTransactionId = GetNewTransactionId(isSubXact);
696  if (!isSubXact)
698 
699  if (isSubXact)
702 
703  /*
704  * If it's a top-level transaction, the predicate locking system needs to
705  * be told about it too.
706  */
707  if (!isSubXact)
709 
710  /*
711  * Acquire lock on the transaction XID. (We assume this cannot block.) We
712  * have to ensure that the lock is assigned to the transaction's own
713  * ResourceOwner.
714  */
715  currentOwner = CurrentResourceOwner;
717 
719 
720  CurrentResourceOwner = currentOwner;
721 
722  /*
723  * Every PGPROC_MAX_CACHED_SUBXIDS assigned transaction ids within each
724  * top-level transaction we issue a WAL record for the assignment. We
725  * include the top-level xid and all the subxids that have not yet been
726  * reported using XLOG_XACT_ASSIGNMENT records.
727  *
728  * This is required to limit the amount of shared memory required in a hot
729  * standby server to keep track of in-progress XIDs. See notes for
730  * RecordKnownAssignedTransactionIds().
731  *
732  * We don't keep track of the immediate parent of each subxid, only the
733  * top-level transaction that each subxact belongs to. This is correct in
734  * recovery only because aborted subtransactions are separately WAL
735  * logged.
736  *
737  * This is correct even for the case where several levels above us didn't
738  * have an xid assigned as we recursed up to them beforehand.
739  */
740  if (isSubXact && XLogStandbyInfoActive())
741  {
743  nUnreportedXids++;
744 
745  /*
746  * ensure this test matches similar one in
747  * RecoverPreparedTransactions()
748  */
750  log_unknown_top)
751  {
752  xl_xact_assignment xlrec;
753 
754  /*
755  * xtop is always set by now because we recurse up transaction
756  * stack to the highest unassigned xid and then come back down
757  */
758  xlrec.xtop = GetTopTransactionId();
760  xlrec.nsubxacts = nUnreportedXids;
761 
762  XLogBeginInsert();
763  XLogRegisterData((char *) &xlrec, MinSizeOfXactAssignment);
765  nUnreportedXids * sizeof(TransactionId));
766 
767  (void) XLogInsert(RM_XACT_ID, XLOG_XACT_ASSIGNMENT);
768 
769  nUnreportedXids = 0;
770  /* mark top, not current xact as having been logged */
772  }
773  }
774 }
#define ERROR
Definition: elog.h:39
#define IsParallelWorker()
Definition: parallel.h:61
void XactLockTableInsert(TransactionId xid)
Definition: lmgr.c:627
void pfree(void *pointer)
Definition: mcxt.c:1405
void * palloc(Size size)
Definition: mcxt.c:1201
void RegisterPredicateLockingXid(TransactionId xid)
Definition: predicate.c:1941
#define PGPROC_MAX_CACHED_SUBXIDS
Definition: proc.h:39
TransactionId xtop
Definition: xact.h:220
void SubTransSetParent(TransactionId xid, TransactionId parent)
Definition: subtrans.c:85
#define XidFromFullTransactionId(x)
Definition: transam.h:48
#define TransactionIdIsValid(xid)
Definition: transam.h:41
FullTransactionId GetNewTransactionId(bool isSubXact)
Definition: varsup.c:77
TransactionId GetTopTransactionId(void)
Definition: xact.c:417
static TransactionId unreportedXids[PGPROC_MAX_CACHED_SUBXIDS]
Definition: xact.c:252
static int nUnreportedXids
Definition: xact.c:251
static void AssignTransactionId(TransactionState s)
Definition: xact.c:626
static TransactionStateData TopTransactionStateData
Definition: xact.c:241
static FullTransactionId XactTopFullTransactionId
Definition: xact.c:125
#define MinSizeOfXactAssignment
Definition: xact.h:225
#define XLOG_XACT_ASSIGNMENT
Definition: xact.h:174
#define XLogLogicalInfoActive()
Definition: xlog.h:124
#define XLogStandbyInfoActive()
Definition: xlog.h:121
void XLogRegisterData(char *data, uint32 len)
Definition: xloginsert.c:365
XLogRecPtr XLogInsert(RmgrId rmid, uint8 info)
Definition: xloginsert.c:475
void XLogBeginInsert(void)
Definition: xloginsert.c:150

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

Referenced by GetCurrentFullTransactionId(), GetCurrentTransactionId(), GetTopFullTransactionId(), and GetTopTransactionId().

◆ AtAbort_Memory()

static void AtAbort_Memory ( void  )
static

Definition at line 1832 of file xact.c.

1833 {
1834  /*
1835  * Switch into TransactionAbortContext, which should have some free space
1836  * even if nothing else does. We'll work in this context until we've
1837  * finished cleaning up.
1838  *
1839  * It is barely possible to get here when we've not been able to create
1840  * TransactionAbortContext yet; if so use TopMemoryContext.
1841  */
1842  if (TransactionAbortContext != NULL)
1844  else
1846 }
MemoryContext TopMemoryContext
Definition: mcxt.c:141
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:124
static MemoryContext TransactionAbortContext
Definition: xact.c:297

References MemoryContextSwitchTo(), TopMemoryContext, and TransactionAbortContext.

Referenced by AbortOutOfAnyTransaction(), and AbortTransaction().

◆ AtAbort_ResourceOwner()

static void AtAbort_ResourceOwner ( void  )
static

Definition at line 1864 of file xact.c.

1865 {
1866  /*
1867  * Make sure we have a valid ResourceOwner, if possible (else it will be
1868  * NULL, which is OK)
1869  */
1871 }

References CurrentResourceOwner, and TopTransactionResourceOwner.

Referenced by AbortTransaction().

◆ AtCCI_LocalCache()

static void AtCCI_LocalCache ( void  )
static

Definition at line 1537 of file xact.c.

1538 {
1539  /*
1540  * Make any pending relation map changes visible. We must do this before
1541  * processing local sinval messages, so that the map changes will get
1542  * reflected into the relcache when relcache invals are processed.
1543  */
1545 
1546  /*
1547  * Make catalog changes visible to me for the next command.
1548  */
1550 }
void CommandEndInvalidationMessages(void)
Definition: inval.c:1171
void AtCCI_RelationMap(void)
Definition: relmapper.c:505

References AtCCI_RelationMap(), and CommandEndInvalidationMessages().

Referenced by CommandCounterIncrement().

◆ AtCleanup_Memory()

static void AtCleanup_Memory ( void  )
static

Definition at line 1922 of file xact.c.

1923 {
1925 
1926  /*
1927  * Now that we're "out" of a transaction, have the system allocate things
1928  * in the top memory context instead of per-transaction contexts.
1929  */
1931 
1932  /*
1933  * Clear the special abort context for next time.
1934  */
1935  if (TransactionAbortContext != NULL)
1937 
1938  /*
1939  * Release all transaction-local memory.
1940  */
1941  if (TopTransactionContext != NULL)
1943  TopTransactionContext = NULL;
1944  CurTransactionContext = NULL;
1946 }
void MemoryContextReset(MemoryContext context)
Definition: mcxt.c:330
MemoryContext TopTransactionContext
Definition: mcxt.c:146
MemoryContext CurTransactionContext
Definition: mcxt.c:147
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:403
MemoryContext curTransactionContext
Definition: xact.c:199

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

Referenced by AbortOutOfAnyTransaction(), and CleanupTransaction().

◆ AtCommit_Memory()

static void AtCommit_Memory ( void  )
static

Definition at line 1556 of file xact.c.

1557 {
1558  /*
1559  * Now that we're "out" of a transaction, have the system allocate things
1560  * in the top memory context instead of per-transaction contexts.
1561  */
1563 
1564  /*
1565  * Release all transaction-local memory.
1566  */
1567  Assert(TopTransactionContext != NULL);
1569  TopTransactionContext = NULL;
1570  CurTransactionContext = NULL;
1572 }

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

Referenced by CommitTransaction(), and PrepareTransaction().

◆ AtStart_Cache()

static void AtStart_Cache ( void  )
static

Definition at line 1143 of file xact.c.

1144 {
1146 }
void AcceptInvalidationMessages(void)
Definition: inval.c:807

References AcceptInvalidationMessages().

Referenced by StartTransaction().

◆ AtStart_Memory()

static void AtStart_Memory ( void  )
static

Definition at line 1152 of file xact.c.

1153 {
1155 
1156  /*
1157  * If this is the first time through, create a private context for
1158  * AbortTransaction to work in. By reserving some space now, we can
1159  * insulate AbortTransaction from out-of-memory scenarios. Like
1160  * ErrorContext, we set it up with slow growth rate and a nonzero minimum
1161  * size, so that space will be reserved immediately.
1162  */
1163  if (TransactionAbortContext == NULL)
1166  "TransactionAbortContext",
1167  32 * 1024,
1168  32 * 1024,
1169  32 * 1024);
1170 
1171  /*
1172  * We shouldn't have a transaction context already.
1173  */
1174  Assert(TopTransactionContext == NULL);
1175 
1176  /*
1177  * Create a toplevel context for the transaction.
1178  */
1181  "TopTransactionContext",
1183 
1184  /*
1185  * In a top-level transaction, CurTransactionContext is the same as
1186  * TopTransactionContext.
1187  */
1190 
1191  /* Make the CurTransactionContext active. */
1193 }
#define AllocSetContextCreate
Definition: memutils.h:128
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:152

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

Referenced by StartTransaction().

◆ AtStart_ResourceOwner()

static void AtStart_ResourceOwner ( void  )
static

Definition at line 1199 of file xact.c.

1200 {
1202 
1203  /*
1204  * We shouldn't have a transaction resource owner already.
1205  */
1207 
1208  /*
1209  * Create a toplevel resource owner for the transaction.
1210  */
1211  s->curTransactionOwner = ResourceOwnerCreate(NULL, "TopTransaction");
1212 
1216 }
ResourceOwner ResourceOwnerCreate(ResourceOwner parent, const char *name)
Definition: resowner.c:413
ResourceOwner CurTransactionResourceOwner
Definition: resowner.c:166

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

Referenced by StartTransaction().

◆ AtSubAbort_childXids()

static void AtSubAbort_childXids ( void  )
static

Definition at line 1890 of file xact.c.

1891 {
1893 
1894  /*
1895  * We keep the child-XID arrays in TopTransactionContext (see
1896  * AtSubCommit_childXids). This means we'd better free the array
1897  * explicitly at abort to avoid leakage.
1898  */
1899  if (s->childXids != NULL)
1900  pfree(s->childXids);
1901  s->childXids = NULL;
1902  s->nChildXids = 0;
1903  s->maxChildXids = 0;
1904 
1905  /*
1906  * We could prune the unreportedXids array here. But we don't bother. That
1907  * would potentially reduce number of XLOG_XACT_ASSIGNMENT records but it
1908  * would likely introduce more CPU time into the more common paths, so we
1909  * choose not to do that.
1910  */
1911 }
TransactionId * childXids
Definition: xact.c:201

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

Referenced by AbortSubTransaction().

◆ AtSubAbort_Memory()

static void AtSubAbort_Memory ( void  )
static

Definition at line 1852 of file xact.c.

1853 {
1855 
1857 }

References Assert(), MemoryContextSwitchTo(), and TransactionAbortContext.

Referenced by AbortSubTransaction().

◆ AtSubAbort_ResourceOwner()

static void AtSubAbort_ResourceOwner ( void  )
static

Definition at line 1877 of file xact.c.

1878 {
1880 
1881  /* Make sure we have a valid ResourceOwner */
1883 }

References CurrentResourceOwner, CurrentTransactionState, and TransactionStateData::curTransactionOwner.

Referenced by AbortSubTransaction().

◆ AtSubCleanup_Memory()

static void AtSubCleanup_Memory ( void  )
static

Definition at line 1958 of file xact.c.

1959 {
1961 
1962  Assert(s->parent != NULL);
1963 
1964  /* Make sure we're not in an about-to-be-deleted context */
1967 
1968  /*
1969  * Clear the special abort context for next time.
1970  */
1971  if (TransactionAbortContext != NULL)
1973 
1974  /*
1975  * Delete the subxact local memory contexts. Its CurTransactionContext can
1976  * go too (note this also kills CurTransactionContexts from any children
1977  * of the subxact).
1978  */
1979  if (s->curTransactionContext)
1981  s->curTransactionContext = NULL;
1982 }

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

Referenced by CleanupSubTransaction().

◆ AtSubCommit_childXids()

static void AtSubCommit_childXids ( void  )
static

Definition at line 1612 of file xact.c.

1613 {
1615  int new_nChildXids;
1616 
1617  Assert(s->parent != NULL);
1618 
1619  /*
1620  * The parent childXids array will need to hold my XID and all my
1621  * childXids, in addition to the XIDs already there.
1622  */
1623  new_nChildXids = s->parent->nChildXids + s->nChildXids + 1;
1624 
1625  /* Allocate or enlarge the parent array if necessary */
1626  if (s->parent->maxChildXids < new_nChildXids)
1627  {
1628  int new_maxChildXids;
1629  TransactionId *new_childXids;
1630 
1631  /*
1632  * Make it 2x what's needed right now, to avoid having to enlarge it
1633  * repeatedly. But we can't go above MaxAllocSize. (The latter limit
1634  * is what ensures that we don't need to worry about integer overflow
1635  * here or in the calculation of new_nChildXids.)
1636  */
1637  new_maxChildXids = Min(new_nChildXids * 2,
1638  (int) (MaxAllocSize / sizeof(TransactionId)));
1639 
1640  if (new_maxChildXids < new_nChildXids)
1641  ereport(ERROR,
1642  (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
1643  errmsg("maximum number of committed subtransactions (%d) exceeded",
1644  (int) (MaxAllocSize / sizeof(TransactionId)))));
1645 
1646  /*
1647  * We keep the child-XID arrays in TopTransactionContext; this avoids
1648  * setting up child-transaction contexts for what might be just a few
1649  * bytes of grandchild XIDs.
1650  */
1651  if (s->parent->childXids == NULL)
1652  new_childXids =
1654  new_maxChildXids * sizeof(TransactionId));
1655  else
1656  new_childXids = repalloc(s->parent->childXids,
1657  new_maxChildXids * sizeof(TransactionId));
1658 
1659  s->parent->childXids = new_childXids;
1660  s->parent->maxChildXids = new_maxChildXids;
1661  }
1662 
1663  /*
1664  * Copy all my XIDs to parent's array.
1665  *
1666  * Note: We rely on the fact that the XID of a child always follows that
1667  * of its parent. By copying the XID of this subtransaction before the
1668  * XIDs of its children, we ensure that the array stays ordered. Likewise,
1669  * all XIDs already in the array belong to subtransactions started and
1670  * subcommitted before us, so their XIDs must precede ours.
1671  */
1673 
1674  if (s->nChildXids > 0)
1675  memcpy(&s->parent->childXids[s->parent->nChildXids + 1],
1676  s->childXids,
1677  s->nChildXids * sizeof(TransactionId));
1678 
1679  s->parent->nChildXids = new_nChildXids;
1680 
1681  /* Release child's array to avoid leakage */
1682  if (s->childXids != NULL)
1683  pfree(s->childXids);
1684  /* We must reset these to avoid double-free if fail later in commit */
1685  s->childXids = NULL;
1686  s->nChildXids = 0;
1687  s->maxChildXids = 0;
1688 }
#define Min(x, y)
Definition: c.h:991
int errcode(int sqlerrcode)
Definition: elog.c:860
int errmsg(const char *fmt,...)
Definition: elog.c:1073
#define ereport(elevel,...)
Definition: elog.h:149
void * repalloc(void *pointer, Size size)
Definition: mcxt.c:1425
void * MemoryContextAlloc(MemoryContext context, Size size)
Definition: mcxt.c:1066
#define MaxAllocSize
Definition: memutils.h:40

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

Referenced by CommitSubTransaction().

◆ AtSubCommit_Memory()

static void AtSubCommit_Memory ( void  )
static

Definition at line 1583 of file xact.c.

1584 {
1586 
1587  Assert(s->parent != NULL);
1588 
1589  /* Return to parent transaction level's memory context. */
1592 
1593  /*
1594  * Ordinarily we cannot throw away the child's CurTransactionContext,
1595  * since the data it contains will be needed at upper commit. However, if
1596  * there isn't actually anything in it, we can throw it away. This avoids
1597  * a small memory leak in the common case of "trivial" subxacts.
1598  */
1600  {
1602  s->curTransactionContext = NULL;
1603  }
1604 }
bool MemoryContextIsEmpty(MemoryContext context)
Definition: mcxt.c:652

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

Referenced by CommitSubTransaction().

◆ AtSubStart_Memory()

static void AtSubStart_Memory ( void  )
static

Definition at line 1227 of file xact.c.

1228 {
1230 
1231  Assert(CurTransactionContext != NULL);
1232 
1233  /*
1234  * Create a CurTransactionContext, which will be used to hold data that
1235  * survives subtransaction commit but disappears on subtransaction abort.
1236  * We make it a child of the immediate parent's CurTransactionContext.
1237  */
1239  "CurTransactionContext",
1242 
1243  /* Make the CurTransactionContext active. */
1245 }

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

Referenced by StartSubTransaction().

◆ AtSubStart_ResourceOwner()

static void AtSubStart_ResourceOwner ( void  )
static

Definition at line 1251 of file xact.c.

1252 {
1254 
1255  Assert(s->parent != NULL);
1256 
1257  /*
1258  * Create a resource owner for the subtransaction. We make it a child of
1259  * the immediate parent's resource owner.
1260  */
1261  s->curTransactionOwner =
1263  "SubTransaction");
1264 
1267 }

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

Referenced by StartSubTransaction().

◆ BeginImplicitTransactionBlock()

void BeginImplicitTransactionBlock ( void  )

Definition at line 4189 of file xact.c.

4190 {
4192 
4193  /*
4194  * If we are in STARTED state (that is, no transaction block is open),
4195  * switch to IMPLICIT_INPROGRESS state, creating an implicit transaction
4196  * block.
4197  *
4198  * For caller convenience, we consider all other transaction states as
4199  * legal here; otherwise the caller would need its own state check, which
4200  * seems rather pointless.
4201  */
4202  if (s->blockState == TBLOCK_STARTED)
4204 }

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

Referenced by exec_simple_query().

◆ BeginInternalSubTransaction()

void BeginInternalSubTransaction ( const char *  name)

Definition at line 4557 of file xact.c.

4558 {
4560 
4561  /*
4562  * Workers synchronize transaction state at the beginning of each parallel
4563  * operation, so we can't account for new subtransactions after that
4564  * point. We might be able to make an exception for the type of
4565  * subtransaction established by this function, which is typically used in
4566  * contexts where we're going to release or roll back the subtransaction
4567  * before proceeding further, so that no enduring change to the
4568  * transaction state occurs. For now, however, we prohibit this case along
4569  * with all the others.
4570  */
4571  if (IsInParallelMode())
4572  ereport(ERROR,
4573  (errcode(ERRCODE_INVALID_TRANSACTION_STATE),
4574  errmsg("cannot start subtransactions during a parallel operation")));
4575 
4576  switch (s->blockState)
4577  {
4578  case TBLOCK_STARTED:
4579  case TBLOCK_INPROGRESS:
4581  case TBLOCK_END:
4582  case TBLOCK_PREPARE:
4583  case TBLOCK_SUBINPROGRESS:
4584  /* Normal subtransaction start */
4585  PushTransaction();
4586  s = CurrentTransactionState; /* changed by push */
4587 
4588  /*
4589  * Savepoint names, like the TransactionState block itself, live
4590  * in TopTransactionContext.
4591  */
4592  if (name)
4594  break;
4595 
4596  /* These cases are invalid. */
4597  case TBLOCK_DEFAULT:
4598  case TBLOCK_BEGIN:
4600  case TBLOCK_SUBBEGIN:
4601  case TBLOCK_SUBRELEASE:
4602  case TBLOCK_SUBCOMMIT:
4603  case TBLOCK_ABORT:
4604  case TBLOCK_SUBABORT:
4605  case TBLOCK_ABORT_END:
4606  case TBLOCK_SUBABORT_END:
4607  case TBLOCK_ABORT_PENDING:
4609  case TBLOCK_SUBRESTART:
4611  elog(FATAL, "BeginInternalSubTransaction: unexpected state %s",
4613  break;
4614  }
4615 
4618 }
#define FATAL
Definition: elog.h:41
char * MemoryContextStrdup(MemoryContext context, const char *string)
Definition: mcxt.c:1567
const char * name
static void PushTransaction(void)
Definition: xact.c:5280
void StartTransactionCommand(void)
Definition: xact.c:2954
static const char * BlockStateAsString(TBlockState blockState)
Definition: xact.c:5561
void CommitTransactionCommand(void)
Definition: xact.c:3051

References TransactionStateData::blockState, BlockStateAsString(), CommitTransactionCommand(), CurrentTransactionState, elog, ereport, errcode(), errmsg(), ERROR, FATAL, IsInParallelMode(), MemoryContextStrdup(), TransactionStateData::name, 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(), ReorderBufferImmediateInvalidation(), and ReorderBufferProcessTXN().

◆ BeginTransactionBlock()

void BeginTransactionBlock ( void  )

Definition at line 3787 of file xact.c.

3788 {
3790 
3791  switch (s->blockState)
3792  {
3793  /*
3794  * We are not inside a transaction block, so allow one to begin.
3795  */
3796  case TBLOCK_STARTED:
3797  s->blockState = TBLOCK_BEGIN;
3798  break;
3799 
3800  /*
3801  * BEGIN converts an implicit transaction block to a regular one.
3802  * (Note that we allow this even if we've already done some
3803  * commands, which is a bit odd but matches historical practice.)
3804  */
3806  s->blockState = TBLOCK_BEGIN;
3807  break;
3808 
3809  /*
3810  * Already a transaction block in progress.
3811  */
3812  case TBLOCK_INPROGRESS:
3814  case TBLOCK_SUBINPROGRESS:
3815  case TBLOCK_ABORT:
3816  case TBLOCK_SUBABORT:
3817  ereport(WARNING,
3818  (errcode(ERRCODE_ACTIVE_SQL_TRANSACTION),
3819  errmsg("there is already a transaction in progress")));
3820  break;
3821 
3822  /* These cases are invalid. */
3823  case TBLOCK_DEFAULT:
3824  case TBLOCK_BEGIN:
3825  case TBLOCK_SUBBEGIN:
3826  case TBLOCK_END:
3827  case TBLOCK_SUBRELEASE:
3828  case TBLOCK_SUBCOMMIT:
3829  case TBLOCK_ABORT_END:
3830  case TBLOCK_SUBABORT_END:
3831  case TBLOCK_ABORT_PENDING:
3833  case TBLOCK_SUBRESTART:
3835  case TBLOCK_PREPARE:
3836  elog(FATAL, "BeginTransactionBlock: unexpected state %s",
3838  break;
3839  }
3840 }

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 apply_handle_prepare_internal(), pa_start_subtrans(), and standard_ProcessUtility().

◆ BlockStateAsString()

static const char * BlockStateAsString ( TBlockState  blockState)
static

Definition at line 5561 of file xact.c.

5562 {
5563  switch (blockState)
5564  {
5565  case TBLOCK_DEFAULT:
5566  return "DEFAULT";
5567  case TBLOCK_STARTED:
5568  return "STARTED";
5569  case TBLOCK_BEGIN:
5570  return "BEGIN";
5571  case TBLOCK_INPROGRESS:
5572  return "INPROGRESS";
5574  return "IMPLICIT_INPROGRESS";
5576  return "PARALLEL_INPROGRESS";
5577  case TBLOCK_END:
5578  return "END";
5579  case TBLOCK_ABORT:
5580  return "ABORT";
5581  case TBLOCK_ABORT_END:
5582  return "ABORT_END";
5583  case TBLOCK_ABORT_PENDING:
5584  return "ABORT_PENDING";
5585  case TBLOCK_PREPARE:
5586  return "PREPARE";
5587  case TBLOCK_SUBBEGIN:
5588  return "SUBBEGIN";
5589  case TBLOCK_SUBINPROGRESS:
5590  return "SUBINPROGRESS";
5591  case TBLOCK_SUBRELEASE:
5592  return "SUBRELEASE";
5593  case TBLOCK_SUBCOMMIT:
5594  return "SUBCOMMIT";
5595  case TBLOCK_SUBABORT:
5596  return "SUBABORT";
5597  case TBLOCK_SUBABORT_END:
5598  return "SUBABORT_END";
5600  return "SUBABORT_PENDING";
5601  case TBLOCK_SUBRESTART:
5602  return "SUBRESTART";
5604  return "SUBABORT_RESTART";
5605  }
5606  return "UNRECOGNIZED";
5607 }

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

◆ CallSubXactCallbacks()

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

Definition at line 3761 of file xact.c.

3764 {
3765  SubXactCallbackItem *item;
3767 
3768  for (item = SubXact_callbacks; item; item = next)
3769  {
3770  /* allow callbacks to unregister themselves when called */
3771  next = item->next;
3772  item->callback(event, mySubid, parentSubid, item->arg);
3773  }
3774 }
static int32 next
Definition: blutils.c:221
struct SubXactCallbackItem * next
Definition: xact.c:316
SubXactCallback callback
Definition: xact.c:317
static SubXactCallbackItem * SubXact_callbacks
Definition: xact.c:321

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

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

◆ CallXactCallbacks()

static void CallXactCallbacks ( XactEvent  event)
static

Definition at line 3701 of file xact.c.

3702 {
3703  XactCallbackItem *item;
3705 
3706  for (item = Xact_callbacks; item; item = next)
3707  {
3708  /* allow callbacks to unregister themselves when called */
3709  next = item->next;
3710  item->callback(event, item->arg);
3711  }
3712 }
struct XactCallbackItem * next
Definition: xact.c:304
void * arg
Definition: xact.c:306
XactCallback callback
Definition: xact.c:305
static XactCallbackItem * Xact_callbacks
Definition: xact.c:309

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

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

◆ CheckTransactionBlock()

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

Definition at line 3585 of file xact.c.

3586 {
3587  /*
3588  * xact block already started?
3589  */
3590  if (IsTransactionBlock())
3591  return;
3592 
3593  /*
3594  * subtransaction?
3595  */
3596  if (IsSubTransaction())
3597  return;
3598 
3599  /*
3600  * inside a function call?
3601  */
3602  if (!isTopLevel)
3603  return;
3604 
3605  ereport(throwError ? ERROR : WARNING,
3606  (errcode(ERRCODE_NO_ACTIVE_SQL_TRANSACTION),
3607  /* translator: %s represents an SQL statement name */
3608  errmsg("%s can only be used in transaction blocks",
3609  stmtType)));
3610 }
bool IsSubTransaction(void)
Definition: xact.c:4906
bool IsTransactionBlock(void)
Definition: xact.c:4833

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

Referenced by RequireTransactionBlock(), and WarnNoTransactionBlock().

◆ CleanupSubTransaction()

static void CleanupSubTransaction ( void  )
static

Definition at line 5247 of file xact.c.

5248 {
5250 
5251  ShowTransactionState("CleanupSubTransaction");
5252 
5253  if (s->state != TRANS_ABORT)
5254  elog(WARNING, "CleanupSubTransaction while in %s state",
5256 
5258 
5261  if (s->curTransactionOwner)
5263  s->curTransactionOwner = NULL;
5264 
5266 
5267  s->state = TRANS_DEFAULT;
5268 
5269  PopTransaction();
5270 }
void AtSubCleanup_Portals(SubTransactionId mySubid)
Definition: portalmem.c:1093
void ResourceOwnerDelete(ResourceOwner owner)
Definition: resowner.c:854
static void AtSubCleanup_Memory(void)
Definition: xact.c:1958
static void PopTransaction(void)
Definition: xact.c:5341

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

◆ CleanupTransaction()

static void CleanupTransaction ( void  )
static

Definition at line 2905 of file xact.c.

2906 {
2908 
2909  /*
2910  * State should still be TRANS_ABORT from AbortTransaction().
2911  */
2912  if (s->state != TRANS_ABORT)
2913  elog(FATAL, "CleanupTransaction: unexpected state %s",
2915 
2916  /*
2917  * do abort cleanup processing
2918  */
2919  AtCleanup_Portals(); /* now safe to release portal memory */
2920  AtEOXact_Snapshot(false, true); /* and release the transaction's snapshots */
2921 
2922  CurrentResourceOwner = NULL; /* and resource owner */
2925  s->curTransactionOwner = NULL;
2928 
2929  AtCleanup_Memory(); /* and transaction memory */
2930 
2933  s->nestingLevel = 0;
2934  s->gucNestLevel = 0;
2935  s->childXids = NULL;
2936  s->nChildXids = 0;
2937  s->maxChildXids = 0;
2938  s->parallelModeLevel = 0;
2939 
2942 
2943  /*
2944  * done with abort processing, set current transaction state back to
2945  * default
2946  */
2947  s->state = TRANS_DEFAULT;
2948 }
#define InvalidSubTransactionId
Definition: c.h:645
void AtCleanup_Portals(void)
Definition: portalmem.c:859
void AtEOXact_Snapshot(bool isCommit, bool resetXmin)
Definition: snapmgr.c:1002
#define InvalidFullTransactionId
Definition: transam.h:56
static int nParallelCurrentXids
Definition: xact.c:126

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

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

◆ CommandCounterIncrement()

void CommandCounterIncrement ( void  )

Definition at line 1078 of file xact.c.

1079 {
1080  /*
1081  * If the current value of the command counter hasn't been "used" to mark
1082  * tuples, we need not increment it, since there's no need to distinguish
1083  * a read-only command from others. This helps postpone command counter
1084  * overflow, and keeps no-op CommandCounterIncrement operations cheap.
1085  */
1087  {
1088  /*
1089  * Workers synchronize transaction state at the beginning of each
1090  * parallel operation, so we can't account for new commands after that
1091  * point.
1092  */
1094  elog(ERROR, "cannot start commands during a parallel operation");
1095 
1096  currentCommandId += 1;
1098  {
1099  currentCommandId -= 1;
1100  ereport(ERROR,
1101  (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
1102  errmsg("cannot have more than 2^32-2 commands in a transaction")));
1103  }
1104  currentCommandIdUsed = false;
1105 
1106  /* Propagate new command ID into static snapshots */
1108 
1109  /*
1110  * Make any catalog changes done by the just-completed command visible
1111  * in the local syscache. We obviously don't need to do this after a
1112  * read-only command. (But see hacks in inval.c to make real sure we
1113  * don't think a command that queued inval messages was read-only.)
1114  */
1115  AtCCI_LocalCache();
1116  }
1117 }
#define InvalidCommandId
Definition: c.h:656
void SnapshotSetCommandId(CommandId curcid)
Definition: snapmgr.c:463
static bool currentCommandIdUsed
Definition: xact.c:262
static CommandId currentCommandId
Definition: xact.c:261
static void AtCCI_LocalCache(void)
Definition: xact.c:1537

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

Referenced by _SPI_execute_plan(), acquire_inherited_sample_rows(), addFkRecurseReferenced(), addFkRecurseReferencing(), AddRoleMems(), AlterPublicationOptions(), AlterRole(), ATAddCheckNNConstraint(), ATExecAddColumn(), ATExecAlterColumnType(), ATExecCmd(), ATExecDropColumn(), ATExecDropExpression(), ATExecDropIdentity(), ATExecSetCompression(), ATExecSetExpression(), ATExecSetTableSpace(), ATExecSetTableSpaceNoStorage(), ATInheritAdjustNotNulls(), ATParseTransformCmd(), ATRewriteTables(), AttachPartitionEnsureIndexes(), btadjustmembers(), CloneFkReferencing(), CommitSubTransaction(), CommitTransactionCommand(), copy_table_data(), create_ctas_internal(), create_toast_table(), CreateFKCheckTrigger(), createForeignKeyActionTriggers(), CreateForeignTable(), CreatePublication(), CreateRole(), CreateSchemaCommand(), CreateTriggerFiringOn(), DefineCollation(), DefineDomain(), DefineIndex(), DefineRelation(), DefineVirtualRelation(), deleteOneObject(), DetachPartitionFinalize(), DropClonedTriggersFromPartition(), dropconstraint_internal(), DropRole(), end_replication_step(), EventTriggerDDLCommandEnd(), EventTriggerDDLCommandStart(), EventTriggerInvoke(), EventTriggerSQLDrop(), EventTriggerTableRewrite(), exec_eval_simple_expr(), exec_execute_message(), exec_parse_message(), exec_simple_query(), ExecGrant_common(), ExecGrant_Largeobject(), ExecGrant_Parameter(), ExecGrant_Relation(), execute_sql_string(), ExplainOnePlan(), finish_heap_swap(), fmgr_sql(), hashadjustmembers(), ImportForeignSchema(), index_build(), index_create(), IndexSetParentIndex(), InitTempTableNamespace(), inv_create(), inv_drop(), inv_truncate(), inv_write(), LogicalRepSyncTableStart(), make_new_heap(), makeConfigurationDependencies(), moveArrayTypeName(), objectNamesToOids(), OperatorShellMake(), OperatorUpd(), pg_import_system_collations(), PortalRunMulti(), ProcedureCreate(), process_syncing_tables_for_apply(), ProcessUtilitySlow(), recordExtensionInitPrivWorker(), reindex_index(), reindex_relation(), ReindexRelationConcurrently(), RelationSetNewRelfilenumber(), RemoveRoleFromObjectPolicy(), RenumberEnumType(), replorigin_create(), replorigin_drop_by_name(), ri_PerformCheck(), SetDatatabaseHasLoginEventTriggers(), SetDefaultACL(), SetMatViewPopulatedState(), shdepReassignOwned(), SPI_cursor_open_internal(), standard_ProcessUtility(), StoreConstraints(), StorePartitionBound(), tryAttachPartitionForeignKey(), vacuum(), and validatePartitionedIndex().

◆ CommitSubTransaction()

static void CommitSubTransaction ( void  )
static

Definition at line 4966 of file xact.c.

4967 {
4969 
4970  ShowTransactionState("CommitSubTransaction");
4971 
4972  if (s->state != TRANS_INPROGRESS)
4973  elog(WARNING, "CommitSubTransaction while in %s state",
4975 
4976  /* Pre-commit processing goes here */
4977 
4979  s->parent->subTransactionId);
4980 
4981  /* If in parallel mode, clean up workers and exit parallel mode. */
4982  if (IsInParallelMode())
4983  {
4985  s->parallelModeLevel = 0;
4986  }
4987 
4988  /* Do the actual "commit", such as it is */
4989  s->state = TRANS_COMMIT;
4990 
4991  /* Must CCI to ensure commands of subtransaction are seen as done */
4993 
4994  /*
4995  * Prior to 8.4 we marked subcommit in clog at this point. We now only
4996  * perform that step, if required, as part of the atomic update of the
4997  * whole transaction tree at top level commit or abort.
4998  */
4999 
5000  /* Post-commit cleanup */
5003  AfterTriggerEndSubXact(true);
5006  s->parent->nestingLevel,
5009  s->parent->subTransactionId);
5011 
5013  s->parent->subTransactionId);
5014 
5017  true, false);
5019  s->parent->subTransactionId);
5020  AtEOSubXact_Inval(true);
5021  AtSubCommit_smgr();
5022 
5023  /*
5024  * The only lock we actually release here is the subtransaction XID lock.
5025  */
5029 
5030  /*
5031  * Other locks should get transferred to their parent resource owner.
5032  */
5035  true, false);
5038  true, false);
5039 
5040  AtEOXact_GUC(true, s->gucNestLevel);
5043  s->parent->subTransactionId);
5045  s->parent->subTransactionId);
5047  s->parent->subTransactionId);
5049  AtEOSubXact_PgStat(true, s->nestingLevel);
5051 
5052  /*
5053  * We need to restore the upper transaction's read-only state, in case the
5054  * upper is read-write while the child is read-only; GUC will incorrectly
5055  * think it should leave the child state in place.
5056  */
5058 
5062  s->curTransactionOwner = NULL;
5063 
5065 
5066  s->state = TRANS_DEFAULT;
5067 
5068  PopTransaction();
5069 }
void AtSubCommit_Notify(void)
Definition: async.c:1694
void XactLockTableDelete(TransactionId xid)
Definition: lmgr.c:644
void AtSubCommit_Portals(SubTransactionId mySubid, SubTransactionId parentSubid, int parentLevel, ResourceOwner parentXactOwner)
Definition: portalmem.c:944
void AtSubCommit_Snapshot(int level)
Definition: snapmgr.c:945
void AtSubCommit_smgr(void)
Definition: storage.c:914
static void AtSubCommit_Memory(void)
Definition: xact.c:1583
static void AtSubCommit_childXids(void)
Definition: xact.c:1612
void CommandCounterIncrement(void)
Definition: xact.c:1078
@ SUBXACT_EVENT_PRE_COMMIT_SUB
Definition: xact.h:145
@ SUBXACT_EVENT_COMMIT_SUB
Definition: xact.h:143

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::fullTransactionId, FullTransactionIdIsValid, 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, TransStateAsString(), WARNING, XactLockTableDelete(), XactReadOnly, and XidFromFullTransactionId.

Referenced by CommitTransactionCommand(), and ReleaseCurrentSubTransaction().

◆ CommitTransaction()

static void CommitTransaction ( void  )
static

Definition at line 2157 of file xact.c.

2158 {
2160  TransactionId latestXid;
2161  bool is_parallel_worker;
2162 
2163  is_parallel_worker = (s->blockState == TBLOCK_PARALLEL_INPROGRESS);
2164 
2165  /* Enforce parallel mode restrictions during parallel worker commit. */
2166  if (is_parallel_worker)
2168 
2169  ShowTransactionState("CommitTransaction");
2170 
2171  /*
2172  * check the current transaction state
2173  */
2174  if (s->state != TRANS_INPROGRESS)
2175  elog(WARNING, "CommitTransaction while in %s state",
2177  Assert(s->parent == NULL);
2178 
2179  /*
2180  * Do pre-commit processing that involves calling user-defined code, such
2181  * as triggers. SECURITY_RESTRICTED_OPERATION contexts must not queue an
2182  * action that would run here, because that would bypass the sandbox.
2183  * Since closing cursors could queue trigger actions, triggers could open
2184  * cursors, etc, we have to keep looping until there's nothing left to do.
2185  */
2186  for (;;)
2187  {
2188  /*
2189  * Fire all currently pending deferred triggers.
2190  */
2192 
2193  /*
2194  * Close open portals (converting holdable ones into static portals).
2195  * If there weren't any, we are done ... otherwise loop back to check
2196  * if they queued deferred triggers. Lather, rinse, repeat.
2197  */
2198  if (!PreCommit_Portals(false))
2199  break;
2200  }
2201 
2202  /*
2203  * The remaining actions cannot call any user-defined code, so it's safe
2204  * to start shutting down within-transaction services. But note that most
2205  * of this stuff could still throw an error, which would switch us into
2206  * the transaction-abort path.
2207  */
2208 
2211 
2212  /* If we might have parallel workers, clean them up now. */
2213  if (IsInParallelMode())
2214  AtEOXact_Parallel(true);
2215 
2216  /* Shut down the deferred-trigger manager */
2217  AfterTriggerEndXact(true);
2218 
2219  /*
2220  * Let ON COMMIT management do its thing (must happen after closing
2221  * cursors, to avoid dangling-reference problems)
2222  */
2224 
2225  /*
2226  * Synchronize files that are created and not WAL-logged during this
2227  * transaction. This must happen before AtEOXact_RelationMap(), so that we
2228  * don't see committed-but-broken files after a crash.
2229  */
2230  smgrDoPendingSyncs(true, is_parallel_worker);
2231 
2232  /* close large objects before lower-level cleanup */
2233  AtEOXact_LargeObject(true);
2234 
2235  /*
2236  * Insert notifications sent by NOTIFY commands into the queue. This
2237  * should be late in the pre-commit sequence to minimize time spent
2238  * holding the notify-insertion lock. However, this could result in
2239  * creating a snapshot, so we must do it before serializable cleanup.
2240  */
2241  PreCommit_Notify();
2242 
2243  /*
2244  * Mark serializable transaction as complete for predicate locking
2245  * purposes. This should be done as late as we can put it and still allow
2246  * errors to be raised for failure patterns found at commit. This is not
2247  * appropriate in a parallel worker however, because we aren't committing
2248  * the leader's transaction and its serializable state will live on.
2249  */
2250  if (!is_parallel_worker)
2252 
2253  /* Prevent cancel/die interrupt while cleaning up */
2254  HOLD_INTERRUPTS();
2255 
2256  /* Commit updates to the relation map --- do this as late as possible */
2257  AtEOXact_RelationMap(true, is_parallel_worker);
2258 
2259  /*
2260  * set the current transaction state information appropriately during
2261  * commit processing
2262  */
2263  s->state = TRANS_COMMIT;
2264  s->parallelModeLevel = 0;
2265 
2266  /* Disable transaction timeout */
2267  if (TransactionTimeout > 0)
2269 
2270  if (!is_parallel_worker)
2271  {
2272  /*
2273  * We need to mark our XIDs as committed in pg_xact. This is where we
2274  * durably commit.
2275  */
2276  latestXid = RecordTransactionCommit();
2277  }
2278  else
2279  {
2280  /*
2281  * We must not mark our XID committed; the parallel leader is
2282  * responsible for that.
2283  */
2284  latestXid = InvalidTransactionId;
2285 
2286  /*
2287  * Make sure the leader will know about any WAL we wrote before it
2288  * commits.
2289  */
2291  }
2292 
2293  TRACE_POSTGRESQL_TRANSACTION_COMMIT(MyProc->vxid.lxid);
2294 
2295  /*
2296  * Let others know about no transaction in progress by me. Note that this
2297  * must be done _before_ releasing locks we hold and _after_
2298  * RecordTransactionCommit.
2299  */
2300  ProcArrayEndTransaction(MyProc, latestXid);
2301 
2302  /*
2303  * This is all post-commit cleanup. Note that if an error is raised here,
2304  * it's too late to abort the transaction. This should be just
2305  * noncritical resource releasing.
2306  *
2307  * The ordering of operations is not entirely random. The idea is:
2308  * release resources visible to other backends (eg, files, buffer pins);
2309  * then release locks; then release backend-local resources. We want to
2310  * release locks at the point where any backend waiting for us will see
2311  * our transaction as being fully cleaned up.
2312  *
2313  * Resources that can be associated with individual queries are handled by
2314  * the ResourceOwner mechanism. The other calls here are for backend-wide
2315  * state.
2316  */
2317 
2318  CallXactCallbacks(is_parallel_worker ? XACT_EVENT_PARALLEL_COMMIT
2319  : XACT_EVENT_COMMIT);
2320 
2321  CurrentResourceOwner = NULL;
2324  true, true);
2325 
2326  /* Check we've released all buffer pins */
2327  AtEOXact_Buffers(true);
2328 
2329  /* Clean up the relation cache */
2330  AtEOXact_RelationCache(true);
2331 
2332  /*
2333  * Make catalog changes visible to all backends. This has to happen after
2334  * relcache references are dropped (see comments for
2335  * AtEOXact_RelationCache), but before locks are released (if anyone is
2336  * waiting for lock on a relation we've modified, we want them to know
2337  * about the catalog change before they start using the relation).
2338  */
2339  AtEOXact_Inval(true);
2340 
2342 
2345  true, true);
2348  true, true);
2349 
2350  /*
2351  * Likewise, dropping of files deleted during the transaction is best done
2352  * after releasing relcache and buffer pins. (This is not strictly
2353  * necessary during commit, since such pins should have been released
2354  * already, but this ordering is definitely critical during abort.) Since
2355  * this may take many seconds, also delay until after releasing locks.
2356  * Other backends will observe the attendant catalog changes and not
2357  * attempt to access affected files.
2358  */
2359  smgrDoPendingDeletes(true);
2360 
2361  /*
2362  * Send out notification signals to other backends (and do other
2363  * post-commit NOTIFY cleanup). This must not happen until after our
2364  * transaction is fully done from the viewpoint of other backends.
2365  */
2366  AtCommit_Notify();
2367 
2368  /*
2369  * Everything after this should be purely internal-to-this-backend
2370  * cleanup.
2371  */
2372  AtEOXact_GUC(true, 1);
2373  AtEOXact_SPI(true);
2374  AtEOXact_Enum();
2376  AtEOXact_Namespace(true, is_parallel_worker);
2377  AtEOXact_SMgr();
2378  AtEOXact_Files(true);
2380  AtEOXact_HashTables(true);
2381  AtEOXact_PgStat(true, is_parallel_worker);
2382  AtEOXact_Snapshot(true, false);
2383  AtEOXact_ApplyLauncher(true);
2386 
2388  s->curTransactionOwner = NULL;
2391 
2392  AtCommit_Memory();
2393 
2396  s->nestingLevel = 0;
2397  s->gucNestLevel = 0;
2398  s->childXids = NULL;
2399  s->nChildXids = 0;
2400  s->maxChildXids = 0;
2401 
2404 
2405  /*
2406  * done with commit processing, set current transaction state back to
2407  * default
2408  */
2409  s->state = TRANS_DEFAULT;
2410 
2412 }
void AtCommit_Notify(void)
Definition: async.c:971
void PreCommit_Notify(void)
Definition: async.c:864
void ParallelWorkerReportLastRecEnd(XLogRecPtr last_xlog_end)
Definition: parallel.c:1565
bool PreCommit_Portals(bool isPrepare)
Definition: portalmem.c:678
void PreCommit_CheckForSerializationFailure(void)
Definition: predicate.c:4685
void PreCommit_on_commit_actions(void)
Definition: tablecmds.c:17931
void AfterTriggerFireDeferred(void)
Definition: trigger.c:5204
void EnterParallelMode(void)
Definition: xact.c:1036
static TransactionId RecordTransactionCommit(void)
Definition: xact.c:1283
static void AtCommit_Memory(void)
Definition: xact.c:1556
@ XACT_EVENT_COMMIT
Definition: xact.h:128
@ XACT_EVENT_PARALLEL_PRE_COMMIT
Definition: xact.h:134
@ XACT_EVENT_PARALLEL_COMMIT
Definition: xact.h:129
@ XACT_EVENT_PRE_COMMIT
Definition: xact.h:133

References AfterTriggerEndXact(), AfterTriggerFireDeferred(), Assert(), AtCommit_Memory(), AtCommit_Notify(), AtEOXact_ApplyLauncher(), AtEOXact_Buffers(), AtEOXact_ComboCid(), AtEOXact_Enum(), AtEOXact_Files(), AtEOXact_GUC(), AtEOXact_HashTables(), AtEOXact_Inval(), AtEOXact_LargeObject(), AtEOXact_LogicalRepWorkers(), 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, disable_timeout(), elog, EnterParallelMode(), TransactionStateData::fullTransactionId, TransactionStateData::gucNestLevel, HOLD_INTERRUPTS, InvalidFullTransactionId, 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(), smgrDoPendingSyncs(), TransactionStateData::state, TransactionStateData::subTransactionId, TBLOCK_PARALLEL_INPROGRESS, TopTransactionResourceOwner, TRANS_COMMIT, TRANS_DEFAULT, TRANS_INPROGRESS, TRANSACTION_TIMEOUT, TransactionTimeout, TransStateAsString(), PGPROC::vxid, WARNING, XACT_EVENT_COMMIT, XACT_EVENT_PARALLEL_COMMIT, XACT_EVENT_PARALLEL_PRE_COMMIT, XACT_EVENT_PRE_COMMIT, XactLastRecEnd, and XactTopFullTransactionId.

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

◆ CommitTransactionCommand()

void CommitTransactionCommand ( void  )

Definition at line 3051 of file xact.c.

3052 {
3055 
3056  /* Must save in case we need to restore below */
3058 
3059  switch (s->blockState)
3060  {
3061  /*
3062  * These shouldn't happen. TBLOCK_DEFAULT means the previous
3063  * StartTransactionCommand didn't set the STARTED state
3064  * appropriately, while TBLOCK_PARALLEL_INPROGRESS should be ended
3065  * by EndParallelWorkerTransaction(), not this function.
3066  */
3067  case TBLOCK_DEFAULT:
3069  elog(FATAL, "CommitTransactionCommand: unexpected state %s",
3071  break;
3072 
3073  /*
3074  * If we aren't in a transaction block, just do our usual
3075  * transaction commit, and return to the idle state.
3076  */
3077  case TBLOCK_STARTED:
3080  break;
3081 
3082  /*
3083  * We are completing a "BEGIN TRANSACTION" command, so we change
3084  * to the "transaction block in progress" state and return. (We
3085  * assume the BEGIN did nothing to the database, so we need no
3086  * CommandCounterIncrement.)
3087  */
3088  case TBLOCK_BEGIN:
3090  break;
3091 
3092  /*
3093  * This is the case when we have finished executing a command
3094  * someplace within a transaction block. We increment the command
3095  * counter and return.
3096  */
3097  case TBLOCK_INPROGRESS:
3099  case TBLOCK_SUBINPROGRESS:
3101  break;
3102 
3103  /*
3104  * We are completing a "COMMIT" command. Do it and return to the
3105  * idle state.
3106  */
3107  case TBLOCK_END:
3110  if (s->chain)
3111  {
3112  StartTransaction();
3114  s->chain = false;
3116  }
3117  break;
3118 
3119  /*
3120  * Here we are in the middle of a transaction block but one of the
3121  * commands caused an abort so we do nothing but remain in the
3122  * abort state. Eventually we will get a ROLLBACK command.
3123  */
3124  case TBLOCK_ABORT:
3125  case TBLOCK_SUBABORT:
3126  break;
3127 
3128  /*
3129  * Here we were in an aborted transaction block and we just got
3130  * the ROLLBACK command from the user, so clean up the
3131  * already-aborted transaction and return to the idle state.
3132  */
3133  case TBLOCK_ABORT_END:
3136  if (s->chain)
3137  {
3138  StartTransaction();
3140  s->chain = false;
3142  }
3143  break;
3144 
3145  /*
3146  * Here we were in a perfectly good transaction block but the user
3147  * told us to ROLLBACK anyway. We have to abort the transaction
3148  * and then clean up.
3149  */
3150  case TBLOCK_ABORT_PENDING:
3151  AbortTransaction();
3154  if (s->chain)
3155  {
3156  StartTransaction();
3158  s->chain = false;
3160  }
3161  break;
3162 
3163  /*
3164  * We are completing a "PREPARE TRANSACTION" command. Do it and
3165  * return to the idle state.
3166  */
3167  case TBLOCK_PREPARE:
3170  break;
3171 
3172  /*
3173  * The user issued a SAVEPOINT inside a transaction block. Start a
3174  * subtransaction. (DefineSavepoint already did PushTransaction,
3175  * so as to have someplace to put the SUBBEGIN state.)
3176  */
3177  case TBLOCK_SUBBEGIN:
3180  break;
3181 
3182  /*
3183  * The user issued a RELEASE command, so we end the current
3184  * subtransaction and return to the parent transaction. The parent
3185  * might be ended too, so repeat till we find an INPROGRESS
3186  * transaction or subtransaction.
3187  */
3188  case TBLOCK_SUBRELEASE:
3189  do
3190  {
3192  s = CurrentTransactionState; /* changed by pop */
3193  } while (s->blockState == TBLOCK_SUBRELEASE);
3194 
3197  break;
3198 
3199  /*
3200  * The user issued a COMMIT, so we end the current subtransaction
3201  * hierarchy and perform final commit. We do this by rolling up
3202  * any subtransactions into their parent, which leads to O(N^2)
3203  * operations with respect to resource owners - this isn't that
3204  * bad until we approach a thousands of savepoints but is
3205  * necessary for correctness should after triggers create new
3206  * resource owners.
3207  */
3208  case TBLOCK_SUBCOMMIT:
3209  do
3210  {
3212  s = CurrentTransactionState; /* changed by pop */
3213  } while (s->blockState == TBLOCK_SUBCOMMIT);
3214  /* If we had a COMMIT command, finish off the main xact too */
3215  if (s->blockState == TBLOCK_END)
3216  {
3217  Assert(s->parent == NULL);
3220  if (s->chain)
3221  {
3222  StartTransaction();
3224  s->chain = false;
3226  }
3227  }
3228  else if (s->blockState == TBLOCK_PREPARE)
3229  {
3230  Assert(s->parent == NULL);
3233  }
3234  else
3235  elog(ERROR, "CommitTransactionCommand: unexpected state %s",
3237  break;
3238 
3239  /*
3240  * The current already-failed subtransaction is ending due to a
3241  * ROLLBACK or ROLLBACK TO command, so pop it and recursively
3242  * examine the parent (which could be in any of several states).
3243  */
3244  case TBLOCK_SUBABORT_END:
3247  break;
3248 
3249  /*
3250  * As above, but it's not dead yet, so abort first.
3251  */
3256  break;
3257 
3258  /*
3259  * The current subtransaction is the target of a ROLLBACK TO
3260  * command. Abort and pop it, then start a new subtransaction
3261  * with the same name.
3262  */
3263  case TBLOCK_SUBRESTART:
3264  {
3265  char *name;
3266  int savepointLevel;
3267 
3268  /* save name and keep Cleanup from freeing it */
3269  name = s->name;
3270  s->name = NULL;
3271  savepointLevel = s->savepointLevel;
3272 
3275 
3276  DefineSavepoint(NULL);
3277  s = CurrentTransactionState; /* changed by push */
3278  s->name = name;
3279  s->savepointLevel = savepointLevel;
3280 
3281  /* This is the same as TBLOCK_SUBBEGIN case */
3285  }
3286  break;
3287 
3288  /*
3289  * Same as above, but the subtransaction had already failed, so we
3290  * don't need AbortSubTransaction.
3291  */
3293  {
3294  char *name;
3295  int savepointLevel;
3296 
3297  /* save name and keep Cleanup from freeing it */
3298  name = s->name;
3299  s->name = NULL;
3300  savepointLevel = s->savepointLevel;
3301 
3303 
3304  DefineSavepoint(NULL);
3305  s = CurrentTransactionState; /* changed by push */
3306  s->name = name;
3307  s->savepointLevel = savepointLevel;
3308 
3309  /* This is the same as TBLOCK_SUBBEGIN case */
3313  }
3314  break;
3315  }
3316 }
void SaveTransactionCharacteristics(SavedTransactionCharacteristics *s)
Definition: xact.c:3031
void RestoreTransactionCharacteristics(const SavedTransactionCharacteristics *s)
Definition: xact.c:3039
static void StartTransaction(void)
Definition: xact.c:1993
void DefineSavepoint(const char *name)
Definition: xact.c:4236
static void CommitSubTransaction(void)
Definition: xact.c:4966
static void CommitTransaction(void)
Definition: xact.c:2157
static void PrepareTransaction(void)
Definition: xact.c:2421
static void StartSubTransaction(void)
Definition: xact.c:4929

References AbortSubTransaction(), AbortTransaction(), Assert(), TransactionStateData::blockState, BlockStateAsString(), TransactionStateData::chain, CleanupSubTransaction(), CleanupTransaction(), CommandCounterIncrement(), CommitSubTransaction(), CommitTransaction(), CurrentTransactionState, DefineSavepoint(), elog, ERROR, FATAL, TransactionStateData::name, name, TransactionStateData::parent, PrepareTransaction(), RestoreTransactionCharacteristics(), TransactionStateData::savepointLevel, SaveTransactionCharacteristics(), StartSubTransaction(), StartTransaction(), 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 _SPI_commit(), AllTablesyncsReady(), apply_handle_commit_internal(), apply_handle_commit_prepared(), apply_handle_prepare(), apply_handle_prepare_internal(), apply_handle_rollback_prepared(), apply_handle_stream_prepare(), ATExecDetachPartition(), autoprewarm_database_main(), bbsink_server_new(), BeginInternalSubTransaction(), BootstrapModeMain(), clear_subscription_skip_lsn(), cluster_multiple_rels(), DefineIndex(), DisableSubscriptionAndExit(), do_autovacuum(), EventTriggerOnLogin(), exec_replication_command(), finish_xact_command(), get_database_list(), get_subscription_list(), IdentifySystem(), index_drop(), initialize_worker_spi(), InitializeLogRepWorker(), InitPostgres(), LogicalRepSyncTableStart(), maybe_reread_subscription(), movedb(), pa_start_subtrans(), pa_stream_abort(), ParallelApplyWorkerMain(), ParallelWorkerMain(), pg_attribute_noreturn(), process_syncing_tables_for_apply(), process_syncing_tables_for_sync(), ProcessCatchupInterrupt(), ProcessIncomingNotify(), ReindexMultipleInternal(), ReindexRelationConcurrently(), RemoveTempRelationsCallback(), run_apply_worker(), shell_check_detail(), stream_abort_internal(), stream_stop_internal(), synchronize_slots(), vacuum(), vacuum_rel(), validate_remote_info(), and worker_spi_main().

◆ DefineSavepoint()

void DefineSavepoint ( const char *  name)

Definition at line 4236 of file xact.c.

4237 {
4239 
4240  /*
4241  * Workers synchronize transaction state at the beginning of each parallel
4242  * operation, so we can't account for new subtransactions after that
4243  * point. (Note that this check will certainly error out if s->blockState
4244  * is TBLOCK_PARALLEL_INPROGRESS, so we can treat that as an invalid case
4245  * below.)
4246  */
4247  if (IsInParallelMode())
4248  ereport(ERROR,
4249  (errcode(ERRCODE_INVALID_TRANSACTION_STATE),
4250  errmsg("cannot define savepoints during a parallel operation")));
4251 
4252  switch (s->blockState)
4253  {
4254  case TBLOCK_INPROGRESS:
4255  case TBLOCK_SUBINPROGRESS:
4256  /* Normal subtransaction start */
4257  PushTransaction();
4258  s = CurrentTransactionState; /* changed by push */
4259 
4260  /*
4261  * Savepoint names, like the TransactionState block itself, live
4262  * in TopTransactionContext.
4263  */
4264  if (name)
4266  break;
4267 
4268  /*
4269  * We disallow savepoint commands in implicit transaction blocks.
4270  * There would be no great difficulty in allowing them so far as
4271  * this module is concerned, but a savepoint seems inconsistent
4272  * with exec_simple_query's behavior of abandoning the whole query
4273  * string upon error. Also, the point of an implicit transaction
4274  * block (as opposed to a regular one) is to automatically close
4275  * after an error, so it's hard to see how a savepoint would fit
4276  * into that.
4277  *
4278  * The error messages for this are phrased as if there were no
4279  * active transaction block at all, which is historical but
4280  * perhaps could be improved.
4281  */
4283  ereport(ERROR,
4284  (errcode(ERRCODE_NO_ACTIVE_SQL_TRANSACTION),
4285  /* translator: %s represents an SQL statement name */
4286  errmsg("%s can only be used in transaction blocks",
4287  "SAVEPOINT")));
4288  break;
4289 
4290  /* These cases are invalid. */
4291  case TBLOCK_DEFAULT:
4292  case TBLOCK_STARTED:
4293  case TBLOCK_BEGIN:
4295  case TBLOCK_SUBBEGIN:
4296  case TBLOCK_END:
4297  case TBLOCK_SUBRELEASE:
4298  case TBLOCK_SUBCOMMIT:
4299  case TBLOCK_ABORT:
4300  case TBLOCK_SUBABORT:
4301  case TBLOCK_ABORT_END:
4302  case TBLOCK_SUBABORT_END:
4303  case TBLOCK_ABORT_PENDING:
4305  case TBLOCK_SUBRESTART:
4307  case TBLOCK_PREPARE:
4308  elog(FATAL, "DefineSavepoint: unexpected state %s",
4310  break;
4311  }
4312 }

References TransactionStateData::blockState, BlockStateAsString(), CurrentTransactionState, elog, ereport, errcode(), errmsg(), ERROR, FATAL, IsInParallelMode(), MemoryContextStrdup(), TransactionStateData::name, 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(), pa_start_subtrans(), and standard_ProcessUtility().

◆ EndImplicitTransactionBlock()

void EndImplicitTransactionBlock ( void  )

Definition at line 4214 of file xact.c.

4215 {
4217 
4218  /*
4219  * If we are in IMPLICIT_INPROGRESS state, switch back to STARTED state,
4220  * allowing CommitTransactionCommand to commit whatever happened during
4221  * the implicit transaction block as though it were a single statement.
4222  *
4223  * For caller convenience, we consider all other transaction states as
4224  * legal here; otherwise the caller would need its own state check, which
4225  * seems rather pointless.
4226  */
4229 }

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

Referenced by exec_simple_query().

◆ EndParallelWorkerTransaction()

◆ EndTransactionBlock()

bool EndTransactionBlock ( bool  chain)

Definition at line 3907 of file xact.c.

3908 {
3910  bool result = false;
3911 
3912  switch (s->blockState)
3913  {
3914  /*
3915  * We are in a transaction block, so tell CommitTransactionCommand
3916  * to COMMIT.
3917  */
3918  case TBLOCK_INPROGRESS:
3919  s->blockState = TBLOCK_END;
3920  result = true;
3921  break;
3922 
3923  /*
3924  * We are in an implicit transaction block. If AND CHAIN was
3925  * specified, error. Otherwise commit, but issue a warning
3926  * because there was no explicit BEGIN before this.
3927  */
3929  if (chain)
3930  ereport(ERROR,
3931  (errcode(ERRCODE_NO_ACTIVE_SQL_TRANSACTION),
3932  /* translator: %s represents an SQL statement name */
3933  errmsg("%s can only be used in transaction blocks",
3934  "COMMIT AND CHAIN")));
3935  else
3936  ereport(WARNING,
3937  (errcode(ERRCODE_NO_ACTIVE_SQL_TRANSACTION),
3938  errmsg("there is no transaction in progress")));
3939  s->blockState = TBLOCK_END;
3940  result = true;
3941  break;
3942 
3943  /*
3944  * We are in a failed transaction block. Tell
3945  * CommitTransactionCommand it's time to exit the block.
3946  */
3947  case TBLOCK_ABORT:
3949  break;
3950 
3951  /*
3952  * We are in a live subtransaction block. Set up to subcommit all
3953  * open subtransactions and then commit the main transaction.
3954  */
3955  case TBLOCK_SUBINPROGRESS:
3956  while (s->parent != NULL)
3957  {
3958  if (s->blockState == TBLOCK_SUBINPROGRESS)
3960  else
3961  elog(FATAL, "EndTransactionBlock: unexpected state %s",
3963  s = s->parent;
3964  }
3965  if (s->blockState == TBLOCK_INPROGRESS)
3966  s->blockState = TBLOCK_END;
3967  else
3968  elog(FATAL, "EndTransactionBlock: unexpected state %s",
3970  result = true;
3971  break;
3972 
3973  /*
3974  * Here we are inside an aborted subtransaction. Treat the COMMIT
3975  * as ROLLBACK: set up to abort everything and exit the main
3976  * transaction.
3977  */
3978  case TBLOCK_SUBABORT:
3979  while (s->parent != NULL)
3980  {
3981  if (s->blockState == TBLOCK_SUBINPROGRESS)
3983  else if (s->blockState == TBLOCK_SUBABORT)
3985  else
3986  elog(FATAL, "EndTransactionBlock: unexpected state %s",
3988  s = s->parent;
3989  }
3990  if (s->blockState == TBLOCK_INPROGRESS)
3992  else if (s->blockState == TBLOCK_ABORT)
3994  else
3995  elog(FATAL, "EndTransactionBlock: unexpected state %s",
3997  break;
3998 
3999  /*
4000  * The user issued COMMIT when not inside a transaction. For
4001  * COMMIT without CHAIN, issue a WARNING, staying in
4002  * TBLOCK_STARTED state. The upcoming call to
4003  * CommitTransactionCommand() will then close the transaction and
4004  * put us back into the default state. For COMMIT AND CHAIN,
4005  * error.
4006  */
4007  case TBLOCK_STARTED:
4008  if (chain)
4009  ereport(ERROR,
4010  (errcode(ERRCODE_NO_ACTIVE_SQL_TRANSACTION),
4011  /* translator: %s represents an SQL statement name */
4012  errmsg("%s can only be used in transaction blocks",
4013  "COMMIT AND CHAIN")));
4014  else
4015  ereport(WARNING,
4016  (errcode(ERRCODE_NO_ACTIVE_SQL_TRANSACTION),
4017  errmsg("there is no transaction in progress")));
4018  result = true;
4019  break;
4020 
4021  /*
4022  * The user issued a COMMIT that somehow ran inside a parallel
4023  * worker. We can't cope with that.
4024  */
4026  ereport(FATAL,
4027  (errcode(ERRCODE_INVALID_TRANSACTION_STATE),
4028  errmsg("cannot commit during a parallel operation")));
4029  break;
4030 
4031  /* These cases are invalid. */
4032  case TBLOCK_DEFAULT:
4033  case TBLOCK_BEGIN:
4034  case TBLOCK_SUBBEGIN:
4035  case TBLOCK_END:
4036  case TBLOCK_SUBRELEASE:
4037  case TBLOCK_SUBCOMMIT:
4038  case TBLOCK_ABORT_END:
4039  case TBLOCK_SUBABORT_END:
4040  case TBLOCK_ABORT_PENDING:
4042  case TBLOCK_SUBRESTART:
4044  case TBLOCK_PREPARE:
4045  elog(FATAL, "EndTransactionBlock: unexpected state %s",
4047  break;
4048  }
4049 
4051  s->blockState == TBLOCK_END ||
4052  s->blockState == TBLOCK_ABORT_END ||
4054 
4055  s->chain = chain;
4056 
4057  return result;
4058 }

References Assert(), TransactionStateData::blockState, BlockStateAsString(), TransactionStateData::chain, CurrentTransactionState, elog, ereport, errcode(), errmsg(), ERROR, 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 apply_handle_commit_internal(), pa_stream_abort(), PrepareTransactionBlock(), and standard_ProcessUtility().

◆ EnterParallelMode()

void EnterParallelMode ( void  )

◆ EstimateTransactionStateSpace()

Size EstimateTransactionStateSpace ( void  )

Definition at line 5375 of file xact.c.

5376 {
5377  TransactionState s;
5378  Size nxids = 0;
5380 
5381  for (s = CurrentTransactionState; s != NULL; s = s->parent)
5382  {
5384  nxids = add_size(nxids, 1);
5385  nxids = add_size(nxids, s->nChildXids);
5386  }
5387 
5388  return add_size(size, mul_size(sizeof(TransactionId), nxids));
5389 }
size_t Size
Definition: c.h:592
Size add_size(Size s1, Size s2)
Definition: shmem.c:494
Size mul_size(Size s1, Size s2)
Definition: shmem.c:511
static pg_noinline void Size size
Definition: slab.c:607
#define SerializedTransactionStateHeaderSize
Definition: xact.c:233

References add_size(), CurrentTransactionState, TransactionStateData::fullTransactionId, FullTransactionIdIsValid, mul_size(), TransactionStateData::nChildXids, TransactionStateData::parent, SerializedTransactionStateHeaderSize, and size.

Referenced by InitializeParallelDSM().

◆ ExitParallelMode()

void ExitParallelMode ( void  )

◆ ForceSyncCommit()

void ForceSyncCommit ( void  )

Definition at line 1128 of file xact.c.

1129 {
1130  forceSyncCommit = true;
1131 }
static bool forceSyncCommit
Definition: xact.c:287

References forceSyncCommit.

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

◆ GetCurrentCommandId()

CommandId GetCurrentCommandId ( bool  used)

Definition at line 818 of file xact.c.

819 {
820  /* this is global to a transaction, not subtransaction-local */
821  if (used)
822  {
823  /*
824  * Forbid setting currentCommandIdUsed in a parallel worker, because
825  * we have no provision for communicating this back to the leader. We
826  * could relax this restriction when currentCommandIdUsed was already
827  * true at the start of the parallel operation.
828  */
830  currentCommandIdUsed = true;
831  }
832  return currentCommandId;
833 }

References Assert(), currentCommandId, currentCommandIdUsed, and IsParallelWorker.

Referenced by ATRewriteTable(), CatalogTuplesMultiInsertWithInfo(), CopyFrom(), create_edata_for_relation(), create_estate_for_relation(), GetSnapshotData(), GetSnapshotDataReuse(), intorel_startup(), pgrowlocks(), RegisterRelcacheInvalidation(), RelationFindReplTupleByIndex(), RelationFindReplTupleSeq(), simple_heap_delete(), simple_heap_insert(), simple_heap_update(), simple_table_tuple_delete(), simple_table_tuple_insert(), simple_table_tuple_update(), standard_ExecutorStart(), toast_save_datum(), transientrel_startup(), and UpdateActiveSnapshotCommandId().

◆ GetCurrentFullTransactionId()

FullTransactionId GetCurrentFullTransactionId ( void  )

◆ GetCurrentFullTransactionIdIfAny()

FullTransactionId GetCurrentFullTransactionIdIfAny ( void  )

Definition at line 521 of file xact.c.

522 {
524 }

References CurrentTransactionState, and TransactionStateData::fullTransactionId.

◆ GetCurrentStatementStartTimestamp()

TimestampTz GetCurrentStatementStartTimestamp ( void  )

Definition at line 864 of file xact.c.

865 {
866  return stmtStartTimestamp;
867 }
static TimestampTz stmtStartTimestamp
Definition: xact.c:275

References stmtStartTimestamp.

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

◆ GetCurrentSubTransactionId()

◆ GetCurrentTransactionId()

◆ GetCurrentTransactionIdIfAny()

◆ GetCurrentTransactionNestLevel()

◆ GetCurrentTransactionStartTimestamp()

TimestampTz GetCurrentTransactionStartTimestamp ( void  )

Definition at line 855 of file xact.c.

856 {
857  return xactStartTimestamp;
858 }
static TimestampTz xactStartTimestamp
Definition: xact.c:274

References xactStartTimestamp.

Referenced by GetCurrentTimeUsec(), GetSQLCurrentTimestamp(), GetSQLLocalTimestamp(), InitializeParallelDSM(), now(), pg_timezone_abbrevs(), and timetz_zone().

◆ GetCurrentTransactionStopTimestamp()

TimestampTz GetCurrentTransactionStopTimestamp ( void  )

Definition at line 876 of file xact.c.

877 {
879 
880  /* should only be called after commit / abort processing */
881  Assert(s->state == TRANS_DEFAULT ||
882  s->state == TRANS_COMMIT ||
883  s->state == TRANS_ABORT ||
884  s->state == TRANS_PREPARE);
885 
886  if (xactStopTimestamp == 0)
888 
889  return xactStopTimestamp;
890 }
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1655
#define PG_USED_FOR_ASSERTS_ONLY
Definition: c.h:169
static TimestampTz xactStopTimestamp
Definition: xact.c:276

References Assert(), CurrentTransactionState, GetCurrentTimestamp(), PG_USED_FOR_ASSERTS_ONLY, TRANS_ABORT, TRANS_COMMIT, TRANS_DEFAULT, TRANS_PREPARE, and xactStopTimestamp.

Referenced by pgstat_relation_flush_cb(), pgstat_report_stat(), RecordTransactionAbort(), and RecordTransactionCommit().

◆ GetStableLatestTransactionId()

TransactionId GetStableLatestTransactionId ( void  )

Definition at line 598 of file xact.c.

599 {
601  static TransactionId stablexid = InvalidTransactionId;
602 
603  if (lxid != MyProc->vxid.lxid)
604  {
605  lxid = MyProc->vxid.lxid;
606  stablexid = GetTopTransactionIdIfAny();
607  if (!TransactionIdIsValid(stablexid))
608  stablexid = ReadNextTransactionId();
609  }
610 
611  Assert(TransactionIdIsValid(stablexid));
612 
613  return stablexid;
614 }
uint32 LocalTransactionId
Definition: c.h:641
#define InvalidLocalTransactionId
Definition: lock.h:65
static TransactionId ReadNextTransactionId(void)
Definition: transam.h:315
TransactionId GetTopTransactionIdIfAny(void)
Definition: xact.c:432

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

Referenced by xid_age().

◆ GetTopFullTransactionId()

◆ GetTopFullTransactionIdIfAny()

FullTransactionId GetTopFullTransactionIdIfAny ( void  )

Definition at line 490 of file xact.c.

491 {
493 }

References XactTopFullTransactionId.

Referenced by pg_current_xact_id_if_assigned().

◆ GetTopTransactionId()

◆ GetTopTransactionIdIfAny()

◆ IsAbortedTransactionBlockState()

◆ IsInParallelMode()

◆ IsInTransactionBlock()

bool IsInTransactionBlock ( bool  isTopLevel)

Definition at line 3629 of file xact.c.

3630 {
3631  /*
3632  * Return true on same conditions that would make
3633  * PreventInTransactionBlock error out
3634  */
3635  if (IsTransactionBlock())
3636  return true;
3637 
3638  if (IsSubTransaction())
3639  return true;
3640 
3642  return true;
3643 
3644  if (!isTopLevel)
3645  return true;
3646 
3649  return true;
3650 
3651  return false;
3652 }
int MyXactFlags
Definition: xact.c:136
#define XACT_FLAGS_PIPELINING
Definition: xact.h:121

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

Referenced by vacuum().

◆ IsSubTransaction()

◆ IsSubxactTopXidLogPending()

bool IsSubxactTopXidLogPending ( void  )

Definition at line 550 of file xact.c.

551 {
552  /* check whether it is already logged */
554  return false;
555 
556  /* wal_level has to be logical */
557  if (!XLogLogicalInfoActive())
558  return false;
559 
560  /* we need to be in a transaction state */
561  if (!IsTransactionState())
562  return false;
563 
564  /* it has to be a subtransaction */
565  if (!IsSubTransaction())
566  return false;
567 
568  /* the subtransaction has to have a XID assigned */
570  return false;
571 
572  return true;
573 }
bool IsTransactionState(void)
Definition: xact.c:378
TransactionId GetCurrentTransactionIdIfAny(void)
Definition: xact.c:462

References CurrentTransactionState, GetCurrentTransactionIdIfAny(), IsSubTransaction(), IsTransactionState(), TransactionStateData::topXidLogged, TransactionIdIsValid, and XLogLogicalInfoActive.

Referenced by MarkSubxactTopXidLogged(), and XLogRecordAssemble().

◆ IsTransactionBlock()

◆ IsTransactionOrTransactionBlock()

◆ IsTransactionState()

bool IsTransactionState ( void  )

Definition at line 378 of file xact.c.

379 {
381 
382  /*
383  * TRANS_DEFAULT and TRANS_ABORT are obviously unsafe states. However, we
384  * also reject the startup/shutdown states TRANS_START, TRANS_COMMIT,
385  * TRANS_PREPARE since it might be too soon or too late within those
386  * transition states to do anything interesting. Hence, the only "valid"
387  * state is TRANS_INPROGRESS.
388  */
389  return (s->state == TRANS_INPROGRESS);
390 }

References CurrentTransactionState, TransactionStateData::state, and TRANS_INPROGRESS.

Referenced by apply_handle_commit_internal(), apply_handle_origin(), assign_transaction_timeout(), begin_replication_step(), check_client_encoding(), check_default_table_access_method(), check_default_tablespace(), check_default_text_search_config(), check_role(), check_session_authorization(), check_temp_tablespaces(), check_transaction_isolation(), check_transaction_read_only(), clear_subscription_skip_lsn(), CreateInitDecodingContext(), ensure_last_message(), FetchTableStates(), InitializeClientEncoding(), IsSubxactTopXidLogPending(), LogicalRepApplyLoop(), LogLogicalMessage(), maybe_reread_subscription(), pa_send_data(), pa_start_subtrans(), pg_attribute_noreturn(), pg_do_encoding_conversion(), PrepareClientEncoding(), PrepareTempTablespaces(), process_syncing_tables_for_apply(), process_syncing_tables_for_sync(), RelationClearRelation(), RelationIdGetRelation(), RelationInitPhysicalAddr(), RelationReloadNailed(), replorigin_create(), replorigin_drop_by_name(), SearchCatCacheInternal(), SetMultiXactIdLimit(), SetTransactionIdLimit(), SnapBuildClearExportedSnapshot(), SocketBackend(), stream_stop_internal(), synchronize_slots(), and validate_remote_info().

◆ MarkCurrentTransactionIdLoggedIfAny()

void MarkCurrentTransactionIdLoggedIfAny ( void  )

◆ MarkSubxactTopXidLogged()

void MarkSubxactTopXidLogged ( void  )

Definition at line 582 of file xact.c.

583 {
585 
587 }
bool IsSubxactTopXidLogPending(void)
Definition: xact.c:550

References Assert(), CurrentTransactionState, IsSubxactTopXidLogPending(), and TransactionStateData::topXidLogged.

Referenced by XLogInsertRecord().

◆ PopTransaction()

static void PopTransaction ( void  )
static

Definition at line 5341 of file xact.c.

5342 {
5344 
5345  if (s->state != TRANS_DEFAULT)
5346  elog(WARNING, "PopTransaction while in %s state",
5348 
5349  if (s->parent == NULL)
5350  elog(FATAL, "PopTransaction with no parent");
5351 
5353 
5354  /* Let's just make sure CurTransactionContext is good */
5357 
5358  /* Ditto for ResourceOwner links */
5361 
5362  /* Free the old child structure */
5363  if (s->name)
5364  pfree(s->name);
5365  pfree(s);
5366 }

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

Referenced by CleanupSubTransaction(), and CommitSubTransaction().

◆ PrepareTransaction()

static void PrepareTransaction ( void  )
static

Definition at line 2421 of file xact.c.

2422 {
2425  GlobalTransaction gxact;
2426  TimestampTz prepared_at;
2427 
2429 
2430  ShowTransactionState("PrepareTransaction");
2431 
2432  /*
2433  * check the current transaction state
2434  */
2435  if (s->state != TRANS_INPROGRESS)
2436  elog(WARNING, "PrepareTransaction while in %s state",
2438  Assert(s->parent == NULL);
2439 
2440  /*
2441  * Do pre-commit processing that involves calling user-defined code, such
2442  * as triggers. Since closing cursors could queue trigger actions,
2443  * triggers could open cursors, etc, we have to keep looping until there's
2444  * nothing left to do.
2445  */
2446  for (;;)
2447  {
2448  /*
2449  * Fire all currently pending deferred triggers.
2450  */
2452 
2453  /*
2454  * Close open portals (converting holdable ones into static portals).
2455  * If there weren't any, we are done ... otherwise loop back to check
2456  * if they queued deferred triggers. Lather, rinse, repeat.
2457  */
2458  if (!PreCommit_Portals(true))
2459  break;
2460  }
2461 
2463 
2464  /*
2465  * The remaining actions cannot call any user-defined code, so it's safe
2466  * to start shutting down within-transaction services. But note that most
2467  * of this stuff could still throw an error, which would switch us into
2468  * the transaction-abort path.
2469  */
2470 
2471  /* Shut down the deferred-trigger manager */
2472  AfterTriggerEndXact(true);
2473 
2474  /*
2475  * Let ON COMMIT management do its thing (must happen after closing
2476  * cursors, to avoid dangling-reference problems)
2477  */
2479 
2480  /*
2481  * Synchronize files that are created and not WAL-logged during this
2482  * transaction. This must happen before EndPrepare(), so that we don't see
2483  * committed-but-broken files after a crash and COMMIT PREPARED.
2484  */
2485  smgrDoPendingSyncs(true, false);
2486 
2487  /* close large objects before lower-level cleanup */
2488  AtEOXact_LargeObject(true);
2489 
2490  /* NOTIFY requires no work at this point */
2491 
2492  /*
2493  * Mark serializable transaction as complete for predicate locking
2494  * purposes. This should be done as late as we can put it and still allow
2495  * errors to be raised for failure patterns found at commit.
2496  */
2498 
2499  /*
2500  * Don't allow PREPARE TRANSACTION if we've accessed a temporary table in
2501  * this transaction. Having the prepared xact hold locks on another
2502  * backend's temp table seems a bad idea --- for instance it would prevent
2503  * the backend from exiting. There are other problems too, such as how to
2504  * clean up the source backend's local buffers and ON COMMIT state if the
2505  * prepared xact includes a DROP of a temp table.
2506  *
2507  * Other objects types, like functions, operators or extensions, share the
2508  * same restriction as they should not be created, locked or dropped as
2509  * this can mess up with this session or even a follow-up session trying
2510  * to use the same temporary namespace.
2511  *
2512  * We must check this after executing any ON COMMIT actions, because they
2513  * might still access a temp relation.
2514  *
2515  * XXX In principle this could be relaxed to allow some useful special
2516  * cases, such as a temp table created and dropped all within the
2517  * transaction. That seems to require much more bookkeeping though.
2518  */
2520  ereport(ERROR,
2521  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2522  errmsg("cannot PREPARE a transaction that has operated on temporary objects")));
2523 
2524  /*
2525  * Likewise, don't allow PREPARE after pg_export_snapshot. This could be
2526  * supported if we added cleanup logic to twophase.c, but for now it
2527  * doesn't seem worth the trouble.
2528  */
2530  ereport(ERROR,
2531  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2532  errmsg("cannot PREPARE a transaction that has exported snapshots")));
2533 
2534  /* Prevent cancel/die interrupt while cleaning up */
2535  HOLD_INTERRUPTS();
2536 
2537  /*
2538  * set the current transaction state information appropriately during
2539  * prepare processing
2540  */
2541  s->state = TRANS_PREPARE;
2542 
2543  /* Disable transaction timeout */
2544  if (TransactionTimeout > 0)
2546 
2547  prepared_at = GetCurrentTimestamp();
2548 
2549  /*
2550  * Reserve the GID for this transaction. This could fail if the requested
2551  * GID is invalid or already in use.
2552  */
2553  gxact = MarkAsPreparing(xid, prepareGID, prepared_at,
2554  GetUserId(), MyDatabaseId);
2555  prepareGID = NULL;
2556 
2557  /*
2558  * Collect data for the 2PC state file. Note that in general, no actual
2559  * state change should happen in the called modules during this step,
2560  * since it's still possible to fail before commit, and in that case we
2561  * want transaction abort to be able to clean up. (In particular, the
2562  * AtPrepare routines may error out if they find cases they cannot
2563  * handle.) State cleanup should happen in the PostPrepare routines
2564  * below. However, some modules can go ahead and clear state here because
2565  * they wouldn't do anything with it during abort anyway.
2566  *
2567  * Note: because the 2PC state file records will be replayed in the same
2568  * order they are made, the order of these calls has to match the order in
2569  * which we want things to happen during COMMIT PREPARED or ROLLBACK
2570  * PREPARED; in particular, pay attention to whether things should happen
2571  * before or after releasing the transaction's locks.
2572  */
2573  StartPrepare(gxact);
2574 
2575  AtPrepare_Notify();
2576  AtPrepare_Locks();
2578  AtPrepare_PgStat();
2581 
2582  /*
2583  * Here is where we really truly prepare.
2584  *
2585  * We have to record transaction prepares even if we didn't make any
2586  * updates, because the transaction manager might get confused if we lose
2587  * a global transaction.
2588  */
2589  EndPrepare(gxact);
2590 
2591  /*
2592  * Now we clean up backend-internal state and release internal resources.
2593  */
2594 
2595  /* Reset XactLastRecEnd until the next transaction writes something */
2596  XactLastRecEnd = 0;
2597 
2598  /*
2599  * Transfer our locks to a dummy PGPROC. This has to be done before
2600  * ProcArrayClearTransaction(). Otherwise, a GetLockConflicts() would
2601  * conclude "xact already committed or aborted" for our locks.
2602  */
2603  PostPrepare_Locks(xid);
2604 
2605  /*
2606  * Let others know about no transaction in progress by me. This has to be
2607  * done *after* the prepared transaction has been marked valid, else
2608  * someone may think it is unlocked and recyclable.
2609  */
2611 
2612  /*
2613  * In normal commit-processing, this is all non-critical post-transaction
2614  * cleanup. When the transaction is prepared, however, it's important
2615  * that the locks and other per-backend resources are transferred to the
2616  * prepared transaction's PGPROC entry. Note that if an error is raised
2617  * here, it's too late to abort the transaction. XXX: This probably should
2618  * be in a critical section, to force a PANIC if any of this fails, but
2619  * that cure could be worse than the disease.
2620  */
2621 
2623 
2626  true, true);
2627 
2628  /* Check we've released all buffer pins */
2629  AtEOXact_Buffers(true);
2630 
2631  /* Clean up the relation cache */
2632  AtEOXact_RelationCache(true);
2633 
2634  /* notify doesn't need a postprepare call */
2635 
2637 
2639 
2640  PostPrepare_smgr();
2641 
2642  PostPrepare_MultiXact(xid);
2643 
2645 
2648  true, true);
2651  true, true);
2652 
2653  /*
2654  * Allow another backend to finish the transaction. After
2655  * PostPrepare_Twophase(), the transaction is completely detached from our
2656  * backend. The rest is just non-critical cleanup of backend-local state.
2657  */
2659 
2660  /* PREPARE acts the same as COMMIT as far as GUC is concerned */
2661  AtEOXact_GUC(true, 1);
2662  AtEOXact_SPI(true);
2663  AtEOXact_Enum();
2665  AtEOXact_Namespace(true, false);
2666  AtEOXact_SMgr();
2667  AtEOXact_Files(true);
2669  AtEOXact_HashTables(true);
2670  /* don't call AtEOXact_PgStat here; we fixed pgstat state above */
2671  AtEOXact_Snapshot(true, true);
2672  /* we treat PREPARE as ROLLBACK so far as waking workers goes */
2673  AtEOXact_ApplyLauncher(false);
2676 
2677  CurrentResourceOwner = NULL;
2679  s->curTransactionOwner = NULL;
2682 
2683  AtCommit_Memory();
2684 
2687  s->nestingLevel = 0;
2688  s->gucNestLevel = 0;
2689  s->childXids = NULL;
2690  s->nChildXids = 0;
2691  s->maxChildXids = 0;
2692 
2695 
2696  /*
2697  * done with 1st phase commit processing, set current transaction state
2698  * back to default
2699  */
2700  s->state = TRANS_DEFAULT;
2701 
2703 }
void AtPrepare_Notify(void)
Definition: async.c:839
int64 TimestampTz
Definition: timestamp.h:39
Oid MyDatabaseId
Definition: globals.c:90
void PostPrepare_Inval(void)
Definition: inval.c:864
void AtPrepare_Locks(void)
Definition: lock.c:3255
void PostPrepare_Locks(TransactionId xid)
Definition: lock.c:3351
Oid GetUserId(void)
Definition: miscinit.c:515
void AtPrepare_MultiXact(void)
Definition: multixact.c:1773
void PostPrepare_MultiXact(TransactionId xid)
Definition: multixact.c:1787
void AtPrepare_PgStat(void)
Definition: pgstat_xact.c:190
void PostPrepare_PgStat(void)
Definition: pgstat_xact.c:210
void AtPrepare_PredicateLocks(void)
Definition: predicate.c:4772
void PostPrepare_PredicateLocks(TransactionId xid)
Definition: predicate.c:4841
void ProcArrayClearTransaction(PGPROC *proc)
Definition: procarray.c:908
void AtPrepare_RelationMap(void)
Definition: relmapper.c:589
bool XactHasExportedSnapshots(void)
Definition: snapmgr.c:1561
void PostPrepare_smgr(void)
Definition: storage.c:893
void EndPrepare(GlobalTransaction gxact)
Definition: twophase.c:1161
void StartPrepare(GlobalTransaction gxact)
Definition: twophase.c:1068
void PostPrepare_Twophase(void)
Definition: twophase.c:347
GlobalTransaction MarkAsPreparing(TransactionId xid, const char *gid, TimestampTz prepared_at, Oid owner, Oid databaseid)
Definition: twophase.c:362
static char * prepareGID
Definition: xact.c:282
TransactionId GetCurrentTransactionId(void)
Definition: xact.c:445
@ XACT_EVENT_PRE_PREPARE
Definition: xact.h:135
@ XACT_EVENT_PREPARE
Definition: xact.h:132
#define XACT_FLAGS_ACCESSEDTEMPNAMESPACE
Definition: xact.h:102

References AfterTriggerEndXact(), AfterTriggerFireDeferred(), Assert(), AtCommit_Memory(), AtEOXact_ApplyLauncher(), AtEOXact_Buffers(), AtEOXact_ComboCid(), AtEOXact_Enum(), AtEOXact_Files(), AtEOXact_GUC(), AtEOXact_HashTables(), AtEOXact_LargeObject(), AtEOXact_LogicalRepWorkers(), 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(), CallXactCallbacks(), TransactionStateData::childXids, CurrentResourceOwner, CurrentTransactionState, TransactionStateData::curTransactionOwner, CurTransactionResourceOwner, disable_timeout(), elog, EndPrepare(), ereport, errcode(), errmsg(), ERROR, TransactionStateData::fullTransactionId, GetCurrentTimestamp(), GetCurrentTransactionId(), GetUserId(), TransactionStateData::gucNestLevel, HOLD_INTERRUPTS, InvalidFullTransactionId, InvalidSubTransactionId, 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(), smgrDoPendingSyncs(), StartPrepare(), TransactionStateData::state, TransactionStateData::subTransactionId, TopTransactionResourceOwner, TRANS_DEFAULT, TRANS_INPROGRESS, TRANS_PREPARE, TRANSACTION_TIMEOUT, TransactionTimeout, TransStateAsString(), WARNING, XACT_EVENT_PRE_PREPARE, XACT_EVENT_PREPARE, XACT_FLAGS_ACCESSEDTEMPNAMESPACE, XactHasExportedSnapshots(), XactLastRecEnd, and XactTopFullTransactionId.

Referenced by CommitTransactionCommand().

◆ PrepareTransactionBlock()

bool PrepareTransactionBlock ( const char *  gid)

Definition at line 3855 of file xact.c.

3856 {
3857  TransactionState s;
3858  bool result;
3859 
3860  /* Set up to commit the current transaction */
3861  result = EndTransactionBlock(false);
3862 
3863  /* If successful, change outer tblock state to PREPARE */
3864  if (result)
3865  {
3867 
3868  while (s->parent != NULL)
3869  s = s->parent;
3870 
3871  if (s->blockState == TBLOCK_END)
3872  {
3873  /* Save GID where PrepareTransaction can find it again */
3875 
3877  }
3878  else
3879  {
3880  /*
3881  * ignore case where we are not in a transaction;
3882  * EndTransactionBlock already issued a warning.
3883  */
3886  /* Don't send back a PREPARE result tag... */
3887  result = false;
3888  }
3889  }
3890 
3891  return result;
3892 }
bool EndTransactionBlock(bool chain)
Definition: xact.c:3907

References Assert(), TransactionStateData::blockState, CurrentTransactionState, EndTransactionBlock(), MemoryContextStrdup(), TransactionStateData::parent, prepareGID, TBLOCK_END, TBLOCK_IMPLICIT_INPROGRESS, TBLOCK_PREPARE, TBLOCK_STARTED, and TopTransactionContext.

Referenced by apply_handle_prepare_internal(), and standard_ProcessUtility().

◆ PreventInTransactionBlock()

void PreventInTransactionBlock ( bool  isTopLevel,
const char *  stmtType 
)

Definition at line 3498 of file xact.c.

3499 {
3500  /*
3501  * xact block already started?
3502  */
3503  if (IsTransactionBlock())
3504  ereport(ERROR,
3505  (errcode(ERRCODE_ACTIVE_SQL_TRANSACTION),
3506  /* translator: %s represents an SQL statement name */
3507  errmsg("%s cannot run inside a transaction block",
3508  stmtType)));
3509 
3510  /*
3511  * subtransaction?
3512  */
3513  if (IsSubTransaction())
3514  ereport(ERROR,
3515  (errcode(ERRCODE_ACTIVE_SQL_TRANSACTION),
3516  /* translator: %s represents an SQL statement name */
3517  errmsg("%s cannot run inside a subtransaction",
3518  stmtType)));
3519 
3520  /*
3521  * inside a pipeline that has started an implicit transaction?
3522  */
3524  ereport(ERROR,
3525  (errcode(ERRCODE_ACTIVE_SQL_TRANSACTION),
3526  /* translator: %s represents an SQL statement name */
3527  errmsg("%s cannot be executed within a pipeline",
3528  stmtType)));
3529 
3530  /*
3531  * inside a function call?
3532  */
3533  if (!isTopLevel)
3534  ereport(ERROR,
3535  (errcode(ERRCODE_ACTIVE_SQL_TRANSACTION),
3536  /* translator: %s represents an SQL statement name */
3537  errmsg("%s cannot be executed from a function", stmtType)));
3538 
3539  /* If we got past IsTransactionBlock test, should be in default state */
3542  elog(FATAL, "cannot prevent transaction chain");
3543 
3544  /* All okay. Set the flag to make sure the right thing happens later. */
3546 }
#define XACT_FLAGS_NEEDIMMEDIATECOMMIT
Definition: xact.h:114

References TransactionStateData::blockState, CurrentTransactionState, elog, ereport, errcode(), errmsg(), ERROR, FATAL, IsSubTransaction(), IsTransactionBlock(), MyXactFlags, TBLOCK_DEFAULT, TBLOCK_STARTED, XACT_FLAGS_NEEDIMMEDIATECOMMIT, and XACT_FLAGS_PIPELINING.

Referenced by AlterDatabase(), AlterSubscription(), cluster(), CreateSubscription(), DiscardAll(), DropSubscription(), exec_replication_command(), ExecDropStmt(), ExecReindex(), ProcessUtilitySlow(), ReindexPartitions(), standard_ProcessUtility(), and vacuum().

◆ PushTransaction()

static void PushTransaction ( void  )
static

Definition at line 5280 of file xact.c.

5281 {
5283  TransactionState s;
5284 
5285  /*
5286  * We keep subtransaction state nodes in TopTransactionContext.
5287  */
5288  s = (TransactionState)
5290  sizeof(TransactionStateData));
5291 
5292  /*
5293  * Assign a subtransaction ID, watching out for counter wraparound.
5294  */
5297  {
5299  pfree(s);
5300  ereport(ERROR,
5301  (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
5302  errmsg("cannot have more than 2^32-1 subtransactions in a transaction")));
5303  }
5304 
5305  /*
5306  * We can now stack a minimally valid subtransaction without fear of
5307  * failure.
5308  */
5309  s->fullTransactionId = InvalidFullTransactionId; /* until assigned */
5311  s->parent = p;
5312  s->nestingLevel = p->nestingLevel + 1;
5315  s->state = TRANS_DEFAULT;
5320  s->parallelModeLevel = 0;
5321  s->topXidLogged = false;
5322 
5324 
5325  /*
5326  * AbortSubTransaction and CleanupSubTransaction have to be able to cope
5327  * with the subtransaction from here on out; in particular they should not
5328  * assume that it necessarily has a transaction context, resource owner,
5329  * or XID.
5330  */
5331 }
int NewGUCNestLevel(void)
Definition: guc.c:2231
void * MemoryContextAllocZero(MemoryContext context, Size size)
Definition: mcxt.c:1100
void GetUserIdAndSecContext(Oid *userid, int *sec_context)
Definition: miscinit.c:636
bool startedInRecovery
Definition: xact.c:207
TransactionStateData * TransactionState
Definition: xact.c:215
static SubTransactionId currentSubTransactionId
Definition: xact.c:260

References TransactionStateData::blockState, currentSubTransactionId, CurrentTransactionState, ereport, errcode(), errmsg(), ERROR, TransactionStateData::fullTransactionId, GetUserIdAndSecContext(), TransactionStateData::gucNestLevel, InvalidFullTransactionId, InvalidSubTransactionId, MemoryContextAllocZero(), TransactionStateData::nestingLevel, NewGUCNestLevel(), TransactionStateData::parallelModeLevel, TransactionStateData::parent, pfree(), TransactionStateData::prevSecContext, TransactionStateData::prevUser, TransactionStateData::prevXactReadOnly, TransactionStateData::savepointLevel, TransactionStateData::startedInRecovery, TransactionStateData::state, TransactionStateData::subTransactionId, TBLOCK_SUBBEGIN, TopTransactionContext, TransactionStateData::topXidLogged, TRANS_DEFAULT, and XactReadOnly.

Referenced by BeginInternalSubTransaction(), and DefineSavepoint().

◆ RecordTransactionAbort()

static TransactionId RecordTransactionAbort ( bool  isSubXact)
static

Definition at line 1702 of file xact.c.

1703 {
1705  TransactionId latestXid;
1706  int nrels;
1707  RelFileLocator *rels;
1708  int ndroppedstats = 0;
1709  xl_xact_stats_item *droppedstats = NULL;
1710  int nchildren;
1711  TransactionId *children;
1712  TimestampTz xact_time;
1713  bool replorigin;
1714 
1715  /*
1716  * If we haven't been assigned an XID, nobody will care whether we aborted
1717  * or not. Hence, we're done in that case. It does not matter if we have
1718  * rels to delete (note that this routine is not responsible for actually
1719  * deleting 'em). We cannot have any child XIDs, either.
1720  */
1721  if (!TransactionIdIsValid(xid))
1722  {
1723  /* Reset XactLastRecEnd until the next transaction writes something */
1724  if (!isSubXact)
1725  XactLastRecEnd = 0;
1726  return InvalidTransactionId;
1727  }
1728 
1729  /*
1730  * We have a valid XID, so we should write an ABORT record for it.
1731  *
1732  * We do not flush XLOG to disk here, since the default assumption after a
1733  * crash would be that we aborted, anyway. For the same reason, we don't
1734  * need to worry about interlocking against checkpoint start.
1735  */
1736 
1737  /*
1738  * Check that we haven't aborted halfway through RecordTransactionCommit.
1739  */
1740  if (TransactionIdDidCommit(xid))
1741  elog(PANIC, "cannot abort transaction %u, it was already committed",
1742  xid);
1743 
1744  /*
1745  * Are we using the replication origins feature? Or, in other words, are
1746  * we replaying remote actions?
1747  */
1748  replorigin = (replorigin_session_origin != InvalidRepOriginId &&
1750 
1751  /* Fetch the data we need for the abort record */
1752  nrels = smgrGetPendingDeletes(false, &rels);
1753  nchildren = xactGetCommittedChildren(&children);
1754  ndroppedstats = pgstat_get_transactional_drops(false, &droppedstats);
1755 
1756  /* XXX do we really need a critical section here? */
1758 
1759  /* Write the ABORT record */
1760  if (isSubXact)
1761  xact_time = GetCurrentTimestamp();
1762  else
1763  {
1764  xact_time = GetCurrentTransactionStopTimestamp();
1765  }
1766 
1767  XactLogAbortRecord(xact_time,
1768  nchildren, children,
1769  nrels, rels,
1770  ndroppedstats, droppedstats,
1772  NULL);
1773 
1774  if (replorigin)
1775  /* Move LSNs forward for this replication origin */
1777  XactLastRecEnd);
1778 
1779  /*
1780  * Report the latest async abort LSN, so that the WAL writer knows to
1781  * flush this abort. There's nothing to be gained by delaying this, since
1782  * WALWriter may as well do this when it can. This is important with
1783  * streaming replication because if we don't flush WAL regularly we will
1784  * find that large aborts leave us with a long backlog for when commits
1785  * occur after the abort, increasing our window of data loss should
1786  * problems occur at that point.
1787  */
1788  if (!isSubXact)
1790 
1791  /*
1792  * Mark the transaction aborted in clog. This is not absolutely necessary
1793  * but we may as well do it while we are here; also, in the subxact case
1794  * it is helpful because XactLockTableWait makes use of it to avoid
1795  * waiting for already-aborted subtransactions. It is OK to do it without
1796  * having flushed the ABORT record to disk, because in event of a crash
1797  * we'd be assumed to have aborted anyway.
1798  */
1799  TransactionIdAbortTree(xid, nchildren, children);
1800 
1801  END_CRIT_SECTION();
1802 
1803  /* Compute latestXid while we have the child XIDs handy */
1804  latestXid = TransactionIdLatest(xid, nchildren, children);
1805 
1806  /*
1807  * If we're aborting a subtransaction, we can immediately remove failed
1808  * XIDs from PGPROC's cache of running child XIDs. We do that here for
1809  * subxacts, because we already have the child XID array at hand. For
1810  * main xacts, the equivalent happens just after this function returns.
1811  */
1812  if (isSubXact)
1813  XidCacheRemoveRunningXids(xid, nchildren, children, latestXid);
1814 
1815  /* Reset XactLastRecEnd until the next transaction writes something */
1816  if (!isSubXact)
1817  XactLastRecEnd = 0;
1818 
1819  /* And clean up local data */
1820  if (rels)
1821  pfree(rels);
1822  if (ndroppedstats)
1823  pfree(droppedstats);
1824 
1825  return latestXid;
1826 }
#define PANIC
Definition: elog.h:42
#define START_CRIT_SECTION()
Definition: miscadmin.h:149
#define END_CRIT_SECTION()
Definition: miscadmin.h:151
void replorigin_session_advance(XLogRecPtr remote_commit, XLogRecPtr local_commit)
Definition: origin.c:1220
RepOriginId replorigin_session_origin
Definition: origin.c:156
XLogRecPtr replorigin_session_origin_lsn
Definition: origin.c:157
#define DoNotReplicateId
Definition: origin.h:34
#define InvalidRepOriginId
Definition: origin.h:33
int pgstat_get_transactional_drops(bool isCommit, xl_xact_stats_item **items)
Definition: pgstat_xact.c:271
void XidCacheRemoveRunningXids(TransactionId xid, int nxids, const TransactionId *xids, TransactionId latestXid)
Definition: procarray.c:3965
int smgrGetPendingDeletes(bool forCommit, RelFileLocator **ptr)
Definition: storage.c:852
TransactionId TransactionIdLatest(TransactionId mainxid, int nxids, const TransactionId *xids)
Definition: transam.c:345
bool TransactionIdDidCommit(TransactionId transactionId)
Definition: transam.c:126
void TransactionIdAbortTree(TransactionId xid, int nxids, TransactionId *xids)
Definition: transam.c:270
int xactGetCommittedChildren(TransactionId **ptr)
Definition: xact.c:5644
TimestampTz GetCurrentTransactionStopTimestamp(void)
Definition: xact.c:876
XLogRecPtr XactLogAbortRecord(TimestampTz abort_time, int nsubxacts, TransactionId *subxacts, int nrels, RelFileLocator *rels, int ndroppedstats, xl_xact_stats_item *droppedstats, int xactflags, TransactionId twophase_xid, const char *twophase_gid)
Definition: xact.c:5840

References DoNotReplicateId, elog, END_CRIT_SECTION, GetCurrentTimestamp(), GetCurrentTransactionIdIfAny(), GetCurrentTransactionStopTimestamp(), InvalidRepOriginId, InvalidTransactionId, MyXactFlags, PANIC, pfree(), pgstat_get_transactional_drops(), replorigin_session_advance(), replorigin_session_origin, replorigin_session_origin_lsn, smgrGetPendingDeletes(), START_CRIT_SECTION, TransactionIdAbortTree(), TransactionIdDidCommit(), TransactionIdIsValid, TransactionIdLatest(), xactGetCommittedChildren(), XactLastRecEnd, XactLogAbortRecord(), XidCacheRemoveRunningXids(), and XLogSetAsyncXactLSN().

Referenced by AbortSubTransaction(), and AbortTransaction().

◆ RecordTransactionCommit()

static TransactionId RecordTransactionCommit ( void  )
static

Definition at line 1283 of file xact.c.

1284 {
1286  bool markXidCommitted = TransactionIdIsValid(xid);
1287  TransactionId latestXid = InvalidTransactionId;
1288  int nrels;
1289  RelFileLocator *rels;
1290  int nchildren;
1291  TransactionId *children;
1292  int ndroppedstats = 0;
1293  xl_xact_stats_item *droppedstats = NULL;
1294  int nmsgs = 0;
1295  SharedInvalidationMessage *invalMessages = NULL;
1296  bool RelcacheInitFileInval = false;
1297  bool wrote_xlog;
1298 
1299  /*
1300  * Log pending invalidations for logical decoding of in-progress
1301  * transactions. Normally for DDLs, we log this at each command end,
1302  * however, for certain cases where we directly update the system table
1303  * without a transaction block, the invalidations are not logged till this
1304  * time.
1305  */
1306  if (XLogLogicalInfoActive())
1308 
1309  /* Get data needed for commit record */
1310  nrels = smgrGetPendingDeletes(true, &rels);
1311  nchildren = xactGetCommittedChildren(&children);
1312  ndroppedstats = pgstat_get_transactional_drops(true, &droppedstats);
1313  if (XLogStandbyInfoActive())
1314  nmsgs = xactGetCommittedInvalidationMessages(&invalMessages,
1315  &RelcacheInitFileInval);
1316  wrote_xlog = (XactLastRecEnd != 0);
1317 
1318  /*
1319  * If we haven't been assigned an XID yet, we neither can, nor do we want
1320  * to write a COMMIT record.
1321  */
1322  if (!markXidCommitted)
1323  {
1324  /*
1325  * We expect that every RelationDropStorage is followed by a catalog
1326  * update, and hence XID assignment, so we shouldn't get here with any
1327  * pending deletes. Same is true for dropping stats.
1328  *
1329  * Use a real test not just an Assert to check this, since it's a bit
1330  * fragile.
1331  */
1332  if (nrels != 0 || ndroppedstats != 0)
1333  elog(ERROR, "cannot commit a transaction that deleted files but has no xid");
1334 
1335  /* Can't have child XIDs either; AssignTransactionId enforces this */
1336  Assert(nchildren == 0);
1337 
1338  /*
1339  * Transactions without an assigned xid can contain invalidation
1340  * messages (e.g. explicit relcache invalidations or catcache
1341  * invalidations for inplace updates); standbys need to process those.
1342  * We can't emit a commit record without an xid, and we don't want to
1343  * force assigning an xid, because that'd be problematic for e.g.
1344  * vacuum. Hence we emit a bespoke record for the invalidations. We
1345  * don't want to use that in case a commit record is emitted, so they
1346  * happen synchronously with commits (besides not wanting to emit more
1347  * WAL records).
1348  */
1349  if (nmsgs != 0)
1350  {
1351  LogStandbyInvalidations(nmsgs, invalMessages,
1352  RelcacheInitFileInval);
1353  wrote_xlog = true; /* not strictly necessary */
1354  }
1355 
1356  /*
1357  * If we didn't create XLOG entries, we're done here; otherwise we
1358  * should trigger flushing those entries the same as a commit record
1359  * would. This will primarily happen for HOT pruning and the like; we
1360  * want these to be flushed to disk in due time.
1361  */
1362  if (!wrote_xlog)
1363  goto cleanup;
1364  }
1365  else
1366  {
1367  bool replorigin;
1368 
1369  /*
1370  * Are we using the replication origins feature? Or, in other words,
1371  * are we replaying remote actions?
1372  */
1373  replorigin = (replorigin_session_origin != InvalidRepOriginId &&
1375 
1376  /*
1377  * Mark ourselves as within our "commit critical section". This
1378  * forces any concurrent checkpoint to wait until we've updated
1379  * pg_xact. Without this, it is possible for the checkpoint to set
1380  * REDO after the XLOG record but fail to flush the pg_xact update to
1381  * disk, leading to loss of the transaction commit if the system
1382  * crashes a little later.
1383  *
1384  * Note: we could, but don't bother to, set this flag in
1385  * RecordTransactionAbort. That's because loss of a transaction abort
1386  * is noncritical; the presumption would be that it aborted, anyway.
1387  *
1388  * It's safe to change the delayChkptFlags flag of our own backend
1389  * without holding the ProcArrayLock, since we're the only one
1390  * modifying it. This makes checkpoint's determination of which xacts
1391  * are delaying the checkpoint a bit fuzzy, but it doesn't matter.
1392  */
1396 
1397  /*
1398  * Insert the commit XLOG record.
1399  */
1401  nchildren, children, nrels, rels,
1402  ndroppedstats, droppedstats,
1403  nmsgs, invalMessages,
1404  RelcacheInitFileInval,
1405  MyXactFlags,
1406  InvalidTransactionId, NULL /* plain commit */ );
1407 
1408  if (replorigin)
1409  /* Move LSNs forward for this replication origin */
1411  XactLastRecEnd);
1412 
1413  /*
1414  * Record commit timestamp. The value comes from plain commit
1415  * timestamp if there's no replication origin; otherwise, the
1416  * timestamp was already set in replorigin_session_origin_timestamp by
1417  * replication.
1418  *
1419  * We don't need to WAL-log anything here, as the commit record
1420  * written above already contains the data.
1421  */
1422 
1423  if (!replorigin || replorigin_session_origin_timestamp == 0)
1425 
1426  TransactionTreeSetCommitTsData(xid, nchildren, children,
1429  }
1430 
1431  /*
1432  * Check if we want to commit asynchronously. We can allow the XLOG flush
1433  * to happen asynchronously if synchronous_commit=off, or if the current
1434  * transaction has not performed any WAL-logged operation or didn't assign
1435  * an xid. The transaction can end up not writing any WAL, even if it has
1436  * an xid, if it only wrote to temporary and/or unlogged tables. It can
1437  * end up having written WAL without an xid if it did HOT pruning. In
1438  * case of a crash, the loss of such a transaction will be irrelevant;
1439  * temp tables will be lost anyway, unlogged tables will be truncated and
1440  * HOT pruning will be done again later. (Given the foregoing, you might
1441  * think that it would be unnecessary to emit the XLOG record at all in
1442  * this case, but we don't currently try to do that. It would certainly
1443  * cause problems at least in Hot Standby mode, where the
1444  * KnownAssignedXids machinery requires tracking every XID assignment. It
1445  * might be OK to skip it only when wal_level < replica, but for now we
1446  * don't.)
1447  *
1448  * However, if we're doing cleanup of any non-temp rels or committing any
1449  * command that wanted to force sync commit, then we must flush XLOG
1450  * immediately. (We must not allow asynchronous commit if there are any
1451  * non-temp tables to be deleted, because we might delete the files before
1452  * the COMMIT record is flushed to disk. We do allow asynchronous commit
1453  * if all to-be-deleted tables are temporary though, since they are lost
1454  * anyway if we crash.)
1455  */
1456  if ((wrote_xlog && markXidCommitted &&
1458  forceSyncCommit || nrels > 0)
1459  {
1461 
1462  /*
1463  * Now we may update the CLOG, if we wrote a COMMIT record above
1464  */
1465  if (markXidCommitted)
1466  TransactionIdCommitTree(xid, nchildren, children);
1467  }
1468  else
1469  {
1470  /*
1471  * Asynchronous commit case:
1472  *
1473  * This enables possible committed transaction loss in the case of a
1474  * postmaster crash because WAL buffers are left unwritten. Ideally we
1475  * could issue the WAL write without the fsync, but some
1476  * wal_sync_methods do not allow separate write/fsync.
1477  *
1478  * Report the latest async commit LSN, so that the WAL writer knows to
1479  * flush this commit.
1480  */
1482 
1483  /*
1484  * We must not immediately update the CLOG, since we didn't flush the
1485  * XLOG. Instead, we store the LSN up to which the XLOG must be
1486  * flushed before the CLOG may be updated.
1487  */
1488  if (markXidCommitted)
1489  TransactionIdAsyncCommitTree(xid, nchildren, children, XactLastRecEnd);
1490  }
1491 
1492  /*
1493  * If we entered a commit critical section, leave it now, and let
1494  * checkpoints proceed.
1495  */
1496  if (markXidCommitted)
1497  {
1499  END_CRIT_SECTION();
1500  }
1501 
1502  /* Compute latestXid while we have the child XIDs handy */
1503  latestXid = TransactionIdLatest(xid, nchildren, children);
1504 
1505  /*
1506  * Wait for synchronous replication, if required. Similar to the decision
1507  * above about using committing asynchronously we only want to wait if
1508  * this backend assigned an xid and wrote WAL. No need to wait if an xid
1509  * was assigned due to temporary/unlogged tables or due to HOT pruning.
1510  *
1511  * Note that at this stage we have marked clog, but still show as running
1512  * in the procarray and continue to hold locks.
1513  */
1514  if (wrote_xlog && markXidCommitted)