PostgreSQL Source Code  git master
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros
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_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 (char *gid)
 
bool EndTransactionBlock (void)
 
void UserAbortTransactionBlock (void)
 
void DefineSavepoint (char *name)
 
void ReleaseSavepoint (List *options)
 
void RollbackToSavepoint (List *options)
 
void BeginInternalSubTransaction (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

Definition at line 194 of file xact.c.

Enumeration Type Documentation

Enumerator
TBLOCK_DEFAULT 
TBLOCK_STARTED 
TBLOCK_BEGIN 
TBLOCK_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_PARALLEL_INPROGRESS, /* live transaction inside parallel worker */
149  TBLOCK_END, /* COMMIT received */
150  TBLOCK_ABORT, /* failed xact, awaiting ROLLBACK */
151  TBLOCK_ABORT_END, /* failed xact, ROLLBACK received */
152  TBLOCK_ABORT_PENDING, /* live xact, ROLLBACK received */
153  TBLOCK_PREPARE, /* live xact, PREPARE received */
154 
155  /* subtransaction states */
156  TBLOCK_SUBBEGIN, /* starting a subtransaction */
157  TBLOCK_SUBINPROGRESS, /* live subtransaction */
158  TBLOCK_SUBRELEASE, /* RELEASE received */
159  TBLOCK_SUBCOMMIT, /* COMMIT received while TBLOCK_SUBINPROGRESS */
160  TBLOCK_SUBABORT, /* failed subxact, awaiting ROLLBACK */
161  TBLOCK_SUBABORT_END, /* failed subxact, ROLLBACK received */
162  TBLOCK_SUBABORT_PENDING, /* live subxact, ROLLBACK received */
163  TBLOCK_SUBRESTART, /* live subxact, ROLLBACK TO received */
164  TBLOCK_SUBABORT_RESTART /* failed subxact, ROLLBACK TO received */
165 } TBlockState;
TBlockState
Definition: xact.c:139
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

void AbortCurrentTransaction ( void  )

Definition at line 2986 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_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().

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

Definition at line 4222 of file xact.c.

References AbortSubTransaction(), AbortTransaction(), Assert, TransactionStateData::blockState, CleanupSubTransaction(), CleanupTransaction(), CurrentTransactionState, NULL, TransactionStateData::parent, TransactionStateData::state, TBLOCK_ABORT, TBLOCK_ABORT_END, TBLOCK_ABORT_PENDING, TBLOCK_BEGIN, TBLOCK_DEFAULT, TBLOCK_END, 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(), RemoveTempRelationsCallback(), and ShutdownPostgres().

4223 {
4225 
4226  /*
4227  * Get out of any transaction or nested transaction
4228  */
4229  do
4230  {
4231  switch (s->blockState)
4232  {
4233  case TBLOCK_DEFAULT:
4234  if (s->state == TRANS_DEFAULT)
4235  {
4236  /* Not in a transaction, do nothing */
4237  }
4238  else
4239  {
4240  /*
4241  * We can get here after an error during transaction start
4242  * (state will be TRANS_START). Need to clean up the
4243  * incompletely started transaction. First, adjust the
4244  * low-level state to suppress warning message from
4245  * AbortTransaction.
4246  */
4247  if (s->state == TRANS_START)
4248  s->state = TRANS_INPROGRESS;
4249  AbortTransaction();
4251  }
4252  break;
4253  case TBLOCK_STARTED:
4254  case TBLOCK_BEGIN:
4255  case TBLOCK_INPROGRESS:
4257  case TBLOCK_END:
4258  case TBLOCK_ABORT_PENDING:
4259  case TBLOCK_PREPARE:
4260  /* In a transaction, so clean up */
4261  AbortTransaction();
4264  break;
4265  case TBLOCK_ABORT:
4266  case TBLOCK_ABORT_END:
4267  /* AbortTransaction already done, still need Cleanup */
4270  break;
4271 
4272  /*
4273  * In a subtransaction, so clean it up and abort parent too
4274  */
4275  case TBLOCK_SUBBEGIN:
4276  case TBLOCK_SUBINPROGRESS:
4277  case TBLOCK_SUBRELEASE:
4278  case TBLOCK_SUBCOMMIT:
4280  case TBLOCK_SUBRESTART:
4283  s = CurrentTransactionState; /* changed by pop */
4284  break;
4285 
4286  case TBLOCK_SUBABORT:
4287  case TBLOCK_SUBABORT_END:
4289  /* As above, but AbortSubTransaction already done */
4291  s = CurrentTransactionState; /* changed by pop */
4292  break;
4293  }
4294  } while (s->blockState != TBLOCK_DEFAULT);
4295 
4296  /* Should be out of all subxacts now */
4297  Assert(s->parent == NULL);
4298 }
static TransactionState CurrentTransactionState
Definition: xact.c:232
TBlockState blockState
Definition: xact.c:177
TransState state
Definition: xact.c:176
static void CleanupTransaction(void)
Definition: xact.c:2628
struct TransactionStateData * parent
Definition: xact.c:191
static void AbortSubTransaction(void)
Definition: xact.c:4545
static void AbortTransaction(void)
Definition: xact.c:2448
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:675
static void CleanupSubTransaction(void)
Definition: xact.c:4690
static void AbortSubTransaction ( void  )
static

Definition at line 4545 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(), 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().

4546 {
4548 
4549  /* Prevent cancel/die interrupt while cleaning up */
4550  HOLD_INTERRUPTS();
4551 
4552  /* Make sure we have a valid memory context and resource owner */
4555 
4556  /*
4557  * Release any LW locks we might be holding as quickly as possible.
4558  * (Regular locks, however, must be held till we finish aborting.)
4559  * Releasing LW locks is critical since we might try to grab them again
4560  * while cleaning up!
4561  *
4562  * FIXME This may be incorrect --- Are there some locks we should keep?
4563  * Buffer locks, for example? I don't think so but I'm not sure.
4564  */
4565  LWLockReleaseAll();
4566 
4569  AbortBufferIO();
4570  UnlockBuffers();
4571 
4572  /* Reset WAL record construction state */
4574 
4575  /*
4576  * Also clean up any open wait for lock, since the lock manager will choke
4577  * if we try to wait for another lock before doing this.
4578  */
4579  LockErrorCleanup();
4580 
4581  /*
4582  * If any timeout events are still active, make sure the timeout interrupt
4583  * is scheduled. This covers possible loss of a timeout interrupt due to
4584  * longjmp'ing out of the SIGINT handler (see notes in handle_sig_alarm).
4585  * We delay this till after LockErrorCleanup so that we don't uselessly
4586  * reschedule lock or deadlock check timeouts.
4587  */
4589 
4590  /*
4591  * Re-enable signals, in case we got here by longjmp'ing out of a signal
4592  * handler. We do this fairly early in the sequence so that the timeout
4593  * infrastructure will be functional if needed while aborting.
4594  */
4596 
4597  /*
4598  * check the current transaction state
4599  */
4600  ShowTransactionState("AbortSubTransaction");
4601 
4602  if (s->state != TRANS_INPROGRESS)
4603  elog(WARNING, "AbortSubTransaction while in %s state",
4605 
4606  s->state = TRANS_ABORT;
4607 
4608  /*
4609  * Reset user ID which might have been changed transiently. (See notes in
4610  * AbortTransaction.)
4611  */
4613 
4614  /* Exit from parallel mode, if necessary. */
4615  if (IsInParallelMode())
4616  {
4618  s->parallelModeLevel = 0;
4619  }
4620 
4621  /*
4622  * We can skip all this stuff if the subxact failed before creating a
4623  * ResourceOwner...
4624  */
4625  if (s->curTransactionOwner)
4626  {
4627  AfterTriggerEndSubXact(false);
4633  s->parent->subTransactionId);
4635 
4636  /* Advertise the fact that we aborted in pg_xact. */
4637  (void) RecordTransactionAbort(true);
4638 
4639  /* Post-abort cleanup */
4642 
4644  s->parent->subTransactionId);
4645 
4648  false, false);
4650  s->parent->subTransactionId);
4651  AtEOSubXact_Inval(false);
4654  false, false);
4657  false, false);
4658  AtSubAbort_smgr();
4659 
4660  AtEOXact_GUC(false, s->gucNestLevel);
4661  AtEOSubXact_SPI(false, s->subTransactionId);
4663  s->parent->subTransactionId);
4665  s->parent->subTransactionId);
4667  s->parent->subTransactionId);
4669  AtEOSubXact_PgStat(false, s->nestingLevel);
4671  }
4672 
4673  /*
4674  * Restore the upper transaction's read-only state, too. This should be
4675  * redundant with GUC's cleanup but we may as well do it for consistency
4676  * with the commit case.
4677  */
4679 
4681 }
static void AtSubAbort_ResourceOwner(void)
Definition: xact.c:1686
void AtEOSubXact_RelationCache(bool isCommit, SubTransactionId mySubid, SubTransactionId parentSubid)
Definition: relcache.c:3066
static TransactionState CurrentTransactionState
Definition: xact.c:232
void SetUserIdAndSecContext(Oid userid, int sec_context)
Definition: miscinit.c:395
void AtEOSubXact_HashTables(bool isCommit, int nestDepth)
Definition: dynahash.c:1824
void AtEOSubXact_SPI(bool isCommit, SubTransactionId mySubid)
Definition: spi.c:214
#define PG_SETMASK(mask)
Definition: pqsignal.h:19
void reschedule_timeouts(void)
Definition: timeout.c:408
#define RESUME_INTERRUPTS()
Definition: miscadmin.h:116
void AtSubAbort_Snapshot(int level)
Definition: snapmgr.c:1018
TransState state
Definition: xact.c:176
ResourceOwner curTransactionOwner
Definition: xact.c:181
bool IsInParallelMode(void)
Definition: xact.c:913
static void AtSubAbort_Memory(void)
Definition: xact.c:1661
void XLogResetInsertion(void)
Definition: xloginsert.c:193
struct TransactionStateData * parent
Definition: xact.c:191
static void ShowTransactionState(const char *str)
Definition: xact.c:4952
void AtEOXact_GUC(bool isCommit, int nestLevel)
Definition: guc.c:5058
SubTransactionId subTransactionId
Definition: xact.c:173
sigset_t UnBlockSig
Definition: pqsignal.c:22
static void AtSubAbort_childXids(void)
Definition: xact.c:1699
static void pgstat_report_wait_end(void)
Definition: pgstat.h:1205
void AtEOSubXact_PgStat(bool isCommit, int nestDepth)
Definition: pgstat.c:2035
void LockErrorCleanup(void)
Definition: proc.c:677
void AtEOSubXact_LargeObject(bool isCommit, SubTransactionId mySubid, SubTransactionId parentSubid)
Definition: be-fsstubs.c:674
#define WARNING
Definition: elog.h:40
void UnlockBuffers(void)
Definition: bufmgr.c:3518
void AtSubAbort_Notify(void)
Definition: async.c:1666
void AtEOSubXact_on_commit_actions(bool isCommit, SubTransactionId mySubid, SubTransactionId parentSubid)
Definition: tablecmds.c:12561
void pgstat_progress_end_command(void)
Definition: pgstat.c:2952
void AtEOSubXact_Files(bool isCommit, SubTransactionId mySubid, SubTransactionId parentSubid)
Definition: fd.c:2549
TransactionId transactionId
Definition: xact.c:172
static void CallSubXactCallbacks(SubXactEvent event, SubTransactionId mySubid, SubTransactionId parentSubid)
Definition: xact.c:3394
bool XactReadOnly
Definition: xact.c:77
int parallelModeLevel
Definition: xact.c:190
void ResourceOwnerRelease(ResourceOwner owner, ResourceReleasePhase phase, bool isCommit, bool isTopLevel)
Definition: resowner.c:471
static const char * TransStateAsString(TransState state)
Definition: xact.c:5054
void AtSubAbort_Portals(SubTransactionId mySubid, SubTransactionId parentSubid, ResourceOwner myXactOwner, ResourceOwner parentXactOwner)
Definition: portalmem.c:894
void AtSubAbort_smgr(void)
Definition: storage.c:471
bool prevXactReadOnly
Definition: xact.c:187
void AbortBufferIO(void)
Definition: bufmgr.c:3974
void AfterTriggerEndSubXact(bool isCommit)
Definition: trigger.c:4442
void AtEOSubXact_Inval(bool isCommit)
Definition: inval.c:981
#define HOLD_INTERRUPTS()
Definition: miscadmin.h:114
#define elog
Definition: elog.h:219
void AtEOSubXact_Namespace(bool isCommit, SubTransactionId mySubid, SubTransactionId parentSubid)
Definition: namespace.c:3793
void LWLockReleaseAll(void)
Definition: lwlock.c:1814
#define TransactionIdIsValid(xid)
Definition: transam.h:41
void AtEOSubXact_Parallel(bool isCommit, SubTransactionId mySubId)
Definition: parallel.c:899
static TransactionId RecordTransactionAbort(bool isSubXact)
Definition: xact.c:1530
static void AbortTransaction ( void  )
static

Definition at line 2448 of file xact.c.

References AbortBufferIO(), AfterTriggerEndXact(), Assert, AtAbort_Memory(), AtAbort_Notify(), AtAbort_Portals(), AtAbort_ResourceOwner(), AtAbort_Twophase(), AtEOXact_Buffers(), AtEOXact_CatCache(), 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, NULL, 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().

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

Definition at line 489 of file xact.c.

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

Referenced by GetCurrentTransactionId(), and GetTopTransactionId().

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

Definition at line 1641 of file xact.c.

References MemoryContextSwitchTo(), NULL, and TopMemoryContext.

Referenced by AbortTransaction().

1642 {
1643  /*
1644  * Switch into TransactionAbortContext, which should have some free space
1645  * even if nothing else does. We'll work in this context until we've
1646  * finished cleaning up.
1647  *
1648  * It is barely possible to get here when we've not been able to create
1649  * TransactionAbortContext yet; if so use TopMemoryContext.
1650  */
1653  else
1655 }
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
static MemoryContext TransactionAbortContext
Definition: xact.c:269
MemoryContext TopMemoryContext
Definition: mcxt.c:43
#define NULL
Definition: c.h:229
static void AtAbort_ResourceOwner ( void  )
static

Definition at line 1673 of file xact.c.

References CurrentResourceOwner, and TopTransactionResourceOwner.

Referenced by AbortTransaction().

1674 {
1675  /*
1676  * Make sure we have a valid ResourceOwner, if possible (else it will be
1677  * NULL, which is OK)
1678  */
1680 }
ResourceOwner TopTransactionResourceOwner
Definition: resowner.c:140
ResourceOwner CurrentResourceOwner
Definition: resowner.c:138
static void AtCCI_LocalCache ( void  )
static

Definition at line 1365 of file xact.c.

References AtCCI_RelationMap(), and CommandEndInvalidationMessages().

Referenced by CommandCounterIncrement().

1366 {
1367  /*
1368  * Make any pending relation map changes visible. We must do this before
1369  * processing local sinval messages, so that the map changes will get
1370  * reflected into the relcache when relcache invals are processed.
1371  */
1373 
1374  /*
1375  * Make catalog changes visible to me for the next command.
1376  */
1378 }
void CommandEndInvalidationMessages(void)
Definition: inval.c:1058
void AtCCI_RelationMap(void)
Definition: relmapper.c:423
static void AtCleanup_Memory ( void  )
static

Definition at line 1731 of file xact.c.

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

Referenced by CleanupTransaction().

1732 {
1734 
1735  /*
1736  * Now that we're "out" of a transaction, have the system allocate things
1737  * in the top memory context instead of per-transaction contexts.
1738  */
1740 
1741  /*
1742  * Clear the special abort context for next time.
1743  */
1746 
1747  /*
1748  * Release all transaction-local memory.
1749  */
1750  if (TopTransactionContext != NULL)
1755 }
static TransactionState CurrentTransactionState
Definition: xact.c:232
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:200
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:269
struct TransactionStateData * parent
Definition: xact.c:191
MemoryContext curTransactionContext
Definition: xact.c:180
MemoryContext TopMemoryContext
Definition: mcxt.c:43
#define MemoryContextResetAndDeleteChildren(ctx)
Definition: memutils.h:67
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:675
static void AtCommit_Memory ( void  )
static

Definition at line 1384 of file xact.c.

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

Referenced by CommitTransaction(), and PrepareTransaction().

1385 {
1386  /*
1387  * Now that we're "out" of a transaction, have the system allocate things
1388  * in the top memory context instead of per-transaction contexts.
1389  */
1391 
1392  /*
1393  * Release all transaction-local memory.
1394  */
1400 }
static TransactionState CurrentTransactionState
Definition: xact.c:232
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:200
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:180
MemoryContext TopMemoryContext
Definition: mcxt.c:43
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:675
static void AtStart_Cache ( void  )
static

Definition at line 985 of file xact.c.

References AcceptInvalidationMessages().

Referenced by StartTransaction().

986 {
988 }
void AcceptInvalidationMessages(void)
Definition: inval.c:672
static void AtStart_Memory ( void  )
static

Definition at line 994 of file xact.c.

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

Referenced by StartTransaction().

995 {
997 
998  /*
999  * If this is the first time through, create a private context for
1000  * AbortTransaction to work in. By reserving some space now, we can
1001  * insulate AbortTransaction from out-of-memory scenarios. Like
1002  * ErrorContext, we set it up with slow growth rate and a nonzero minimum
1003  * size, so that space will be reserved immediately.
1004  */
1008  "TransactionAbortContext",
1009  32 * 1024,
1010  32 * 1024,
1011  32 * 1024);
1012 
1013  /*
1014  * We shouldn't have a transaction context already.
1015  */
1017 
1018  /*
1019  * Create a toplevel context for the transaction.
1020  */
1023  "TopTransactionContext",
1025 
1026  /*
1027  * In a top-level transaction, CurTransactionContext is the same as
1028  * TopTransactionContext.
1029  */
1032 
1033  /* Make the CurTransactionContext active. */
1035 }
static TransactionState CurrentTransactionState
Definition: xact.c:232
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:269
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:165
MemoryContext curTransactionContext
Definition: xact.c:180
MemoryContext TopMemoryContext
Definition: mcxt.c:43
MemoryContext AllocSetContextCreate(MemoryContext parent, const char *name, Size minContextSize, Size initBlockSize, Size maxBlockSize)
Definition: aset.c:322
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:675
static void AtStart_ResourceOwner ( void  )
static

Definition at line 1041 of file xact.c.

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

Referenced by StartTransaction().

1042 {
1044 
1045  /*
1046  * We shouldn't have a transaction resource owner already.
1047  */
1049 
1050  /*
1051  * Create a toplevel resource owner for the transaction.
1052  */
1053  s->curTransactionOwner = ResourceOwnerCreate(NULL, "TopTransaction");
1054 
1058 }
static TransactionState CurrentTransactionState
Definition: xact.c:232
ResourceOwner TopTransactionResourceOwner
Definition: resowner.c:140
ResourceOwner CurTransactionResourceOwner
Definition: resowner.c:139
ResourceOwner CurrentResourceOwner
Definition: resowner.c:138
ResourceOwner curTransactionOwner
Definition: xact.c:181
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:675
ResourceOwner ResourceOwnerCreate(ResourceOwner parent, const char *name)
Definition: resowner.c:416
static void AtSubAbort_childXids ( void  )
static

Definition at line 1699 of file xact.c.

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

Referenced by AbortSubTransaction().

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

Definition at line 1661 of file xact.c.

References Assert, MemoryContextSwitchTo(), and NULL.

Referenced by AbortSubTransaction().

1662 {
1664 
1666 }
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
static MemoryContext TransactionAbortContext
Definition: xact.c:269
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:675
static void AtSubAbort_ResourceOwner ( void  )
static

Definition at line 1686 of file xact.c.

References CurrentResourceOwner, CurrentTransactionState, and TransactionStateData::curTransactionOwner.

Referenced by AbortSubTransaction().

1687 {
1689 
1690  /* Make sure we have a valid ResourceOwner */
1692 }
static TransactionState CurrentTransactionState
Definition: xact.c:232
ResourceOwner CurrentResourceOwner
Definition: resowner.c:138
ResourceOwner curTransactionOwner
Definition: xact.c:181
static void AtSubCleanup_Memory ( void  )
static

Definition at line 1767 of file xact.c.

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

Referenced by CleanupSubTransaction().

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

Definition at line 1440 of file xact.c.

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

Referenced by CommitSubTransaction().

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

Definition at line 1411 of file xact.c.

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

Referenced by CommitSubTransaction().

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

Definition at line 1069 of file xact.c.

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

Referenced by StartSubTransaction().

1070 {
1072 
1074 
1075  /*
1076  * Create a CurTransactionContext, which will be used to hold data that
1077  * survives subtransaction commit but disappears on subtransaction abort.
1078  * We make it a child of the immediate parent's CurTransactionContext.
1079  */
1081  "CurTransactionContext",
1084 
1085  /* Make the CurTransactionContext active. */
1087 }
static TransactionState CurrentTransactionState
Definition: xact.c:232
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
MemoryContext CurTransactionContext
Definition: mcxt.c:49
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:165
MemoryContext curTransactionContext
Definition: xact.c:180
MemoryContext AllocSetContextCreate(MemoryContext parent, const char *name, Size minContextSize, Size initBlockSize, Size maxBlockSize)
Definition: aset.c:322
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:675
static void AtSubStart_ResourceOwner ( void  )
static

Definition at line 1093 of file xact.c.

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

Referenced by StartSubTransaction().

1094 {
1096 
1097  Assert(s->parent != NULL);
1098 
1099  /*
1100  * Create a resource owner for the subtransaction. We make it a child of
1101  * the immediate parent's resource owner.
1102  */
1103  s->curTransactionOwner =
1105  "SubTransaction");
1106 
1109 }
static TransactionState CurrentTransactionState
Definition: xact.c:232
ResourceOwner CurTransactionResourceOwner
Definition: resowner.c:139
ResourceOwner CurrentResourceOwner
Definition: resowner.c:138
ResourceOwner curTransactionOwner
Definition: xact.c:181
struct TransactionStateData * parent
Definition: xact.c:191
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:675
ResourceOwner ResourceOwnerCreate(ResourceOwner parent, const char *name)
Definition: resowner.c:416
void BeginInternalSubTransaction ( char *  name)

Definition at line 4053 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_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().

4054 {
4056 
4057  /*
4058  * Workers synchronize transaction state at the beginning of each parallel
4059  * operation, so we can't account for new subtransactions after that
4060  * point. We might be able to make an exception for the type of
4061  * subtransaction established by this function, which is typically used in
4062  * contexts where we're going to release or roll back the subtransaction
4063  * before proceeding further, so that no enduring change to the
4064  * transaction state occurs. For now, however, we prohibit this case along
4065  * with all the others.
4066  */
4067  if (IsInParallelMode())
4068  ereport(ERROR,
4069  (errcode(ERRCODE_INVALID_TRANSACTION_STATE),
4070  errmsg("cannot start subtransactions during a parallel operation")));
4071 
4072  switch (s->blockState)
4073  {
4074  case TBLOCK_STARTED:
4075  case TBLOCK_INPROGRESS:
4076  case TBLOCK_END:
4077  case TBLOCK_PREPARE:
4078  case TBLOCK_SUBINPROGRESS:
4079  /* Normal subtransaction start */
4080  PushTransaction();
4081  s = CurrentTransactionState; /* changed by push */
4082 
4083  /*
4084  * Savepoint names, like the TransactionState block itself, live
4085  * in TopTransactionContext.
4086  */
4087  if (name)
4089  break;
4090 
4091  /* These cases are invalid. */
4092  case TBLOCK_DEFAULT:
4093  case TBLOCK_BEGIN:
4095  case TBLOCK_SUBBEGIN:
4096  case TBLOCK_SUBRELEASE:
4097  case TBLOCK_SUBCOMMIT:
4098  case TBLOCK_ABORT:
4099  case TBLOCK_SUBABORT:
4100  case TBLOCK_ABORT_END:
4101  case TBLOCK_SUBABORT_END:
4102  case TBLOCK_ABORT_PENDING:
4104  case TBLOCK_SUBRESTART:
4106  elog(FATAL, "BeginInternalSubTransaction: unexpected state %s",
4108  break;
4109  }
4110 
4113 }
static TransactionState CurrentTransactionState
Definition: xact.c:232
MemoryContext TopTransactionContext
Definition: mcxt.c:48
void CommitTransactionCommand(void)
Definition: xact.c:2747
int errcode(int sqlerrcode)
Definition: elog.c:575
TBlockState blockState
Definition: xact.c:177
bool IsInParallelMode(void)
Definition: xact.c:913
#define ERROR
Definition: elog.h:43
#define FATAL
Definition: elog.h:52
static const char * BlockStateAsString(TBlockState blockState)
Definition: xact.c:5003
#define ereport(elevel, rest)
Definition: elog.h:122
static void PushTransaction(void)
Definition: xact.c:4723
void StartTransactionCommand(void)
Definition: xact.c:2677
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:1064
#define elog
Definition: elog.h:219
void BeginTransactionBlock ( void  )

Definition at line 3415 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_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().

3416 {
3418 
3419  switch (s->blockState)
3420  {
3421  /*
3422  * We are not inside a transaction block, so allow one to begin.
3423  */
3424  case TBLOCK_STARTED:
3425  s->blockState = TBLOCK_BEGIN;
3426  break;
3427 
3428  /*
3429  * Already a transaction block in progress.
3430  */
3431  case TBLOCK_INPROGRESS:
3433  case TBLOCK_SUBINPROGRESS:
3434  case TBLOCK_ABORT:
3435  case TBLOCK_SUBABORT:
3436  ereport(WARNING,
3437  (errcode(ERRCODE_ACTIVE_SQL_TRANSACTION),
3438  errmsg("there is already a transaction in progress")));
3439  break;
3440 
3441  /* These cases are invalid. */
3442  case TBLOCK_DEFAULT:
3443  case TBLOCK_BEGIN:
3444  case TBLOCK_SUBBEGIN:
3445  case TBLOCK_END:
3446  case TBLOCK_SUBRELEASE:
3447  case TBLOCK_SUBCOMMIT:
3448  case TBLOCK_ABORT_END:
3449  case TBLOCK_SUBABORT_END:
3450  case TBLOCK_ABORT_PENDING:
3452  case TBLOCK_SUBRESTART:
3454  case TBLOCK_PREPARE:
3455  elog(FATAL, "BeginTransactionBlock: unexpected state %s",
3457  break;
3458  }
3459 }
static TransactionState CurrentTransactionState
Definition: xact.c:232
int errcode(int sqlerrcode)
Definition: elog.c:575
TBlockState blockState
Definition: xact.c:177
#define FATAL
Definition: elog.h:52
static const char * BlockStateAsString(TBlockState blockState)
Definition: xact.c:5003
#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
static const char * BlockStateAsString ( TBlockState  blockState)
static

Definition at line 5003 of file xact.c.

References TBLOCK_ABORT, TBLOCK_ABORT_END, TBLOCK_ABORT_PENDING, TBLOCK_BEGIN, TBLOCK_DEFAULT, TBLOCK_END, 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().

5004 {
5005  switch (blockState)
5006  {
5007  case TBLOCK_DEFAULT:
5008  return "DEFAULT";
5009  case TBLOCK_STARTED:
5010  return "STARTED";
5011  case TBLOCK_BEGIN:
5012  return "BEGIN";
5013  case TBLOCK_INPROGRESS:
5014  return "INPROGRESS";
5016  return "PARALLEL_INPROGRESS";
5017  case TBLOCK_END:
5018  return "END";
5019  case TBLOCK_ABORT:
5020  return "ABORT";
5021  case TBLOCK_ABORT_END:
5022  return "ABORT END";
5023  case TBLOCK_ABORT_PENDING:
5024  return "ABORT PEND";
5025  case TBLOCK_PREPARE:
5026  return "PREPARE";
5027  case TBLOCK_SUBBEGIN:
5028  return "SUB BEGIN";
5029  case TBLOCK_SUBINPROGRESS:
5030  return "SUB INPROGRS";
5031  case TBLOCK_SUBRELEASE:
5032  return "SUB RELEASE";
5033  case TBLOCK_SUBCOMMIT:
5034  return "SUB COMMIT";
5035  case TBLOCK_SUBABORT:
5036  return "SUB ABORT";
5037  case TBLOCK_SUBABORT_END:
5038  return "SUB ABORT END";
5040  return "SUB ABRT PEND";
5041  case TBLOCK_SUBRESTART:
5042  return "SUB RESTART";
5044  return "SUB AB RESTRT";
5045  }
5046  return "UNRECOGNIZED";
5047 }
static void CallSubXactCallbacks ( SubXactEvent  event,
SubTransactionId  mySubid,
SubTransactionId  parentSubid 
)
static

Definition at line 3394 of file xact.c.

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

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

3397 {
3398  SubXactCallbackItem *item;
3399 
3400  for (item = SubXact_callbacks; item; item = item->next)
3401  (*item->callback) (event, mySubid, parentSubid, item->arg);
3402 }
static SubXactCallbackItem * SubXact_callbacks
Definition: xact.c:293
struct SubXactCallbackItem * next
Definition: xact.c:288
SubXactCallback callback
Definition: xact.c:289
static void CallXactCallbacks ( XactEvent  event)
static

Definition at line 3339 of file xact.c.

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

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

3340 {
3341  XactCallbackItem *item;
3342 
3343  for (item = Xact_callbacks; item; item = item->next)
3344  (*item->callback) (event, item->arg);
3345 }
struct XactCallbackItem * next
Definition: xact.c:276
void * arg
Definition: xact.c:278
XactCallback callback
Definition: xact.c:277
static XactCallbackItem * Xact_callbacks
Definition: xact.c:281
static void CheckTransactionChain ( bool  isTopLevel,
bool  throwError,
const char *  stmtType 
)
static

Definition at line 3231 of file xact.c.

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

Referenced by RequireTransactionChain(), and WarnNoTransactionChain().

3232 {
3233  /*
3234  * xact block already started?
3235  */
3236  if (IsTransactionBlock())
3237  return;
3238 
3239  /*
3240  * subtransaction?
3241  */
3242  if (IsSubTransaction())
3243  return;
3244 
3245  /*
3246  * inside a function call?
3247  */
3248  if (!isTopLevel)
3249  return;
3250 
3251  ereport(throwError ? ERROR : WARNING,
3252  (errcode(ERRCODE_NO_ACTIVE_SQL_TRANSACTION),
3253  /* translator: %s represents an SQL statement name */
3254  errmsg("%s can only be used in transaction blocks",
3255  stmtType)));
3256  return;
3257 }
int errcode(int sqlerrcode)
Definition: elog.c:575
bool IsTransactionBlock(void)
Definition: xact.c:4304
#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:4376
int errmsg(const char *fmt,...)
Definition: elog.c:797
static void CleanupSubTransaction ( void  )
static

Definition at line 4690 of file xact.c.

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

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

4691 {
4693 
4694  ShowTransactionState("CleanupSubTransaction");
4695 
4696  if (s->state != TRANS_ABORT)
4697  elog(WARNING, "CleanupSubTransaction while in %s state",
4699 
4701 
4704  if (s->curTransactionOwner)
4707 
4709 
4710  s->state = TRANS_DEFAULT;
4711 
4712  PopTransaction();
4713 }
static TransactionState CurrentTransactionState
Definition: xact.c:232
static void PopTransaction(void)
Definition: xact.c:4782
ResourceOwner CurTransactionResourceOwner
Definition: resowner.c:139
ResourceOwner CurrentResourceOwner
Definition: resowner.c:138
void ResourceOwnerDelete(ResourceOwner owner)
Definition: resowner.c:687
TransState state
Definition: xact.c:176
ResourceOwner curTransactionOwner
Definition: xact.c:181
struct TransactionStateData * parent
Definition: xact.c:191
static void ShowTransactionState(const char *str)
Definition: xact.c:4952
SubTransactionId subTransactionId
Definition: xact.c:173
void AtSubCleanup_Portals(SubTransactionId mySubid)
Definition: portalmem.c:1007
#define WARNING
Definition: elog.h:40
static void AtSubCleanup_Memory(void)
Definition: xact.c:1767
#define NULL
Definition: c.h:229
static const char * TransStateAsString(TransState state)
Definition: xact.c:5054
#define elog
Definition: elog.h:219
static void CleanupTransaction ( void  )
static

Definition at line 2628 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, NULL, TransactionStateData::parallelModeLevel, ResourceOwnerDelete(), TransactionStateData::state, TransactionStateData::subTransactionId, TopTransactionResourceOwner, TRANS_ABORT, TRANS_DEFAULT, TransactionStateData::transactionId, TransStateAsString(), and XactTopTransactionId.

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

2629 {
2631 
2632  /*
2633  * State should still be TRANS_ABORT from AbortTransaction().
2634  */
2635  if (s->state != TRANS_ABORT)
2636  elog(FATAL, "CleanupTransaction: unexpected state %s",
2638 
2639  /*
2640  * do abort cleanup processing
2641  */
2642  AtCleanup_Portals(); /* now safe to release portal memory */
2643  AtEOXact_Snapshot(false); /* and release the transaction's snapshots */
2644 
2645  CurrentResourceOwner = NULL; /* and resource owner */
2651 
2652  AtCleanup_Memory(); /* and transaction memory */
2653 
2656  s->nestingLevel = 0;
2657  s->gucNestLevel = 0;
2658  s->childXids = NULL;
2659  s->nChildXids = 0;
2660  s->maxChildXids = 0;
2661  s->parallelModeLevel = 0;
2662 
2665 
2666  /*
2667  * done with abort processing, set current transaction state back to
2668  * default
2669  */
2670  s->state = TRANS_DEFAULT;
2671 }
TransactionId XactTopTransactionId
Definition: xact.c:107
static TransactionState CurrentTransactionState
Definition: xact.c:232
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:687
static void AtCleanup_Memory(void)
Definition: xact.c:1731
int nParallelCurrentXids
Definition: xact.c:108
void AtCleanup_Portals(void)
Definition: portalmem.c:818
TransactionId * childXids
Definition: xact.c:182
TransState state
Definition: xact.c:176
ResourceOwner curTransactionOwner
Definition: xact.c:181
#define FATAL
Definition: elog.h:52
void AtEOXact_Snapshot(bool isCommit)
Definition: snapmgr.c:1054
#define InvalidTransactionId
Definition: transam.h:31
SubTransactionId subTransactionId
Definition: xact.c:173
TransactionId transactionId
Definition: xact.c:172
int parallelModeLevel
Definition: xact.c:190
#define NULL
Definition: c.h:229
static const char * TransStateAsString(TransState state)
Definition: xact.c:5054
#define InvalidSubTransactionId
Definition: c.h:403
#define elog
Definition: elog.h:219
void CommandCounterIncrement ( void  )

Definition at line 922 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(), ATExecSetTableSpace(), CommitSubTransaction(), CommitTransactionCommand(), 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().

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

Definition at line 4437 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, NULL, 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().

4438 {
4440 
4441  ShowTransactionState("CommitSubTransaction");
4442 
4443  if (s->state != TRANS_INPROGRESS)
4444  elog(WARNING, "CommitSubTransaction while in %s state",
4446 
4447  /* Pre-commit processing goes here */
4448 
4450  s->parent->subTransactionId);
4451 
4452  /* If in parallel mode, clean up workers and exit parallel mode. */
4453  if (IsInParallelMode())
4454  {
4456  s->parallelModeLevel = 0;
4457  }
4458 
4459  /* Do the actual "commit", such as it is */
4460  s->state = TRANS_COMMIT;
4461 
4462  /* Must CCI to ensure commands of subtransaction are seen as done */
4464 
4465  /*
4466  * Prior to 8.4 we marked subcommit in clog at this point. We now only
4467  * perform that step, if required, as part of the atomic update of the
4468  * whole transaction tree at top level commit or abort.
4469  */
4470 
4471  /* Post-commit cleanup */
4474  AfterTriggerEndSubXact(true);
4479  s->parent->subTransactionId);
4481 
4483  s->parent->subTransactionId);
4484 
4487  true, false);
4489  s->parent->subTransactionId);
4490  AtEOSubXact_Inval(true);
4491  AtSubCommit_smgr();
4492 
4493  /*
4494  * The only lock we actually release here is the subtransaction XID lock.
4495  */
4499 
4500  /*
4501  * Other locks should get transferred to their parent resource owner.
4502  */
4505  true, false);
4508  true, false);
4509 
4510  AtEOXact_GUC(true, s->gucNestLevel);
4513  s->parent->subTransactionId);
4515  s->parent->subTransactionId);
4517  s->parent->subTransactionId);
4519  AtEOSubXact_PgStat(true, s->nestingLevel);
4521 
4522  /*
4523  * We need to restore the upper transaction's read-only state, in case the
4524  * upper is read-write while the child is read-only; GUC will incorrectly
4525  * think it should leave the child state in place.
4526  */
4528 
4533 
4535 
4536  s->state = TRANS_DEFAULT;
4537 
4538  PopTransaction();
4539 }
void AtEOSubXact_RelationCache(bool isCommit, SubTransactionId mySubid, SubTransactionId parentSubid)
Definition: relcache.c:3066
static TransactionState CurrentTransactionState
Definition: xact.c:232
static void AtSubCommit_Memory(void)
Definition: xact.c:1411
static void PopTransaction(void)
Definition: xact.c:4782
ResourceOwner CurTransactionResourceOwner
Definition: resowner.c:139
ResourceOwner CurrentResourceOwner
Definition: resowner.c:138
void AtEOSubXact_HashTables(bool isCommit, int nestDepth)
Definition: dynahash.c:1824
void ResourceOwnerDelete(ResourceOwner owner)
Definition: resowner.c:687
void AtSubCommit_smgr(void)
Definition: storage.c:451
void AtEOSubXact_SPI(bool isCommit, SubTransactionId mySubid)
Definition: spi.c:214
void AtSubCommit_Snapshot(int level)
Definition: snapmgr.c:997
static void AtSubCommit_childXids(void)
Definition: xact.c:1440
TransState state
Definition: xact.c:176
ResourceOwner curTransactionOwner
Definition: xact.c:181
bool IsInParallelMode(void)
Definition: xact.c:913
struct TransactionStateData * parent
Definition: xact.c:191
void AtSubCommit_Notify(void)
Definition: async.c:1634
static void ShowTransactionState(const char *str)
Definition: xact.c:4952
void AtEOXact_GUC(bool isCommit, int nestLevel)
Definition: guc.c:5058
SubTransactionId subTransactionId
Definition: xact.c:173
void AtEOSubXact_PgStat(bool isCommit, int nestDepth)
Definition: pgstat.c:2035
void AtEOSubXact_LargeObject(bool isCommit, SubTransactionId mySubid, SubTransactionId parentSubid)
Definition: be-fsstubs.c:674
#define WARNING
Definition: elog.h:40
void AtEOSubXact_on_commit_actions(bool isCommit, SubTransactionId mySubid, SubTransactionId parentSubid)
Definition: tablecmds.c:12561
void CommandCounterIncrement(void)
Definition: xact.c:922
void AtEOSubXact_Files(bool isCommit, SubTransactionId mySubid, SubTransactionId parentSubid)
Definition: fd.c:2549
TransactionId transactionId
Definition: xact.c:172
static void CallSubXactCallbacks(SubXactEvent event, SubTransactionId mySubid, SubTransactionId parentSubid)
Definition: xact.c:3394
bool XactReadOnly
Definition: xact.c:77
int parallelModeLevel
Definition: xact.c:190
#define NULL
Definition: c.h:229
void ResourceOwnerRelease(ResourceOwner owner, ResourceReleasePhase phase, bool isCommit, bool isTopLevel)
Definition: resowner.c:471
static const char * TransStateAsString(TransState state)
Definition: xact.c:5054
bool prevXactReadOnly
Definition: xact.c:187
void AfterTriggerEndSubXact(bool isCommit)
Definition: trigger.c:4442
void AtEOSubXact_Inval(bool isCommit)
Definition: inval.c:981
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:3793
#define TransactionIdIsValid(xid)
Definition: transam.h:41
void AtEOSubXact_Parallel(bool isCommit, SubTransactionId mySubId)
Definition: parallel.c:899
void AtSubCommit_Portals(SubTransactionId mySubid, SubTransactionId parentSubid, ResourceOwner parentXactOwner)
Definition: portalmem.c:860
static void CommitTransaction ( void  )
static

Definition at line 1940 of file xact.c.

References AfterTriggerEndXact(), AfterTriggerFireDeferred(), Assert, AtCommit_ApplyLauncher(), AtCommit_Memory(), AtCommit_Notify(), AtEOXact_Buffers(), AtEOXact_CatCache(), 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, NULL, 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().

1941 {
1943  TransactionId latestXid;
1944  bool is_parallel_worker;
1945 
1946  is_parallel_worker = (s->blockState == TBLOCK_PARALLEL_INPROGRESS);
1947 
1948  /* Enforce parallel mode restrictions during parallel worker commit. */
1949  if (is_parallel_worker)
1951 
1952  ShowTransactionState("CommitTransaction");
1953 
1954  /*
1955  * check the current transaction state
1956  */
1957  if (s->state != TRANS_INPROGRESS)
1958  elog(WARNING, "CommitTransaction while in %s state",
1960  Assert(s->parent == NULL);
1961 
1962  /*
1963  * Do pre-commit processing that involves calling user-defined code, such
1964  * as triggers. Since closing cursors could queue trigger actions,
1965  * triggers could open cursors, etc, we have to keep looping until there's
1966  * nothing left to do.
1967  */
1968  for (;;)
1969  {
1970  /*
1971  * Fire all currently pending deferred triggers.
1972  */
1974 
1975  /*
1976  * Close open portals (converting holdable ones into static portals).
1977  * If there weren't any, we are done ... otherwise loop back to check
1978  * if they queued deferred triggers. Lather, rinse, repeat.
1979  */
1980  if (!PreCommit_Portals(false))
1981  break;
1982  }
1983 
1986 
1987  /*
1988  * The remaining actions cannot call any user-defined code, so it's safe
1989  * to start shutting down within-transaction services. But note that most
1990  * of this stuff could still throw an error, which would switch us into
1991  * the transaction-abort path.
1992  */
1993 
1994  /* If we might have parallel workers, clean them up now. */
1995  if (IsInParallelMode())
1996  AtEOXact_Parallel(true);
1997 
1998  /* Shut down the deferred-trigger manager */
1999  AfterTriggerEndXact(true);
2000 
2001  /*
2002  * Let ON COMMIT management do its thing (must happen after closing
2003  * cursors, to avoid dangling-reference problems)
2004  */
2006 
2007  /* close large objects before lower-level cleanup */
2008  AtEOXact_LargeObject(true);
2009 
2010  /*
2011  * Mark serializable transaction as complete for predicate locking
2012  * purposes. This should be done as late as we can put it and still allow
2013  * errors to be raised for failure patterns found at commit.
2014  */
2016 
2017  /*
2018  * Insert notifications sent by NOTIFY commands into the queue. This
2019  * should be late in the pre-commit sequence to minimize time spent
2020  * holding the notify-insertion lock.
2021  */
2022  PreCommit_Notify();
2023 
2024  /* Prevent cancel/die interrupt while cleaning up */
2025  HOLD_INTERRUPTS();
2026 
2027  /* Commit updates to the relation map --- do this as late as possible */
2028  AtEOXact_RelationMap(true);
2029 
2030  /*
2031  * set the current transaction state information appropriately during
2032  * commit processing
2033  */
2034  s->state = TRANS_COMMIT;
2035  s->parallelModeLevel = 0;
2036 
2037  if (!is_parallel_worker)
2038  {
2039  /*
2040  * We need to mark our XIDs as committed in pg_xact. This is where we
2041  * durably commit.
2042  */
2043  latestXid = RecordTransactionCommit();
2044  }
2045  else
2046  {
2047  /*
2048  * We must not mark our XID committed; the parallel master is
2049  * responsible for that.
2050  */
2051  latestXid = InvalidTransactionId;
2052 
2053  /*
2054  * Make sure the master will know about any WAL we wrote before it
2055  * commits.
2056  */
2058  }
2059 
2060  TRACE_POSTGRESQL_TRANSACTION_COMMIT(MyProc->lxid);
2061 
2062  /*
2063  * Let others know about no transaction in progress by me. Note that this
2064  * must be done _before_ releasing locks we hold and _after_
2065  * RecordTransactionCommit.
2066  */
2067  ProcArrayEndTransaction(MyProc, latestXid);
2068 
2069  /*
2070  * This is all post-commit cleanup. Note that if an error is raised here,
2071  * it's too late to abort the transaction. This should be just
2072  * noncritical resource releasing.
2073  *
2074  * The ordering of operations is not entirely random. The idea is:
2075  * release resources visible to other backends (eg, files, buffer pins);
2076  * then release locks; then release backend-local resources. We want to
2077  * release locks at the point where any backend waiting for us will see
2078  * our transaction as being fully cleaned up.
2079  *
2080  * Resources that can be associated with individual queries are handled by
2081  * the ResourceOwner mechanism. The other calls here are for backend-wide
2082  * state.
2083  */
2084 
2085  CallXactCallbacks(is_parallel_worker ? XACT_EVENT_PARALLEL_COMMIT
2086  : XACT_EVENT_COMMIT);
2087 
2090  true, true);
2091 
2092  /* Check we've released all buffer pins */
2093  AtEOXact_Buffers(true);
2094 
2095  /* Clean up the relation cache */
2096  AtEOXact_RelationCache(true);
2097 
2098  /*
2099  * Make catalog changes visible to all backends. This has to happen after
2100  * relcache references are dropped (see comments for
2101  * AtEOXact_RelationCache), but before locks are released (if anyone is
2102  * waiting for lock on a relation we've modified, we want them to know
2103  * about the catalog change before they start using the relation).
2104  */
2105  AtEOXact_Inval(true);
2106 
2108 
2111  true, true);
2114  true, true);
2115 
2116  /*
2117  * Likewise, dropping of files deleted during the transaction is best done
2118  * after releasing relcache and buffer pins. (This is not strictly
2119  * necessary during commit, since such pins should have been released
2120  * already, but this ordering is definitely critical during abort.) Since
2121  * this may take many seconds, also delay until after releasing locks.
2122  * Other backends will observe the attendant catalog changes and not
2123  * attempt to access affected files.
2124  */
2125  smgrDoPendingDeletes(true);
2126 
2127  /* Check we've released all catcache entries */
2128  AtEOXact_CatCache(true);
2129 
2130  AtCommit_Notify();
2131  AtEOXact_GUC(true, 1);
2132  AtEOXact_SPI(true);
2134  AtEOXact_Namespace(true, is_parallel_worker);
2135  AtEOXact_SMgr();
2136  AtEOXact_Files();
2138  AtEOXact_HashTables(true);
2139  AtEOXact_PgStat(true);
2140  AtEOXact_Snapshot(true);
2143 
2149 
2150  AtCommit_Memory();
2151 
2154  s->nestingLevel = 0;
2155  s->gucNestLevel = 0;
2156  s->childXids = NULL;
2157  s->nChildXids = 0;
2158  s->maxChildXids = 0;
2159 
2162 
2163  /*
2164  * done with commit processing, set current transaction state back to
2165  * default
2166  */
2167  s->state = TRANS_DEFAULT;
2168 
2170 }
TransactionId XactTopTransactionId
Definition: xact.c:107
void smgrDoPendingDeletes(bool isCommit)
Definition: storage.c:306
static TransactionState CurrentTransactionState
Definition: xact.c:232
void AtEOXact_Inval(bool isCommit)
Definition: inval.c:922
uint32 TransactionId
Definition: c.h:397
static void AtCommit_Memory(void)
Definition: xact.c:1384
void pgstat_report_xact_timestamp(TimestampTz tstamp)
Definition: pgstat.c:3004
XLogRecPtr XactLastRecEnd
Definition: xlog.c:337
void AtEOXact_RelationCache(bool isCommit)
Definition: relcache.c:2915
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 AtEOXact_CatCache(bool isCommit)
Definition: catcache.c:548
void ResourceOwnerDelete(ResourceOwner owner)
Definition: resowner.c:687
static void CallXactCallbacks(XactEvent event)
Definition: xact.c:3339
int nParallelCurrentXids
Definition: xact.c:108
void AtEOXact_on_commit_actions(bool isCommit)
Definition: tablecmds.c:12519
void ProcArrayEndTransaction(PGPROC *proc, TransactionId latestXid)
Definition: procarray.c:394
static TransactionId RecordTransactionCommit(void)
Definition: xact.c:1125
TBlockState blockState
Definition: xact.c:177
TransactionId * childXids
Definition: xact.c:182
void PreCommit_CheckForSerializationFailure(void)
Definition: predicate.c:4629
#define RESUME_INTERRUPTS()
Definition: miscadmin.h:116
void PreCommit_Notify(void)
Definition: async.c:772
TransState state
Definition: xact.c:176
ResourceOwner curTransactionOwner
Definition: xact.c:181
void AtEOXact_SMgr(void)
Definition: smgr.c:798
bool IsInParallelMode(void)
Definition: xact.c:913
void AfterTriggerEndXact(bool isCommit)
Definition: trigger.c:4320
void AtEOXact_Files(void)
Definition: fd.c:2580
struct TransactionStateData * parent
Definition: xact.c:191
static void ShowTransactionState(const char *str)
Definition: xact.c:4952
void AtEOXact_Snapshot(bool isCommit)
Definition: snapmgr.c:1054
void AtEOXact_GUC(bool isCommit, int nestLevel)
Definition: guc.c:5058
#define InvalidTransactionId
Definition: transam.h:31
SubTransactionId subTransactionId
Definition: xact.c:173
#define WARNING
Definition: elog.h:40
void AtCommit_ApplyLauncher(void)
Definition: launcher.c:601
TransactionId transactionId
Definition: xact.c:172
void ParallelWorkerReportLastRecEnd(XLogRecPtr last_xlog_end)
Definition: parallel.c:1156
void AtEOXact_ComboCid(void)
Definition: combocid.c:183
void AfterTriggerFireDeferred(void)
Definition: trigger.c:4264
int parallelModeLevel
Definition: xact.c:190
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:675
void ResourceOwnerRelease(ResourceOwner owner, ResourceReleasePhase phase, bool isCommit, bool isTopLevel)
Definition: resowner.c:471
static const char * TransStateAsString(TransState state)
Definition: xact.c:5054
void AtEOXact_SPI(bool isCommit)
Definition: spi.c:186
void AtEOXact_MultiXact(void)
Definition: multixact.c:1662
void EnterParallelMode(void)
Definition: xact.c:880
#define InvalidSubTransactionId
Definition: c.h:403
bool PreCommit_Portals(bool isPrepare)
Definition: portalmem.c:630
void PreCommit_on_commit_actions(void)
Definition: tablecmds.c:12448
void AtCommit_Notify(void)
Definition: async.c:871
#define HOLD_INTERRUPTS()
Definition: miscadmin.h:114
#define elog
Definition: elog.h:219
void AtEOXact_HashTables(bool isCommit)
Definition: dynahash.c:1798
void AtEOXact_LargeObject(bool isCommit)
Definition: be-fsstubs.c:633
void AtEOXact_Parallel(bool isCommit)
Definition: parallel.c:918
void AtEOXact_Namespace(bool isCommit, bool parallel)
Definition: namespace.c:3738
void AtEOXact_PgStat(bool isCommit)
Definition: pgstat.c:1952
LocalTransactionId lxid
Definition: proc.h:100
void CommitTransactionCommand ( void  )

Definition at line 2747 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, name, NULL, TransactionStateData::parent, PrepareTransaction(), TransactionStateData::savepointLevel, StartSubTransaction(), TBLOCK_ABORT, TBLOCK_ABORT_END, TBLOCK_ABORT_PENDING, TBLOCK_BEGIN, TBLOCK_DEFAULT, TBLOCK_END, 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(), BeginInternalSubTransaction(), cluster(), CommitTransactionCommand(), DefineIndex(), do_autovacuum(), finish_xact_command(), get_database_list(), get_subscription_list(), IdentifySystem(), index_drop(), initialize_worker_spi(), InitPostgres(), LogicalRepSyncTableStart(), movedb(), ParallelWorkerMain(), pg_attribute_noreturn(), process_syncing_tables_for_apply(), ProcessCatchupInterrupt(), ProcessCompletedNotifies(), ProcessIncomingNotify(), ReindexMultipleTables(), RemoveTempRelationsCallback(), reread_subscription(), vacuum(), and vacuum_rel().

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

Definition at line 3748 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_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().

3749 {
3751 
3752  /*
3753  * Workers synchronize transaction state at the beginning of each parallel
3754  * operation, so we can't account for new subtransactions after that
3755  * point. (Note that this check will certainly error out if s->blockState
3756  * is TBLOCK_PARALLEL_INPROGRESS, so we can treat that as an invalid case
3757  * below.)
3758  */
3759  if (IsInParallelMode())
3760  ereport(ERROR,
3761  (errcode(ERRCODE_INVALID_TRANSACTION_STATE),
3762  errmsg("cannot define savepoints during a parallel operation")));
3763 
3764  switch (s->blockState)
3765  {
3766  case TBLOCK_INPROGRESS:
3767  case TBLOCK_SUBINPROGRESS:
3768  /* Normal subtransaction start */
3769  PushTransaction();
3770  s = CurrentTransactionState; /* changed by push */
3771 
3772  /*
3773  * Savepoint names, like the TransactionState block itself, live
3774  * in TopTransactionContext.
3775  */
3776  if (name)
3778  break;
3779 
3780  /* These cases are invalid. */
3781  case TBLOCK_DEFAULT:
3782  case TBLOCK_STARTED:
3783  case TBLOCK_BEGIN:
3785  case TBLOCK_SUBBEGIN:
3786  case TBLOCK_END:
3787  case TBLOCK_SUBRELEASE:
3788  case TBLOCK_SUBCOMMIT:
3789  case TBLOCK_ABORT:
3790  case TBLOCK_SUBABORT:
3791  case TBLOCK_ABORT_END:
3792  case TBLOCK_SUBABORT_END:
3793  case TBLOCK_ABORT_PENDING:
3795  case TBLOCK_SUBRESTART:
3797  case TBLOCK_PREPARE:
3798  elog(FATAL, "DefineSavepoint: unexpected state %s",
3800  break;
3801  }
3802 }
static TransactionState CurrentTransactionState
Definition: xact.c:232
MemoryContext TopTransactionContext
Definition: mcxt.c:48
int errcode(int sqlerrcode)
Definition: elog.c:575
TBlockState blockState
Definition: xact.c:177
bool IsInParallelMode(void)
Definition: xact.c:913
#define ERROR
Definition: elog.h:43
#define FATAL
Definition: elog.h:52
static const char * BlockStateAsString(TBlockState blockState)
Definition: xact.c:5003
#define ereport(elevel, rest)
Definition: elog.h:122
static void PushTransaction(void)
Definition: xact.c:4723
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:1064
#define elog
Definition: elog.h:219
void EndParallelWorkerTransaction ( void  )

Definition at line 4940 of file xact.c.

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

Referenced by ParallelWorkerMain().

4941 {
4945 }
static TransactionState CurrentTransactionState
Definition: xact.c:232
TBlockState blockState
Definition: xact.c:177
#define Assert(condition)
Definition: c.h:675
static void CommitTransaction(void)
Definition: xact.c:1940
bool EndTransactionBlock ( void  )

Definition at line 3525 of file xact.c.

References TransactionStateData::blockState, BlockStateAsString(), CurrentTransactionState, elog, ereport, errcode(), errmsg(), FATAL, NULL, TransactionStateData::parent, result, TBLOCK_ABORT, TBLOCK_ABORT_END, TBLOCK_ABORT_PENDING, TBLOCK_BEGIN, TBLOCK_DEFAULT, TBLOCK_END, 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().

3526 {
3528  bool result = false;
3529 
3530  switch (s->blockState)
3531  {
3532  /*
3533  * We are in a transaction block, so tell CommitTransactionCommand
3534  * to COMMIT.
3535  */
3536  case TBLOCK_INPROGRESS:
3537  s->blockState = TBLOCK_END;
3538  result = true;
3539  break;
3540 
3541  /*
3542  * We are in a failed transaction block. Tell
3543  * CommitTransactionCommand it's time to exit the block.
3544  */
3545  case TBLOCK_ABORT:
3547  break;
3548 
3549  /*
3550  * We are in a live subtransaction block. Set up to subcommit all
3551  * open subtransactions and then commit the main transaction.
3552  */
3553  case TBLOCK_SUBINPROGRESS:
3554  while (s->parent != NULL)
3555  {
3556  if (s->blockState == TBLOCK_SUBINPROGRESS)
3558  else
3559  elog(FATAL, "EndTransactionBlock: unexpected state %s",
3561  s = s->parent;
3562  }
3563  if (s->blockState == TBLOCK_INPROGRESS)
3564  s->blockState = TBLOCK_END;
3565  else
3566  elog(FATAL, "EndTransactionBlock: unexpected state %s",
3568  result = true;
3569  break;
3570 
3571  /*
3572  * Here we are inside an aborted subtransaction. Treat the COMMIT
3573  * as ROLLBACK: set up to abort everything and exit the main
3574  * transaction.
3575  */
3576  case TBLOCK_SUBABORT:
3577  while (s->parent != NULL)
3578  {
3579  if (s->blockState == TBLOCK_SUBINPROGRESS)
3581  else if (s->blockState == TBLOCK_SUBABORT)
3583  else
3584  elog(FATAL, "EndTransactionBlock: unexpected state %s",
3586  s = s->parent;
3587  }
3588  if (s->blockState == TBLOCK_INPROGRESS)
3590  else if (s->blockState == TBLOCK_ABORT)
3592  else
3593  elog(FATAL, "EndTransactionBlock: unexpected state %s",
3595  break;
3596 
3597  /*
3598  * The user issued COMMIT when not inside a transaction. Issue a
3599  * WARNING, staying in TBLOCK_STARTED state. The upcoming call to
3600  * CommitTransactionCommand() will then close the transaction and
3601  * put us back into the default state.
3602  */
3603  case TBLOCK_STARTED:
3604  ereport(WARNING,
3605  (errcode(ERRCODE_NO_ACTIVE_SQL_TRANSACTION),
3606  errmsg("there is no transaction in progress")));
3607  result = true;
3608  break;
3609 
3610  /*
3611  * The user issued a COMMIT that somehow ran inside a parallel
3612  * worker. We can't cope with that.
3613  */
3615  ereport(FATAL,
3616  (errcode(ERRCODE_INVALID_TRANSACTION_STATE),
3617  errmsg("cannot commit during a parallel operation")));
3618  break;
3619 
3620  /* These cases are invalid. */
3621  case TBLOCK_DEFAULT:
3622  case TBLOCK_BEGIN:
3623  case TBLOCK_SUBBEGIN:
3624  case TBLOCK_END:
3625  case TBLOCK_SUBRELEASE:
3626  case TBLOCK_SUBCOMMIT:
3627  case TBLOCK_ABORT_END:
3628  case TBLOCK_SUBABORT_END:
3629  case TBLOCK_ABORT_PENDING:
3631  case TBLOCK_SUBRESTART:
3633  case TBLOCK_PREPARE:
3634  elog(FATAL, "EndTransactionBlock: unexpected state %s",
3636  break;
3637  }
3638 
3639  return result;
3640 }
static TransactionState CurrentTransactionState
Definition: xact.c:232
int errcode(int sqlerrcode)
Definition: elog.c:575
return result
Definition: formatting.c:1618
TBlockState blockState
Definition: xact.c:177
#define FATAL
Definition: elog.h:52
struct TransactionStateData * parent
Definition: xact.c:191
static const char * BlockStateAsString(TBlockState blockState)
Definition: xact.c:5003
#define ereport(elevel, rest)
Definition: elog.h:122
#define WARNING
Definition: elog.h:40
#define NULL
Definition: c.h:229
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define elog
Definition: elog.h:219
void EnterParallelMode ( void  )

Definition at line 880 of file xact.c.

References Assert, CurrentTransactionState, and TransactionStateData::parallelModeLevel.

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

881 {
883 
884  Assert(s->parallelModeLevel >= 0);
885 
886  ++s->parallelModeLevel;
887 }
static TransactionState CurrentTransactionState
Definition: xact.c:232
int parallelModeLevel
Definition: xact.c:190
#define Assert(condition)
Definition: c.h:675
Size EstimateTransactionStateSpace ( void  )

Definition at line 4816 of file xact.c.

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

Referenced by InitializeParallelDSM().

4817 {
4818  TransactionState s;
4819  Size nxids = 6; /* iso level, deferrable, top & current XID,
4820  * command counter, XID count */
4821 
4822  for (s = CurrentTransactionState; s != NULL; s = s->parent)
4823  {
4825  nxids = add_size(nxids, 1);
4826  nxids = add_size(nxids, s->nChildXids);
4827  }
4828 
4829  nxids = add_size(nxids, nParallelCurrentXids);
4830  return mul_size(nxids, sizeof(TransactionId));
4831 }
static TransactionState CurrentTransactionState
Definition: xact.c:232
uint32 TransactionId
Definition: c.h:397
int nParallelCurrentXids
Definition: xact.c:108
struct TransactionStateData * parent
Definition: xact.c:191
Size mul_size(Size s1, Size s2)
Definition: shmem.c:492
Size add_size(Size s1, Size s2)
Definition: shmem.c:475
TransactionId transactionId
Definition: xact.c:172
#define NULL
Definition: c.h:229
size_t Size
Definition: c.h:356
#define TransactionIdIsValid(xid)
Definition: transam.h:41
void ExitParallelMode ( void  )

Definition at line 893 of file xact.c.

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

Referenced by ExecutePlan(), and ParallelWorkerMain().

894 {
896 
897  Assert(s->parallelModeLevel > 0);
899 
900  --s->parallelModeLevel;
901 }
static TransactionState CurrentTransactionState
Definition: xact.c:232
bool ParallelContextActive(void)
Definition: parallel.c:681
int parallelModeLevel
Definition: xact.c:190
#define Assert(condition)
Definition: c.h:675
void ForceSyncCommit ( void  )

Definition at line 970 of file xact.c.

References forceSyncCommit.

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

971 {
972  forceSyncCommit = true;
973 }
static bool forceSyncCommit
Definition: xact.c:262
CommandId GetCurrentCommandId ( bool  used)

Definition at line 687 of file xact.c.

References Assert, currentCommandId, currentCommandIdUsed, and TransactionStateData::parallelModeLevel.

Referenced by ATRewriteTable(), CopyFrom(), 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().

688 {
689  /* this is global to a transaction, not subtransaction-local */
690  if (used)
691  {
692  /*
693  * Forbid setting currentCommandIdUsed in parallel mode, because we
694  * have no provision for communicating this back to the master. We
695  * could relax this restriction when currentCommandIdUsed was already
696  * true at the start of the parallel operation.
697  */
699  currentCommandIdUsed = true;
700  }
701  return currentCommandId;
702 }
static TransactionState CurrentTransactionState
Definition: xact.c:232
int parallelModeLevel
Definition: xact.c:190
#define Assert(condition)
Definition: c.h:675
static CommandId currentCommandId
Definition: xact.c:239
static bool currentCommandIdUsed
Definition: xact.c:240
TimestampTz GetCurrentStatementStartTimestamp ( void  )

Definition at line 717 of file xact.c.

References stmtStartTimestamp.

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

718 {
719  return stmtStartTimestamp;
720 }
static TimestampTz stmtStartTimestamp
Definition: xact.c:250
TransactionId GetCurrentTransactionIdIfAny ( void  )

Definition at line 434 of file xact.c.

References TransactionStateData::transactionId.

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

435 {
437 }
static TransactionState CurrentTransactionState
Definition: xact.c:232
TransactionId transactionId
Definition: xact.c:172
TimestampTz GetCurrentTransactionStartTimestamp ( void  )
TimestampTz GetCurrentTransactionStopTimestamp ( void  )

Definition at line 729 of file xact.c.

References GetCurrentTimestamp(), and xactStopTimestamp.

Referenced by pgstat_report_stat().

730 {
731  if (xactStopTimestamp != 0)
732  return xactStopTimestamp;
733  return GetCurrentTimestamp();
734 }
static TimestampTz xactStopTimestamp
Definition: xact.c:251
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1569
TransactionId GetStableLatestTransactionId ( void  )

Definition at line 461 of file xact.c.

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

Referenced by xid_age().

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

Definition at line 389 of file xact.c.

References AssignTransactionId(), TransactionIdIsValid, and XactTopTransactionId.

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

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

Definition at line 3270 of file xact.c.

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

Referenced by vacuum().

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

Definition at line 4304 of file xact.c.

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

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

4305 {
4307 
4309  return false;
4310 
4311  return true;
4312 }
static TransactionState CurrentTransactionState
Definition: xact.c:232
TBlockState blockState
Definition: xact.c:177
bool IsTransactionOrTransactionBlock ( void  )

Definition at line 4322 of file xact.c.

References TransactionStateData::blockState, CurrentTransactionState, and TBLOCK_DEFAULT.

Referenced by PostgresMain(), ProcessCatchupInterrupt(), ProcessNotifyInterrupt(), RecoveryConflictInterrupt(), ReorderBufferCommit(), ReorderBufferImmediateInvalidation(), SnapBuildExportSnapshot(), and StartupDecodingContext().

4323 {
4325 
4326  if (s->blockState == TBLOCK_DEFAULT)
4327  return false;
4328 
4329  return true;
4330 }
static TransactionState CurrentTransactionState
Definition: xact.c:232
TBlockState blockState
Definition: xact.c:177
bool IsTransactionState ( void  )

Definition at line 350 of file xact.c.

References CurrentTransactionState, TransactionStateData::state, and TRANS_INPROGRESS.

Referenced by apply_handle_commit(), apply_handle_origin(), check_client_encoding(), check_default_tablespace(), check_role(), check_session_authorization(), check_temp_tablespaces(), check_transaction_read_only(), check_TSCurrentConfig(), check_XactIsoLevel(), CreateInitDecodingContext(), ensure_transaction(), LogLogicalMessage(), 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(), reread_subscription(), SearchCatCache(), SetMultiXactIdLimit(), SetTransactionIdLimit(), SnapBuildClearExportedSnapshot(), and SocketBackend().

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

Definition at line 445 of file xact.c.

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

Referenced by XLogInsertRecord().

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

Definition at line 4782 of file xact.c.

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

Referenced by CleanupSubTransaction(), and CommitSubTransaction().

4783 {
4785 
4786  if (s->state != TRANS_DEFAULT)
4787  elog(WARNING, "PopTransaction while in %s state",
4789 
4790  if (s->parent == NULL)
4791  elog(FATAL, "PopTransaction with no parent");
4792 
4794 
4795  /* Let's just make sure CurTransactionContext is good */
4798 
4799  /* Ditto for ResourceOwner links */
4802 
4803  /* Free the old child structure */
4804  if (s->name)
4805  pfree(s->name);
4806  pfree(s);
4807 }
static TransactionState CurrentTransactionState
Definition: xact.c:232
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:176
ResourceOwner curTransactionOwner
Definition: xact.c:181
void pfree(void *pointer)
Definition: mcxt.c:950
#define FATAL
Definition: elog.h:52
struct TransactionStateData * parent
Definition: xact.c:191
MemoryContext curTransactionContext
Definition: xact.c:180
#define WARNING
Definition: elog.h:40
#define NULL
Definition: c.h:229
static const char * TransStateAsString(TransState state)
Definition: xact.c:5054
#define elog
Definition: elog.h:219
static void PrepareTransaction ( void  )
static

Definition at line 2179 of file xact.c.

References AfterTriggerEndXact(), AfterTriggerFireDeferred(), Assert, AtCommit_Memory(), AtEOXact_Buffers(), AtEOXact_CatCache(), 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, NULL, 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, and XactTopTransactionId.

Referenced by CommitTransactionCommand().

2180 {
2183  GlobalTransaction gxact;
2184  TimestampTz prepared_at;
2185 
2187 
2188  ShowTransactionState("PrepareTransaction");
2189 
2190  /*
2191  * check the current transaction state
2192  */
2193  if (s->state != TRANS_INPROGRESS)
2194  elog(WARNING, "PrepareTransaction while in %s state",
2196  Assert(s->parent == NULL);
2197 
2198  /*
2199  * Do pre-commit processing that involves calling user-defined code, such
2200  * as triggers. Since closing cursors could queue trigger actions,
2201  * triggers could open cursors, etc, we have to keep looping until there's
2202  * nothing left to do.
2203  */
2204  for (;;)
2205  {
2206  /*
2207  * Fire all currently pending deferred triggers.
2208  */
2210 
2211  /*
2212  * Close open portals (converting holdable ones into static portals).
2213  * If there weren't any, we are done ... otherwise loop back to check
2214  * if they queued deferred triggers. Lather, rinse, repeat.
2215  */
2216  if (!PreCommit_Portals(true))
2217  break;
2218  }
2219 
2221 
2222  /*
2223  * The remaining actions cannot call any user-defined code, so it's safe
2224  * to start shutting down within-transaction services. But note that most
2225  * of this stuff could still throw an error, which would switch us into
2226  * the transaction-abort path.
2227  */
2228 
2229  /* Shut down the deferred-trigger manager */
2230  AfterTriggerEndXact(true);
2231 
2232  /*
2233  * Let ON COMMIT management do its thing (must happen after closing
2234  * cursors, to avoid dangling-reference problems)
2235  */
2237 
2238  /* close large objects before lower-level cleanup */
2239  AtEOXact_LargeObject(true);
2240 
2241  /*
2242  * Mark serializable transaction as complete for predicate locking
2243  * purposes. This should be done as late as we can put it and still allow
2244  * errors to be raised for failure patterns found at commit.
2245  */
2247 
2248  /* NOTIFY will be handled below */
2249 
2250  /*
2251  * Don't allow PREPARE TRANSACTION if we've accessed a temporary table in
2252  * this transaction. Having the prepared xact hold locks on another
2253  * backend's temp table seems a bad idea --- for instance it would prevent
2254  * the backend from exiting. There are other problems too, such as how to
2255  * clean up the source backend's local buffers and ON COMMIT state if the
2256  * prepared xact includes a DROP of a temp table.
2257  *
2258  * We must check this after executing any ON COMMIT actions, because they
2259  * might still access a temp relation.
2260  *
2261  * XXX In principle this could be relaxed to allow some useful special
2262  * cases, such as a temp table created and dropped all within the
2263  * transaction. That seems to require much more bookkeeping though.
2264  */
2266  ereport(ERROR,
2267  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2268  errmsg("cannot PREPARE a transaction that has operated on temporary tables")));
2269 
2270  /*
2271  * Likewise, don't allow PREPARE after pg_export_snapshot. This could be
2272  * supported if we added cleanup logic to twophase.c, but for now it
2273  * doesn't seem worth the trouble.
2274  */
2276  ereport(ERROR,
2277  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2278  errmsg("cannot PREPARE a transaction that has exported snapshots")));
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  StartPrepare(gxact);
2319 
2320  AtPrepare_Notify();
2321  AtPrepare_Locks();
2323  AtPrepare_PgStat();
2326 
2327  /*
2328  * Here is where we really truly prepare.
2329  *
2330  * We have to record transaction prepares even if we didn't make any
2331  * updates, because the transaction manager might get confused if we lose
2332  * a global transaction.
2333  */
2334  EndPrepare(gxact);
2335 
2336  /*
2337  * Now we clean up backend-internal state and release internal resources.
2338  */
2339 
2340  /* Reset XactLastRecEnd until the next transaction writes something */
2341  XactLastRecEnd = 0;
2342 
2343  /*
2344  * Let others know about no transaction in progress by me. This has to be
2345  * done *after* the prepared transaction has been marked valid, else
2346  * someone may think it is unlocked and recyclable.
2347  */
2349 
2350  /*
2351  * In normal commit-processing, this is all non-critical post-transaction
2352  * cleanup. When the transaction is prepared, however, it's important
2353  * that the locks and other per-backend resources are transferred to the
2354  * prepared transaction's PGPROC entry. Note that if an error is raised
2355  * here, it's too late to abort the transaction. XXX: This probably should
2356  * be in a critical section, to force a PANIC if any of this fails, but
2357  * that cure could be worse than the disease.
2358  */
2359 
2361 
2364  true, true);
2365 
2366  /* Check we've released all buffer pins */
2367  AtEOXact_Buffers(true);
2368 
2369  /* Clean up the relation cache */
2370  AtEOXact_RelationCache(true);
2371 
2372  /* notify doesn't need a postprepare call */
2373 
2375 
2377 
2378  PostPrepare_smgr();
2379 
2380  PostPrepare_MultiXact(xid);
2381 
2382  PostPrepare_Locks(xid);
2384 
2387  true, true);
2390  true, true);
2391 
2392  /*
2393  * Allow another backend to finish the transaction. After
2394  * PostPrepare_Twophase(), the transaction is completely detached from our
2395  * backend. The rest is just non-critical cleanup of backend-local state.
2396  */
2398 
2399  /* Check we've released all catcache entries */
2400  AtEOXact_CatCache(true);
2401 
2402  /* PREPARE acts the same as COMMIT as far as GUC is concerned */
2403  AtEOXact_GUC(true, 1);
2404  AtEOXact_SPI(true);
2406  AtEOXact_Namespace(true, false);
2407  AtEOXact_SMgr();
2408  AtEOXact_Files();
2410  AtEOXact_HashTables(true);
2411  /* don't call AtEOXact_PgStat here; we fixed pgstat state above */
2412  AtEOXact_Snapshot(true);
2414 
2420 
2421  AtCommit_Memory();
2422 
2425  s->nestingLevel = 0;
2426  s->gucNestLevel = 0;
2427  s->childXids = NULL;
2428  s->nChildXids = 0;
2429  s->maxChildXids = 0;
2430 
2433 
2434  /*
2435  * done with 1st phase commit processing, set current transaction state
2436  * back to default
2437  */
2438  s->state = TRANS_DEFAULT;
2439 
2441 }
TransactionId XactTopTransactionId
Definition: xact.c:107
void PostPrepare_PredicateLocks(TransactionId xid)
Definition: predicate.c:4791
void StartPrepare(GlobalTransaction gxact)
Definition: twophase.c:947
static TransactionState CurrentTransactionState
Definition: xact.c:232
bool XactHasExportedSnapshots(void)
Definition: snapmgr.c:1557
void AtPrepare_MultiXact(void)
Definition: multixact.c:1691
uint32 TransactionId
Definition: c.h:397
static void AtCommit_Memory(void)
Definition: xact.c:1384
Oid GetUserId(void)
Definition: miscinit.c:283