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

Go to the source code of this file.

Data Structures

struct  TransactionStateData
 
struct  XactCallbackItem
 
struct  SubXactCallbackItem
 

Typedefs

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

Enumerations

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

Functions

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

Variables

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

Typedef Documentation

◆ SubXactCallbackItem

◆ TBlockState

◆ TransactionState

Definition at line 195 of file xact.c.

◆ TransactionStateData

◆ TransState

◆ XactCallbackItem

Enumeration Type Documentation

◆ TBlockState

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

Definition at line 139 of file xact.c.

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

◆ TransState

enum TransState
Enumerator
TRANS_DEFAULT 
TRANS_START 
TRANS_INPROGRESS 
TRANS_COMMIT 
TRANS_ABORT 
TRANS_PREPARE 

Definition at line 123 of file xact.c.

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

Function Documentation

◆ AbortCurrentTransaction()

void AbortCurrentTransaction ( void  )

Definition at line 2985 of file xact.c.

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

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

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

◆ AbortOutOfAnyTransaction()

void AbortOutOfAnyTransaction ( void  )

Definition at line 4344 of file xact.c.

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

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

4345 {
4347 
4348  /* Ensure we're not running in a doomed memory context */
4349  AtAbort_Memory();
4350 
4351  /*
4352  * Get out of any transaction or nested transaction
4353  */
4354  do
4355  {
4356  switch (s->blockState)
4357  {
4358  case TBLOCK_DEFAULT:
4359  if (s->state == TRANS_DEFAULT)
4360  {
4361  /* Not in a transaction, do nothing */
4362  }
4363  else
4364  {
4365  /*
4366  * We can get here after an error during transaction start
4367  * (state will be TRANS_START). Need to clean up the
4368  * incompletely started transaction. First, adjust the
4369  * low-level state to suppress warning message from
4370  * AbortTransaction.
4371  */
4372  if (s->state == TRANS_START)
4373  s->state = TRANS_INPROGRESS;
4374  AbortTransaction();
4376  }
4377  break;
4378  case TBLOCK_STARTED:
4379  case TBLOCK_BEGIN:
4380  case TBLOCK_INPROGRESS:
4383  case TBLOCK_END:
4384  case TBLOCK_ABORT_PENDING:
4385  case TBLOCK_PREPARE:
4386  /* In a transaction, so clean up */
4387  AbortTransaction();
4390  break;
4391  case TBLOCK_ABORT:
4392  case TBLOCK_ABORT_END:
4393 
4394  /*
4395  * AbortTransaction is already done, still need Cleanup.
4396  * However, if we failed partway through running ROLLBACK,
4397  * there will be an active portal running that command, which
4398  * we need to shut down before doing CleanupTransaction.
4399  */
4400  AtAbort_Portals();
4403  break;
4404 
4405  /*
4406  * In a subtransaction, so clean it up and abort parent too
4407  */
4408  case TBLOCK_SUBBEGIN:
4409  case TBLOCK_SUBINPROGRESS:
4410  case TBLOCK_SUBRELEASE:
4411  case TBLOCK_SUBCOMMIT:
4413  case TBLOCK_SUBRESTART:
4416  s = CurrentTransactionState; /* changed by pop */
4417  break;
4418 
4419  case TBLOCK_SUBABORT:
4420  case TBLOCK_SUBABORT_END:
4422  /* As above, but AbortSubTransaction already done */
4423  if (s->curTransactionOwner)
4424  {
4425  /* As in TBLOCK_ABORT, might have a live portal to zap */
4430  }
4432  s = CurrentTransactionState; /* changed by pop */
4433  break;
4434  }
4435  } while (s->blockState != TBLOCK_DEFAULT);
4436 
4437  /* Should be out of all subxacts now */
4438  Assert(s->parent == NULL);
4439 
4440  /* If we didn't actually have anything to do, revert to TopMemoryContext */
4441  AtCleanup_Memory();
4442 }
static TransactionState CurrentTransactionState
Definition: xact.c:233
static void AtCleanup_Memory(void)
Definition: xact.c:1725
void AtAbort_Portals(void)
Definition: portalmem.c:752
TBlockState blockState
Definition: xact.c:178
TransState state
Definition: xact.c:177
ResourceOwner curTransactionOwner
Definition: xact.c:182
static void CleanupTransaction(void)
Definition: xact.c:2625
struct TransactionStateData * parent
Definition: xact.c:192
SubTransactionId subTransactionId
Definition: xact.c:174
static void AbortSubTransaction(void)
Definition: xact.c:4690
static void AtAbort_Memory(void)
Definition: xact.c:1635
static void AbortTransaction(void)
Definition: xact.c:2445
#define Assert(condition)
Definition: c.h:680
void AtSubAbort_Portals(SubTransactionId mySubid, SubTransactionId parentSubid, ResourceOwner myXactOwner, ResourceOwner parentXactOwner)
Definition: portalmem.c:907
static void CleanupSubTransaction(void)
Definition: xact.c:4838

◆ AbortSubTransaction()

static void AbortSubTransaction ( void  )
static

Definition at line 4690 of file xact.c.

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

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

4691 {
4693 
4694  /* Prevent cancel/die interrupt while cleaning up */
4695  HOLD_INTERRUPTS();
4696 
4697  /* Make sure we have a valid memory context and resource owner */
4700 
4701  /*
4702  * Release any LW locks we might be holding as quickly as possible.
4703  * (Regular locks, however, must be held till we finish aborting.)
4704  * Releasing LW locks is critical since we might try to grab them again
4705  * while cleaning up!
4706  *
4707  * FIXME This may be incorrect --- Are there some locks we should keep?
4708  * Buffer locks, for example? I don't think so but I'm not sure.
4709  */
4710  LWLockReleaseAll();
4711 
4714  AbortBufferIO();
4715  UnlockBuffers();
4716 
4717  /* Reset WAL record construction state */
4719 
4720  /* Cancel condition variable sleep */
4722 
4723  /*
4724  * Also clean up any open wait for lock, since the lock manager will choke
4725  * if we try to wait for another lock before doing this.
4726  */
4727  LockErrorCleanup();
4728 
4729  /*
4730  * If any timeout events are still active, make sure the timeout interrupt
4731  * is scheduled. This covers possible loss of a timeout interrupt due to
4732  * longjmp'ing out of the SIGINT handler (see notes in handle_sig_alarm).
4733  * We delay this till after LockErrorCleanup so that we don't uselessly
4734  * reschedule lock or deadlock check timeouts.
4735  */
4737 
4738  /*
4739  * Re-enable signals, in case we got here by longjmp'ing out of a signal
4740  * handler. We do this fairly early in the sequence so that the timeout
4741  * infrastructure will be functional if needed while aborting.
4742  */
4744 
4745  /*
4746  * check the current transaction state
4747  */
4748  ShowTransactionState("AbortSubTransaction");
4749 
4750  if (s->state != TRANS_INPROGRESS)
4751  elog(WARNING, "AbortSubTransaction while in %s state",
4753 
4754  s->state = TRANS_ABORT;
4755 
4756  /*
4757  * Reset user ID which might have been changed transiently. (See notes in
4758  * AbortTransaction.)
4759  */
4761 
4762  /* Exit from parallel mode, if necessary. */
4763  if (IsInParallelMode())
4764  {
4766  s->parallelModeLevel = 0;
4767  }
4768 
4769  /*
4770  * We can skip all this stuff if the subxact failed before creating a
4771  * ResourceOwner...
4772  */
4773  if (s->curTransactionOwner)
4774  {
4775  AfterTriggerEndSubXact(false);
4781  s->parent->subTransactionId);
4783 
4784  /* Advertise the fact that we aborted in pg_xact. */
4785  (void) RecordTransactionAbort(true);
4786 
4787  /* Post-abort cleanup */
4790 
4792  s->parent->subTransactionId);
4793 
4796  false, false);
4798  s->parent->subTransactionId);
4799  AtEOSubXact_Inval(false);
4802  false, false);
4805  false, false);
4806  AtSubAbort_smgr();
4807 
4808  AtEOXact_GUC(false, s->gucNestLevel);
4809  AtEOSubXact_SPI(false, s->subTransactionId);
4811  s->parent->subTransactionId);
4813  s->parent->subTransactionId);
4815  s->parent->subTransactionId);
4817  AtEOSubXact_PgStat(false, s->nestingLevel);
4819  }
4820 
4821  /*
4822  * Restore the upper transaction's read-only state, too. This should be
4823  * redundant with GUC's cleanup but we may as well do it for consistency
4824  * with the commit case.
4825  */
4827 
4829 }
static void AtSubAbort_ResourceOwner(void)
Definition: xact.c:1680
void AtEOSubXact_RelationCache(bool isCommit, SubTransactionId mySubid, SubTransactionId parentSubid)
Definition: relcache.c:3033
static TransactionState CurrentTransactionState
Definition: xact.c:233
void SetUserIdAndSecContext(Oid userid, int sec_context)
Definition: miscinit.c:396
void AtEOSubXact_HashTables(bool isCommit, int nestDepth)
Definition: dynahash.c:1858
void AtEOSubXact_SPI(bool isCommit, SubTransactionId mySubid)
Definition: spi.c:216
#define PG_SETMASK(mask)
Definition: pqsignal.h:19
void reschedule_timeouts(void)
Definition: timeout.c:408
#define RESUME_INTERRUPTS()
Definition: miscadmin.h:117
void AtSubAbort_Snapshot(int level)
Definition: snapmgr.c:1023
TransState state
Definition: xact.c:177
ResourceOwner curTransactionOwner
Definition: xact.c:182
bool IsInParallelMode(void)
Definition: xact.c:906
void ConditionVariableCancelSleep(void)
static void AtSubAbort_Memory(void)
Definition: xact.c:1655
void XLogResetInsertion(void)
Definition: xloginsert.c:193
struct TransactionStateData * parent
Definition: xact.c:192
static void ShowTransactionState(const char *str)
Definition: xact.c:5100
void AtEOXact_GUC(bool isCommit, int nestLevel)
Definition: guc.c:5115
SubTransactionId subTransactionId
Definition: xact.c:174
sigset_t UnBlockSig
Definition: pqsignal.c:22
static void AtSubAbort_childXids(void)
Definition: xact.c:1693
static void pgstat_report_wait_end(void)
Definition: pgstat.h:1259
void AtEOSubXact_PgStat(bool isCommit, int nestDepth)
Definition: pgstat.c:2136
void LockErrorCleanup(void)
Definition: proc.c:686
void AtEOSubXact_LargeObject(bool isCommit, SubTransactionId mySubid, SubTransactionId parentSubid)
Definition: be-fsstubs.c:624
#define WARNING
Definition: elog.h:40
void UnlockBuffers(void)
Definition: bufmgr.c:3518
void AtSubAbort_Notify(void)
Definition: async.c:1671
void AtEOSubXact_on_commit_actions(bool isCommit, SubTransactionId mySubid, SubTransactionId parentSubid)
Definition: tablecmds.c:13034
void pgstat_progress_end_command(void)
Definition: pgstat.c:3144
void AtEOSubXact_Files(bool isCommit, SubTransactionId mySubid, SubTransactionId parentSubid)
Definition: fd.c:2879
TransactionId transactionId
Definition: xact.c:173
static void CallSubXactCallbacks(SubXactEvent event, SubTransactionId mySubid, SubTransactionId parentSubid)
Definition: xact.c:3393
bool XactReadOnly
Definition: xact.c:77
int parallelModeLevel
Definition: xact.c:191
void ResourceOwnerRelease(ResourceOwner owner, ResourceReleasePhase phase, bool isCommit, bool isTopLevel)
Definition: resowner.c:471
static const char * TransStateAsString(TransState state)
Definition: xact.c:5204
void AtSubAbort_Portals(SubTransactionId mySubid, SubTransactionId parentSubid, ResourceOwner myXactOwner, ResourceOwner parentXactOwner)
Definition: portalmem.c:907
void AtSubAbort_smgr(void)
Definition: storage.c:471
bool prevXactReadOnly
Definition: xact.c:188
void AbortBufferIO(void)
Definition: bufmgr.c:3974
void AfterTriggerEndSubXact(bool isCommit)
Definition: trigger.c:4842
void AtEOSubXact_Inval(bool isCommit)
Definition: inval.c:988
#define HOLD_INTERRUPTS()
Definition: miscadmin.h:115
#define elog
Definition: elog.h:219
void AtEOSubXact_Namespace(bool isCommit, SubTransactionId mySubid, SubTransactionId parentSubid)
Definition: namespace.c:3943
void LWLockReleaseAll(void)
Definition: lwlock.c:1823
#define TransactionIdIsValid(xid)
Definition: transam.h:41
void AtEOSubXact_Parallel(bool isCommit, SubTransactionId mySubId)
Definition: parallel.c:921
static TransactionId RecordTransactionAbort(bool isSubXact)
Definition: xact.c:1524

◆ AbortTransaction()

static void AbortTransaction ( void  )
static

Definition at line 2445 of file xact.c.

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

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

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

◆ AssignTransactionId()

static void AssignTransactionId ( TransactionState  s)
static

Definition at line 490 of file xact.c.

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

Referenced by GetCurrentTransactionId(), and GetTopTransactionId().

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

◆ AtAbort_Memory()

static void AtAbort_Memory ( void  )
static

Definition at line 1635 of file xact.c.

References MemoryContextSwitchTo(), and TopMemoryContext.

Referenced by AbortOutOfAnyTransaction(), and AbortTransaction().

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

◆ AtAbort_ResourceOwner()

static void AtAbort_ResourceOwner ( void  )
static

Definition at line 1667 of file xact.c.

References CurrentResourceOwner, and TopTransactionResourceOwner.

Referenced by AbortTransaction().

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

◆ AtCCI_LocalCache()

static void AtCCI_LocalCache ( void  )
static

Definition at line 1359 of file xact.c.

References AtCCI_RelationMap(), and CommandEndInvalidationMessages().

Referenced by CommandCounterIncrement().

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

◆ AtCleanup_Memory()

static void AtCleanup_Memory ( void  )
static

Definition at line 1725 of file xact.c.

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

Referenced by AbortOutOfAnyTransaction(), and CleanupTransaction().

1726 {
1728 
1729  /*
1730  * Now that we're "out" of a transaction, have the system allocate things
1731  * in the top memory context instead of per-transaction contexts.
1732  */
1734 
1735  /*
1736  * Clear the special abort context for next time.
1737  */
1738  if (TransactionAbortContext != NULL)
1740 
1741  /*
1742  * Release all transaction-local memory.
1743  */
1744  if (TopTransactionContext != NULL)
1746  TopTransactionContext = NULL;
1747  CurTransactionContext = NULL;
1749 }
static TransactionState CurrentTransactionState
Definition: xact.c:233
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:198
MemoryContext TopTransactionContext
Definition: mcxt.c:48
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
MemoryContext CurTransactionContext
Definition: mcxt.c:49
static MemoryContext TransactionAbortContext
Definition: xact.c:270
struct TransactionStateData * parent
Definition: xact.c:192
MemoryContext curTransactionContext
Definition: xact.c:181
MemoryContext TopMemoryContext
Definition: mcxt.c:43
#define MemoryContextResetAndDeleteChildren(ctx)
Definition: memutils.h:67
#define Assert(condition)
Definition: c.h:680

◆ AtCommit_Memory()

static void AtCommit_Memory ( void  )
static

Definition at line 1378 of file xact.c.

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

Referenced by CommitTransaction(), and PrepareTransaction().

1379 {
1380  /*
1381  * Now that we're "out" of a transaction, have the system allocate things
1382  * in the top memory context instead of per-transaction contexts.
1383  */
1385 
1386  /*
1387  * Release all transaction-local memory.
1388  */
1389  Assert(TopTransactionContext != NULL);
1391  TopTransactionContext = NULL;
1392  CurTransactionContext = NULL;
1394 }
static TransactionState CurrentTransactionState
Definition: xact.c:233
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:198
MemoryContext TopTransactionContext
Definition: mcxt.c:48
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
MemoryContext CurTransactionContext
Definition: mcxt.c:49
MemoryContext curTransactionContext
Definition: xact.c:181
MemoryContext TopMemoryContext
Definition: mcxt.c:43
#define Assert(condition)
Definition: c.h:680

◆ AtStart_Cache()

static void AtStart_Cache ( void  )
static

Definition at line 978 of file xact.c.

References AcceptInvalidationMessages().

Referenced by StartTransaction().

979 {
981 }
void AcceptInvalidationMessages(void)
Definition: inval.c:679

◆ AtStart_Memory()

static void AtStart_Memory ( void  )
static

Definition at line 987 of file xact.c.

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

Referenced by StartTransaction().

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

◆ AtStart_ResourceOwner()

static void AtStart_ResourceOwner ( void  )
static

Definition at line 1035 of file xact.c.

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

Referenced by StartTransaction().

1036 {
1038 
1039  /*
1040  * We shouldn't have a transaction resource owner already.
1041  */
1043 
1044  /*
1045  * Create a toplevel resource owner for the transaction.
1046  */
1047  s->curTransactionOwner = ResourceOwnerCreate(NULL, "TopTransaction");
1048 
1052 }
static TransactionState CurrentTransactionState
Definition: xact.c:233
ResourceOwner TopTransactionResourceOwner
Definition: resowner.c:140
ResourceOwner CurTransactionResourceOwner
Definition: resowner.c:139
ResourceOwner CurrentResourceOwner
Definition: resowner.c:138
ResourceOwner curTransactionOwner
Definition: xact.c:182
#define Assert(condition)
Definition: c.h:680
ResourceOwner ResourceOwnerCreate(ResourceOwner parent, const char *name)
Definition: resowner.c:416

◆ AtSubAbort_childXids()

static void AtSubAbort_childXids ( void  )
static

Definition at line 1693 of file xact.c.

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

Referenced by AbortSubTransaction().

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

◆ AtSubAbort_Memory()

static void AtSubAbort_Memory ( void  )
static

Definition at line 1655 of file xact.c.

References Assert, and MemoryContextSwitchTo().

Referenced by AbortSubTransaction().

1656 {
1658 
1660 }
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
static MemoryContext TransactionAbortContext
Definition: xact.c:270
#define Assert(condition)
Definition: c.h:680

◆ AtSubAbort_ResourceOwner()

static void AtSubAbort_ResourceOwner ( void  )
static

Definition at line 1680 of file xact.c.

References CurrentResourceOwner, CurrentTransactionState, and TransactionStateData::curTransactionOwner.

Referenced by AbortSubTransaction().

1681 {
1683 
1684  /* Make sure we have a valid ResourceOwner */
1686 }
static TransactionState CurrentTransactionState
Definition: xact.c:233
ResourceOwner CurrentResourceOwner
Definition: resowner.c:138
ResourceOwner curTransactionOwner
Definition: xact.c:182

◆ AtSubCleanup_Memory()

static void AtSubCleanup_Memory ( void  )
static

Definition at line 1761 of file xact.c.

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

Referenced by CleanupSubTransaction().

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

◆ AtSubCommit_childXids()

static void AtSubCommit_childXids ( void  )
static

Definition at line 1434 of file xact.c.

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

Referenced by CommitSubTransaction().

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

◆ AtSubCommit_Memory()

static void AtSubCommit_Memory ( void  )
static

Definition at line 1405 of file xact.c.

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

Referenced by CommitSubTransaction().

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

◆ AtSubStart_Memory()

static void AtSubStart_Memory ( void  )
static

Definition at line 1063 of file xact.c.

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

Referenced by StartSubTransaction().

1064 {
1066 
1067  Assert(CurTransactionContext != NULL);
1068 
1069  /*
1070  * Create a CurTransactionContext, which will be used to hold data that
1071  * survives subtransaction commit but disappears on subtransaction abort.
1072  * We make it a child of the immediate parent's CurTransactionContext.
1073  */
1075  "CurTransactionContext",
1078 
1079  /* Make the CurTransactionContext active. */
1081 }
static TransactionState CurrentTransactionState
Definition: xact.c:233
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
MemoryContext CurTransactionContext
Definition: mcxt.c:49
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:197
MemoryContext curTransactionContext
Definition: xact.c:181
#define AllocSetContextCreate(parent, name, allocparams)
Definition: memutils.h:165
#define Assert(condition)
Definition: c.h:680

◆ AtSubStart_ResourceOwner()

static void AtSubStart_ResourceOwner ( void  )
static

Definition at line 1087 of file xact.c.

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

Referenced by StartSubTransaction().

1088 {
1090 
1091  Assert(s->parent != NULL);
1092 
1093  /*
1094  * Create a resource owner for the subtransaction. We make it a child of
1095  * the immediate parent's resource owner.
1096  */
1097  s->curTransactionOwner =
1099  "SubTransaction");
1100 
1103 }
static TransactionState CurrentTransactionState
Definition: xact.c:233
ResourceOwner CurTransactionResourceOwner
Definition: resowner.c:139
ResourceOwner CurrentResourceOwner
Definition: resowner.c:138
ResourceOwner curTransactionOwner
Definition: xact.c:182
struct TransactionStateData * parent
Definition: xact.c:192
#define Assert(condition)
Definition: c.h:680
ResourceOwner ResourceOwnerCreate(ResourceOwner parent, const char *name)
Definition: resowner.c:416

◆ BeginImplicitTransactionBlock()

void BeginImplicitTransactionBlock ( void  )

Definition at line 3780 of file xact.c.

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

Referenced by exec_simple_query().

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

◆ BeginInternalSubTransaction()

void BeginInternalSubTransaction ( const char *  name)

Definition at line 4172 of file xact.c.

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

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

4173 {
4175 
4176  /*
4177  * Workers synchronize transaction state at the beginning of each parallel
4178  * operation, so we can't account for new subtransactions after that
4179  * point. We might be able to make an exception for the type of
4180  * subtransaction established by this function, which is typically used in
4181  * contexts where we're going to release or roll back the subtransaction
4182  * before proceeding further, so that no enduring change to the
4183  * transaction state occurs. For now, however, we prohibit this case along
4184  * with all the others.
4185  */
4186  if (IsInParallelMode())
4187  ereport(ERROR,
4188  (errcode(ERRCODE_INVALID_TRANSACTION_STATE),
4189  errmsg("cannot start subtransactions during a parallel operation")));
4190 
4191  switch (s->blockState)
4192  {
4193  case TBLOCK_STARTED:
4194  case TBLOCK_INPROGRESS:
4196  case TBLOCK_END:
4197  case TBLOCK_PREPARE:
4198  case TBLOCK_SUBINPROGRESS:
4199  /* Normal subtransaction start */
4200  PushTransaction();
4201  s = CurrentTransactionState; /* changed by push */
4202 
4203  /*
4204  * Savepoint names, like the TransactionState block itself, live
4205  * in TopTransactionContext.
4206  */
4207  if (name)
4209  break;
4210 
4211  /* These cases are invalid. */
4212  case TBLOCK_DEFAULT:
4213  case TBLOCK_BEGIN:
4215  case TBLOCK_SUBBEGIN:
4216  case TBLOCK_SUBRELEASE:
4217  case TBLOCK_SUBCOMMIT:
4218  case TBLOCK_ABORT:
4219  case TBLOCK_SUBABORT:
4220  case TBLOCK_ABORT_END:
4221  case TBLOCK_SUBABORT_END:
4222  case TBLOCK_ABORT_PENDING:
4224  case TBLOCK_SUBRESTART:
4226  elog(FATAL, "BeginInternalSubTransaction: unexpected state %s",
4228  break;
4229  }
4230 
4233 }
static TransactionState CurrentTransactionState
Definition: xact.c:233
MemoryContext TopTransactionContext
Definition: mcxt.c:48
void CommitTransactionCommand(void)
Definition: xact.c:2745
int errcode(int sqlerrcode)
Definition: elog.c:575
TBlockState blockState
Definition: xact.c:178
bool IsInParallelMode(void)
Definition: xact.c:906
#define ERROR
Definition: elog.h:43
#define FATAL
Definition: elog.h:52
static const char * BlockStateAsString(TBlockState blockState)
Definition: xact.c:5151
#define ereport(elevel, rest)
Definition: elog.h:122
static void PushTransaction(void)
Definition: xact.c:4871
void StartTransactionCommand(void)
Definition: xact.c:2674
const char * name
Definition: encode.c:521
int errmsg(const char *fmt,...)
Definition: elog.c:797
char * MemoryContextStrdup(MemoryContext context, const char *string)
Definition: mcxt.c:1050
#define elog
Definition: elog.h:219

◆ BeginTransactionBlock()

void BeginTransactionBlock ( void  )

Definition at line 3414 of file xact.c.

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

Referenced by standard_ProcessUtility().

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

◆ BlockStateAsString()

static const char * BlockStateAsString ( TBlockState  blockState)
static

Definition at line 5151 of file xact.c.

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

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

5152 {
5153  switch (blockState)
5154  {
5155  case TBLOCK_DEFAULT:
5156  return "DEFAULT";
5157  case TBLOCK_STARTED:
5158  return "STARTED";
5159  case TBLOCK_BEGIN:
5160  return "BEGIN";
5161  case TBLOCK_INPROGRESS:
5162  return "INPROGRESS";
5164  return "IMPLICIT_INPROGRESS";
5166  return "PARALLEL_INPROGRESS";
5167  case TBLOCK_END:
5168  return "END";
5169  case TBLOCK_ABORT:
5170  return "ABORT";
5171  case TBLOCK_ABORT_END:
5172  return "ABORT END";
5173  case TBLOCK_ABORT_PENDING:
5174  return "ABORT PEND";
5175  case TBLOCK_PREPARE:
5176  return "PREPARE";
5177  case TBLOCK_SUBBEGIN:
5178  return "SUB BEGIN";
5179  case TBLOCK_SUBINPROGRESS:
5180  return "SUB INPROGRS";
5181  case TBLOCK_SUBRELEASE:
5182  return "SUB RELEASE";
5183  case TBLOCK_SUBCOMMIT:
5184  return "SUB COMMIT";
5185  case TBLOCK_SUBABORT:
5186  return "SUB ABORT";
5187  case TBLOCK_SUBABORT_END:
5188  return "SUB ABORT END";
5190  return "SUB ABRT PEND";
5191  case TBLOCK_SUBRESTART:
5192  return "SUB RESTART";
5194  return "SUB AB RESTRT";
5195  }
5196  return "UNRECOGNIZED";
5197 }

◆ CallSubXactCallbacks()

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

Definition at line 3393 of file xact.c.

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

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

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

◆ CallXactCallbacks()

static void CallXactCallbacks ( XactEvent  event)
static

Definition at line 3338 of file xact.c.

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

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

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

◆ CheckTransactionChain()

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

Definition at line 3230 of file xact.c.

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

Referenced by RequireTransactionChain(), and WarnNoTransactionChain().

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

◆ CleanupSubTransaction()

static void CleanupSubTransaction ( void  )
static

Definition at line 4838 of file xact.c.

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

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

4839 {
4841 
4842  ShowTransactionState("CleanupSubTransaction");
4843 
4844  if (s->state != TRANS_ABORT)
4845  elog(WARNING, "CleanupSubTransaction while in %s state",
4847 
4849 
4852  if (s->curTransactionOwner)
4854  s->curTransactionOwner = NULL;
4855 
4857 
4858  s->state = TRANS_DEFAULT;
4859 
4860  PopTransaction();
4861 }
static TransactionState CurrentTransactionState
Definition: xact.c:233
static void PopTransaction(void)
Definition: xact.c:4930
ResourceOwner CurTransactionResourceOwner
Definition: resowner.c:139
ResourceOwner CurrentResourceOwner
Definition: resowner.c:138
void ResourceOwnerDelete(ResourceOwner owner)
Definition: resowner.c:673
TransState state
Definition: xact.c:177
ResourceOwner curTransactionOwner
Definition: xact.c:182
struct TransactionStateData * parent
Definition: xact.c:192
static void ShowTransactionState(const char *str)
Definition: xact.c:5100
SubTransactionId subTransactionId
Definition: xact.c:174
void AtSubCleanup_Portals(SubTransactionId mySubid)
Definition: portalmem.c:1020
#define WARNING
Definition: elog.h:40
static void AtSubCleanup_Memory(void)
Definition: xact.c:1761
static const char * TransStateAsString(TransState state)
Definition: xact.c:5204
#define elog
Definition: elog.h:219

◆ CleanupTransaction()

static void CleanupTransaction ( void  )
static

Definition at line 2625 of file xact.c.

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

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

2626 {
2628 
2629  /*
2630  * State should still be TRANS_ABORT from AbortTransaction().
2631  */
2632  if (s->state != TRANS_ABORT)
2633  elog(FATAL, "CleanupTransaction: unexpected state %s",
2635 
2636  /*
2637  * do abort cleanup processing
2638  */
2639  AtCleanup_Portals(); /* now safe to release portal memory */
2640  AtEOXact_Snapshot(false, true); /* and release the transaction's snapshots */
2641 
2642  CurrentResourceOwner = NULL; /* and resource owner */
2645  s->curTransactionOwner = NULL;
2648 
2649  AtCleanup_Memory(); /* and transaction memory */
2650 
2653  s->nestingLevel = 0;
2654  s->gucNestLevel = 0;
2655  s->childXids = NULL;
2656  s->nChildXids = 0;
2657  s->maxChildXids = 0;
2658  s->parallelModeLevel = 0;
2659 
2662 
2663  /*
2664  * done with abort processing, set current transaction state back to
2665  * default
2666  */
2667  s->state = TRANS_DEFAULT;
2668 }
TransactionId XactTopTransactionId
Definition: xact.c:107
static TransactionState CurrentTransactionState
Definition: xact.c:233
ResourceOwner TopTransactionResourceOwner
Definition: resowner.c:140
ResourceOwner CurTransactionResourceOwner
Definition: resowner.c:139
ResourceOwner CurrentResourceOwner
Definition: resowner.c:138
void ResourceOwnerDelete(ResourceOwner owner)
Definition: resowner.c:673
static void AtCleanup_Memory(void)
Definition: xact.c:1725
int nParallelCurrentXids
Definition: xact.c:108
void AtCleanup_Portals(void)
Definition: portalmem.c:824
TransactionId * childXids
Definition: xact.c:183
TransState state
Definition: xact.c:177
ResourceOwner curTransactionOwner
Definition: xact.c:182
#define FATAL
Definition: elog.h:52
#define InvalidTransactionId
Definition: transam.h:31
SubTransactionId subTransactionId
Definition: xact.c:174
TransactionId transactionId
Definition: xact.c:173
int parallelModeLevel
Definition: xact.c:191
static const char * TransStateAsString(TransState state)
Definition: xact.c:5204
#define InvalidSubTransactionId
Definition: c.h:461
#define elog
Definition: elog.h:219
void AtEOXact_Snapshot(bool isCommit, bool resetXmin)
Definition: snapmgr.c:1059

◆ CommandCounterIncrement()

void CommandCounterIncrement ( void  )

Definition at line 915 of file xact.c.

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

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

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

◆ CommitSubTransaction()

static void CommitSubTransaction ( void  )
static

Definition at line 4582 of file xact.c.

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

Referenced by CommitTransactionCommand(), and ReleaseCurrentSubTransaction().

4583 {
4585 
4586  ShowTransactionState("CommitSubTransaction");
4587 
4588  if (s->state != TRANS_INPROGRESS)
4589  elog(WARNING, "CommitSubTransaction while in %s state",
4591 
4592  /* Pre-commit processing goes here */
4593 
4595  s->parent->subTransactionId);
4596 
4597  /* If in parallel mode, clean up workers and exit parallel mode. */
4598  if (IsInParallelMode())
4599  {
4601  s->parallelModeLevel = 0;
4602  }
4603 
4604  /* Do the actual "commit", such as it is */
4605  s->state = TRANS_COMMIT;
4606 
4607  /* Must CCI to ensure commands of subtransaction are seen as done */
4609 
4610  /*
4611  * Prior to 8.4 we marked subcommit in clog at this point. We now only
4612  * perform that step, if required, as part of the atomic update of the
4613  * whole transaction tree at top level commit or abort.
4614  */
4615 
4616  /* Post-commit cleanup */
4619  AfterTriggerEndSubXact(true);
4624  s->parent->subTransactionId);
4626 
4628  s->parent->subTransactionId);
4629 
4632  true, false);
4634  s->parent->subTransactionId);
4635  AtEOSubXact_Inval(true);
4636  AtSubCommit_smgr();
4637 
4638  /*
4639  * The only lock we actually release here is the subtransaction XID lock.
4640  */
4644 
4645  /*
4646  * Other locks should get transferred to their parent resource owner.
4647  */
4650  true, false);
4653  true, false);
4654 
4655  AtEOXact_GUC(true, s->gucNestLevel);
4658  s->parent->subTransactionId);
4660  s->parent->subTransactionId);
4662  s->parent->subTransactionId);
4664  AtEOSubXact_PgStat(true, s->nestingLevel);
4666 
4667  /*
4668  * We need to restore the upper transaction's read-only state, in case the
4669  * upper is read-write while the child is read-only; GUC will incorrectly
4670  * think it should leave the child state in place.
4671  */
4673 
4677  s->curTransactionOwner = NULL;
4678 
4680 
4681  s->state = TRANS_DEFAULT;
4682 
4683  PopTransaction();
4684 }
void AtEOSubXact_RelationCache(bool isCommit, SubTransactionId mySubid, SubTransactionId parentSubid)
Definition: relcache.c:3033
static TransactionState CurrentTransactionState
Definition: xact.c:233
static void AtSubCommit_Memory(void)
Definition: xact.c:1405
static void PopTransaction(void)
Definition: xact.c:4930
ResourceOwner CurTransactionResourceOwner
Definition: resowner.c:139
ResourceOwner CurrentResourceOwner
Definition: resowner.c:138
void AtEOSubXact_HashTables(bool isCommit, int nestDepth)
Definition: dynahash.c:1858
void ResourceOwnerDelete(ResourceOwner owner)
Definition: resowner.c:673
void AtSubCommit_smgr(void)
Definition: storage.c:451
void AtEOSubXact_SPI(bool isCommit, SubTransactionId mySubid)
Definition: spi.c:216
void AtSubCommit_Snapshot(int level)
Definition: snapmgr.c:1002
static void AtSubCommit_childXids(void)
Definition: xact.c:1434
TransState state
Definition: xact.c:177
ResourceOwner curTransactionOwner
Definition: xact.c:182
bool IsInParallelMode(void)
Definition: xact.c:906
struct TransactionStateData * parent
Definition: xact.c:192
void AtSubCommit_Notify(void)
Definition: async.c:1639
static void ShowTransactionState(const char *str)
Definition: xact.c:5100
void AtEOXact_GUC(bool isCommit, int nestLevel)
Definition: guc.c:5115
SubTransactionId subTransactionId
Definition: xact.c:174
void AtEOSubXact_PgStat(bool isCommit, int nestDepth)
Definition: pgstat.c:2136
void AtEOSubXact_LargeObject(bool isCommit, SubTransactionId mySubid, SubTransactionId parentSubid)
Definition: be-fsstubs.c:624
#define WARNING
Definition: elog.h:40
void AtEOSubXact_on_commit_actions(bool isCommit, SubTransactionId mySubid, SubTransactionId parentSubid)
Definition: tablecmds.c:13034
void CommandCounterIncrement(void)
Definition: xact.c:915
void AtEOSubXact_Files(bool isCommit, SubTransactionId mySubid, SubTransactionId parentSubid)
Definition: fd.c:2879
TransactionId transactionId
Definition: xact.c:173
static void CallSubXactCallbacks(SubXactEvent event, SubTransactionId mySubid, SubTransactionId parentSubid)
Definition: xact.c:3393
bool XactReadOnly
Definition: xact.c:77
int parallelModeLevel
Definition: xact.c:191
void ResourceOwnerRelease(ResourceOwner owner, ResourceReleasePhase phase, bool isCommit, bool isTopLevel)
Definition: resowner.c:471
static const char * TransStateAsString(TransState state)
Definition: xact.c:5204
bool prevXactReadOnly
Definition: xact.c:188
void AfterTriggerEndSubXact(bool isCommit)
Definition: trigger.c:4842
void AtEOSubXact_Inval(bool isCommit)
Definition: inval.c:988
void XactLockTableDelete(TransactionId xid)
Definition: lmgr.c:530
#define elog
Definition: elog.h:219
void AtEOSubXact_Namespace(bool isCommit, SubTransactionId mySubid, SubTransactionId parentSubid)
Definition: namespace.c:3943
#define TransactionIdIsValid(xid)
Definition: transam.h:41
void AtEOSubXact_Parallel(bool isCommit, SubTransactionId mySubId)
Definition: parallel.c:921
void AtSubCommit_Portals(SubTransactionId mySubid, SubTransactionId parentSubid, ResourceOwner parentXactOwner)
Definition: portalmem.c:873

◆ CommitTransaction()

static void CommitTransaction ( void  )
static

Definition at line 1934 of file xact.c.

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

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

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

◆ CommitTransactionCommand()

void CommitTransactionCommand ( void  )

Definition at line 2745 of file xact.c.

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

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

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

◆ DefineSavepoint()

void DefineSavepoint ( const char *  name)

Definition at line 3827 of file xact.c.

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

Referenced by CommitTransactionCommand(), and standard_ProcessUtility().

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

◆ EndImplicitTransactionBlock()

void EndImplicitTransactionBlock ( void  )

Definition at line 3805 of file xact.c.

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

Referenced by exec_simple_query().

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

◆ EndParallelWorkerTransaction()

void EndParallelWorkerTransaction ( void  )

Definition at line 5088 of file xact.c.

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

Referenced by ParallelWorkerMain().

5089 {
5093 }
static TransactionState CurrentTransactionState
Definition: xact.c:233
TBlockState blockState
Definition: xact.c:178
#define Assert(condition)
Definition: c.h:680
static void CommitTransaction(void)
Definition: xact.c:1934

◆ EndTransactionBlock()

bool EndTransactionBlock ( void  )

Definition at line 3534 of file xact.c.

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

Referenced by PrepareTransactionBlock(), and standard_ProcessUtility().

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

◆ EnterParallelMode()

void EnterParallelMode ( void  )

Definition at line 873 of file xact.c.

References Assert, CurrentTransactionState, and TransactionStateData::parallelModeLevel.

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

874 {
876 
877  Assert(s->parallelModeLevel >= 0);
878 
879  ++s->parallelModeLevel;
880 }
static TransactionState CurrentTransactionState
Definition: xact.c:233
int parallelModeLevel
Definition: xact.c:191
#define Assert(condition)
Definition: c.h:680

◆ EstimateTransactionStateSpace()

Size EstimateTransactionStateSpace ( void  )

Definition at line 4964 of file xact.c.

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

Referenced by InitializeParallelDSM().

4965 {
4966  TransactionState s;
4967  Size nxids = 6; /* iso level, deferrable, top & current XID,
4968  * command counter, XID count */
4969 
4970  for (s = CurrentTransactionState; s != NULL; s = s->parent)
4971  {
4973  nxids = add_size(nxids, 1);
4974  nxids = add_size(nxids, s->nChildXids);
4975  }
4976 
4977  nxids = add_size(nxids, nParallelCurrentXids);
4978  return mul_size(nxids, sizeof(TransactionId));
4979 }
static TransactionState CurrentTransactionState
Definition: xact.c:233
uint32 TransactionId
Definition: c.h:455
int nParallelCurrentXids
Definition: xact.c:108
struct TransactionStateData * parent
Definition: xact.c:192
Size mul_size(Size s1, Size s2)
Definition: shmem.c:492
Size add_size(Size s1, Size s2)
Definition: shmem.c:475
TransactionId transactionId
Definition: xact.c:173
size_t Size
Definition: c.h:414
#define TransactionIdIsValid(xid)
Definition: transam.h:41

◆ ExitParallelMode()

void ExitParallelMode ( void  )

Definition at line 886 of file xact.c.

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

Referenced by ExecutePlan(), and ParallelWorkerMain().

887 {
889 
890  Assert(s->parallelModeLevel > 0);
892 
893  --s->parallelModeLevel;
894 }
static TransactionState CurrentTransactionState
Definition: xact.c:233
bool ParallelContextActive(void)
Definition: parallel.c:703
int parallelModeLevel
Definition: xact.c:191
#define Assert(condition)
Definition: c.h:680

◆ ForceSyncCommit()

void ForceSyncCommit ( void  )

Definition at line 963 of file xact.c.

References forceSyncCommit.

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

964 {
965  forceSyncCommit = true;
966 }
static bool forceSyncCommit
Definition: xact.c:263

◆ GetCurrentCommandId()

CommandId GetCurrentCommandId ( bool  used)

Definition at line 680 of file xact.c.

References Assert, currentCommandId, currentCommandIdUsed, and IsParallelWorker.

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

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

◆ GetCurrentStatementStartTimestamp()

TimestampTz GetCurrentStatementStartTimestamp ( void  )

Definition at line 710 of file xact.c.

References stmtStartTimestamp.

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

711 {
712  return stmtStartTimestamp;
713 }
static TimestampTz stmtStartTimestamp
Definition: xact.c:251

◆ GetCurrentSubTransactionId()

◆ GetCurrentTransactionId()

◆ GetCurrentTransactionIdIfAny()

TransactionId GetCurrentTransactionIdIfAny ( void  )

Definition at line 435 of file xact.c.

References TransactionStateData::transactionId.

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

436 {
438 }
static TransactionState CurrentTransactionState
Definition: xact.c:233
TransactionId transactionId
Definition: xact.c:173

◆ GetCurrentTransactionNestLevel()

◆ GetCurrentTransactionStartTimestamp()

TimestampTz GetCurrentTransactionStartTimestamp ( void  )

◆ GetCurrentTransactionStopTimestamp()

TimestampTz GetCurrentTransactionStopTimestamp ( void  )

Definition at line 722 of file xact.c.

References GetCurrentTimestamp(), and xactStopTimestamp.

Referenced by pgstat_report_stat().

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

◆ GetStableLatestTransactionId()

TransactionId GetStableLatestTransactionId ( void  )

Definition at line 462 of file xact.c.

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

Referenced by xid_age().

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

◆ GetTopTransactionId()

TransactionId GetTopTransactionId ( void  )

Definition at line 390 of file xact.c.

References AssignTransactionId(), TransactionIdIsValid, and XactTopTransactionId.

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

391 {
394  return XactTopTransactionId;
395 }
TransactionId XactTopTransactionId
Definition: xact.c:107
static TransactionStateData TopTransactionStateData
Definition: xact.c:202
#define TransactionIdIsValid(xid)
Definition: transam.h:41
static void AssignTransactionId(TransactionState s)
Definition: xact.c:490

◆ GetTopTransactionIdIfAny()

◆ IsAbortedTransactionBlockState()

◆ IsInParallelMode()

◆ IsInTransactionChain()

bool IsInTransactionChain ( bool  isTopLevel)

Definition at line 3269 of file xact.c.

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

Referenced by vacuum().

3270 {
3271  /*
3272  * Return true on same conditions that would make PreventTransactionChain
3273  * error out
3274  */
3275  if (IsTransactionBlock())
3276  return true;
3277 
3278  if (IsSubTransaction())
3279  return true;
3280 
3281  if (!isTopLevel)
3282  return true;
3283 
3286  return true;
3287 
3288  return false;
3289 }
static TransactionState CurrentTransactionState
Definition: xact.c:233
TBlockState blockState
Definition: xact.c:178
bool IsTransactionBlock(void)
Definition: xact.c:4448
bool IsSubTransaction(void)
Definition: xact.c:4521

◆ IsSubTransaction()

◆ IsTransactionBlock()

bool IsTransactionBlock ( void  )

Definition at line 4448 of file xact.c.

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

Referenced by CheckTransactionChain(), CreateReplicationSlot(), exec_replication_command(), IsInTransactionChain(), and PreventTransactionChain().

4449 {
4451 
4453  return false;
4454 
4455  return true;
4456 }
static TransactionState CurrentTransactionState
Definition: xact.c:233
TBlockState blockState
Definition: xact.c:178

◆ IsTransactionOrTransactionBlock()

bool IsTransactionOrTransactionBlock ( void  )

◆ IsTransactionState()

bool IsTransactionState ( void  )

Definition at line 351 of file xact.c.

References CurrentTransactionState, TransactionStateData::state, and TRANS_INPROGRESS.

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

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

◆ MarkCurrentTransactionIdLoggedIfAny()

void MarkCurrentTransactionIdLoggedIfAny ( void  )

Definition at line 446 of file xact.c.

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

Referenced by XLogInsertRecord().

447 {
450 }
static TransactionState CurrentTransactionState
Definition: xact.c:233
TransactionId transactionId
Definition: xact.c:173
#define TransactionIdIsValid(xid)
Definition: transam.h:41

◆ PopTransaction()

static void PopTransaction ( void  )
static

Definition at line 4930 of file xact.c.

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

Referenced by CleanupSubTransaction(), and CommitSubTransaction().

4931 {
4933 
4934  if (s->state != TRANS_DEFAULT)
4935  elog(WARNING, "PopTransaction while in %s state",
4937 
4938  if (s->parent == NULL)
4939  elog(FATAL, "PopTransaction with no parent");
4940 
4942 
4943  /* Let's just make sure CurTransactionContext is good */
4946 
4947  /* Ditto for ResourceOwner links */
4950 
4951  /* Free the old child structure */
4952  if (s->name)
4953  pfree(s->name);
4954  pfree(s);
4955 }
static TransactionState CurrentTransactionState
Definition: xact.c:233
ResourceOwner CurTransactionResourceOwner
Definition: resowner.c:139
ResourceOwner CurrentResourceOwner
Definition: resowner.c:138
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
MemoryContext CurTransactionContext
Definition: mcxt.c:49
TransState state
Definition: xact.c:177
ResourceOwner curTransactionOwner
Definition: xact.c:182
void pfree(void *pointer)
Definition: mcxt.c:936
#define FATAL
Definition: elog.h:52
struct TransactionStateData * parent
Definition: xact.c:192
MemoryContext curTransactionContext
Definition: xact.c:181
#define WARNING
Definition: elog.h:40
static const char * TransStateAsString(TransState state)
Definition: xact.c:5204
#define elog
Definition: elog.h:219

◆ PrepareTransaction()

static void PrepareTransaction ( void  )
static

Definition at line 2170 of file xact.c.

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

Referenced by CommitTransactionCommand().

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