1 /*-------------------------------------------------------------------------
4 * top level transaction system support routines
6 * See src/backend/access/transam/README for more information.
8 * Portions Copyright (c) 1996-2015, PostgreSQL Global Development Group
9 * Portions Copyright (c) 1994, Regents of the University of California
13 * src/backend/access/transam/xact.c
15 *-------------------------------------------------------------------------
23 #include "access/commit_ts.h"
24 #include "access/multixact.h"
25 #include "access/subtrans.h"
26 #include "access/transam.h"
27 #include "access/twophase.h"
28 #include "access/xact.h"
29 #include "access/xlog.h"
30 #include "access/xloginsert.h"
31 #include "access/xlogutils.h"
32 #include "catalog/catalog.h"
33 #include "catalog/namespace.h"
34 #include "catalog/storage.h"
35 #include "commands/async.h"
36 #include "commands/tablecmds.h"
37 #include "commands/trigger.h"
38 #include "executor/spi.h"
39 #include "libpq/be-fsstubs.h"
40 #include "libpq/pqsignal.h"
41 #include "miscadmin.h"
43 #include "replication/walsender.h"
44 #include "replication/syncrep.h"
45 #include "storage/fd.h"
46 #include "storage/lmgr.h"
47 #include "storage/predicate.h"
48 #include "storage/proc.h"
49 #include "storage/procarray.h"
50 #include "storage/sinvaladt.h"
51 #include "storage/smgr.h"
52 #include "utils/catcache.h"
53 #include "utils/combocid.h"
54 #include "utils/guc.h"
55 #include "utils/inval.h"
56 #include "utils/memutils.h"
57 #include "utils/relmapper.h"
58 #include "utils/snapmgr.h"
59 #include "utils/timeout.h"
60 #include "utils/timestamp.h"
65 * User-tweakable parameters
67 int DefaultXactIsoLevel = XACT_READ_COMMITTED;
70 bool DefaultXactReadOnly = false;
73 bool DefaultXactDeferrable = false;
76 int synchronous_commit = SYNCHRONOUS_COMMIT_ON;
79 * MyXactAccessedTempRel is set when a temporary relation is accessed.
80 * We don't allow PREPARE TRANSACTION in that case. (This is global
81 * so that it can be set from heapam.c.)
83 bool MyXactAccessedTempRel = false;
87 * transaction states - transaction state from server perspective
89 typedef enum TransState
91 TRANS_DEFAULT, /* idle */
92 TRANS_START, /* transaction starting */
93 TRANS_INPROGRESS, /* inside a valid transaction */
94 TRANS_COMMIT, /* commit in progress */
95 TRANS_ABORT, /* abort in progress */
96 TRANS_PREPARE /* prepare in progress */
100 * transaction block states - transaction state of client queries
102 * Note: the subtransaction states are used only for non-topmost
103 * transactions; the others appear only in the topmost transaction.
105 typedef enum TBlockState
107 /* not-in-transaction-block states */
108 TBLOCK_DEFAULT, /* idle */
109 TBLOCK_STARTED, /* running single-query transaction */
111 /* transaction block states */
112 TBLOCK_BEGIN, /* starting transaction block */
113 TBLOCK_INPROGRESS, /* live transaction */
114 TBLOCK_END, /* COMMIT received */
115 TBLOCK_ABORT, /* failed xact, awaiting ROLLBACK */
116 TBLOCK_ABORT_END, /* failed xact, ROLLBACK received */
117 TBLOCK_ABORT_PENDING, /* live xact, ROLLBACK received */
118 TBLOCK_PREPARE, /* live xact, PREPARE received */
120 /* subtransaction states */
121 TBLOCK_SUBBEGIN, /* starting a subtransaction */
122 TBLOCK_SUBINPROGRESS, /* live subtransaction */
123 TBLOCK_SUBRELEASE, /* RELEASE received */
124 TBLOCK_SUBCOMMIT, /* COMMIT received while TBLOCK_SUBINPROGRESS */
125 TBLOCK_SUBABORT, /* failed subxact, awaiting ROLLBACK */
126 TBLOCK_SUBABORT_END, /* failed subxact, ROLLBACK received */
127 TBLOCK_SUBABORT_PENDING, /* live subxact, ROLLBACK received */
128 TBLOCK_SUBRESTART, /* live subxact, ROLLBACK TO received */
129 TBLOCK_SUBABORT_RESTART /* failed subxact, ROLLBACK TO received */
133 * transaction state structure
135 typedef struct TransactionStateData
137 TransactionId transactionId; /* my XID, or Invalid if none */
138 SubTransactionId subTransactionId; /* my subxact ID */
139 char *name; /* savepoint name, if any */
140 int savepointLevel; /* savepoint level */
141 TransState state; /* low-level state */
142 TBlockState blockState; /* high-level state */
143 int nestingLevel; /* transaction nesting depth */
144 int gucNestLevel; /* GUC context nesting depth */
145 MemoryContext curTransactionContext; /* my xact-lifetime context */
146 ResourceOwner curTransactionOwner; /* my query resources */
147 TransactionId *childXids; /* subcommitted child XIDs, in XID order */
148 int nChildXids; /* # of subcommitted child XIDs */
149 int maxChildXids; /* allocated size of childXids[] */
150 Oid prevUser; /* previous CurrentUserId setting */
151 int prevSecContext; /* previous SecurityRestrictionContext */
152 bool prevXactReadOnly; /* entry-time xact r/o state */
153 bool startedInRecovery; /* did we start in recovery? */
154 bool didLogXid; /* has xid been included in WAL record? */
155 struct TransactionStateData *parent; /* back link to parent */
156 } TransactionStateData;
158 typedef TransactionStateData *TransactionState;
161 * CurrentTransactionState always points to the current transaction state
162 * block. It will point to TopTransactionStateData when not in a
163 * transaction at all, or when in a top-level transaction.
165 static TransactionStateData TopTransactionStateData = {
166 0, /* transaction id */
167 0, /* subtransaction id */
168 NULL, /* savepoint name */
169 0, /* savepoint level */
170 TRANS_DEFAULT, /* transaction state */
171 TBLOCK_DEFAULT, /* transaction block state from the client
173 0, /* transaction nesting depth */
174 0, /* GUC context nesting depth */
175 NULL, /* cur transaction context */
176 NULL, /* cur transaction resource owner */
177 NULL, /* subcommitted child Xids */
178 0, /* # of subcommitted child Xids */
179 0, /* allocated size of childXids[] */
180 InvalidOid, /* previous CurrentUserId setting */
181 0, /* previous SecurityRestrictionContext */
182 false, /* entry-time xact r/o state */
183 false, /* startedInRecovery */
184 false, /* didLogXid */
185 NULL /* link to parent state block */
189 * unreportedXids holds XIDs of all subtransactions that have not yet been
190 * reported in a XLOG_XACT_ASSIGNMENT record.
192 static int nUnreportedXids;
193 static TransactionId unreportedXids[PGPROC_MAX_CACHED_SUBXIDS];
195 static TransactionState CurrentTransactionState = &TopTransactionStateData;
198 * The subtransaction ID and command ID assignment counters are global
199 * to a whole transaction, so we do not keep them in the state stack.
201 static SubTransactionId currentSubTransactionId;
202 static CommandId currentCommandId;
203 static bool currentCommandIdUsed;
206 * xactStartTimestamp is the value of transaction_timestamp().
207 * stmtStartTimestamp is the value of statement_timestamp().
208 * xactStopTimestamp is the time at which we log a commit or abort WAL record.
209 * These do not change as we enter and exit subtransactions, so we don't
210 * keep them inside the TransactionState stack.
212 static TimestampTz xactStartTimestamp;
213 static TimestampTz stmtStartTimestamp;
214 static TimestampTz xactStopTimestamp;
217 * GID to be used for preparing the current transaction. This is also
218 * global to a whole transaction, so we don't keep it in the state stack.
220 static char *prepareGID;
223 * Some commands want to force synchronous commit.
225 static bool forceSyncCommit = false;
228 * Private context for transaction-abort work --- we reserve space for this
229 * at startup to ensure that AbortTransaction and AbortSubTransaction can work
230 * when we've run out of memory.
232 static MemoryContext TransactionAbortContext = NULL;
235 * List of add-on start- and end-of-xact callbacks
237 typedef struct XactCallbackItem
239 struct XactCallbackItem *next;
240 XactCallback callback;
244 static XactCallbackItem *Xact_callbacks = NULL;
247 * List of add-on start- and end-of-subxact callbacks
249 typedef struct SubXactCallbackItem
251 struct SubXactCallbackItem *next;
252 SubXactCallback callback;
254 } SubXactCallbackItem;
256 static SubXactCallbackItem *SubXact_callbacks = NULL;
259 /* local function prototypes */
260 static void AssignTransactionId(TransactionState s);
261 static void AbortTransaction(void);
262 static void AtAbort_Memory(void);
263 static void AtCleanup_Memory(void);
264 static void AtAbort_ResourceOwner(void);
265 static void AtCCI_LocalCache(void);
266 static void AtCommit_Memory(void);
267 static void AtStart_Cache(void);
268 static void AtStart_Memory(void);
269 static void AtStart_ResourceOwner(void);
270 static void CallXactCallbacks(XactEvent event);
271 static void CallSubXactCallbacks(SubXactEvent event,
272 SubTransactionId mySubid,
273 SubTransactionId parentSubid);
274 static void CleanupTransaction(void);
275 static void CheckTransactionChain(bool isTopLevel, bool throwError,
276 const char *stmtType);
277 static void CommitTransaction(void);
278 static TransactionId RecordTransactionAbort(bool isSubXact);
279 static void StartTransaction(void);
281 static void StartSubTransaction(void);
282 static void CommitSubTransaction(void);
283 static void AbortSubTransaction(void);
284 static void CleanupSubTransaction(void);
285 static void PushTransaction(void);
286 static void PopTransaction(void);
288 static void AtSubAbort_Memory(void);
289 static void AtSubCleanup_Memory(void);
290 static void AtSubAbort_ResourceOwner(void);
291 static void AtSubCommit_Memory(void);
292 static void AtSubStart_Memory(void);
293 static void AtSubStart_ResourceOwner(void);
295 static void ShowTransactionState(const char *str);
296 static void ShowTransactionStateRec(TransactionState state);
297 static const char *BlockStateAsString(TBlockState blockState);
298 static const char *TransStateAsString(TransState state);
301 /* ----------------------------------------------------------------
302 * transaction state accessors
303 * ----------------------------------------------------------------
309 * This returns true if we are inside a valid transaction; that is,
310 * it is safe to initiate database access, take heavyweight locks, etc.
313 IsTransactionState(void)
315 TransactionState s = CurrentTransactionState;
318 * TRANS_DEFAULT and TRANS_ABORT are obviously unsafe states. However, we
319 * also reject the startup/shutdown states TRANS_START, TRANS_COMMIT,
320 * TRANS_PREPARE since it might be too soon or too late within those
321 * transition states to do anything interesting. Hence, the only "valid"
322 * state is TRANS_INPROGRESS.
324 return (s->state == TRANS_INPROGRESS);
328 * IsAbortedTransactionBlockState
330 * This returns true if we are within an aborted transaction block.
333 IsAbortedTransactionBlockState(void)
335 TransactionState s = CurrentTransactionState;
337 if (s->blockState == TBLOCK_ABORT ||
338 s->blockState == TBLOCK_SUBABORT)
346 * GetTopTransactionId
348 * This will return the XID of the main transaction, assigning one if
349 * it's not yet set. Be careful to call this only inside a valid xact.
352 GetTopTransactionId(void)
354 if (!TransactionIdIsValid(TopTransactionStateData.transactionId))
355 AssignTransactionId(&TopTransactionStateData);
356 return TopTransactionStateData.transactionId;
360 * GetTopTransactionIdIfAny
362 * This will return the XID of the main transaction, if one is assigned.
363 * It will return InvalidTransactionId if we are not currently inside a
364 * transaction, or inside a transaction that hasn't yet been assigned an XID.
367 GetTopTransactionIdIfAny(void)
369 return TopTransactionStateData.transactionId;
373 * GetCurrentTransactionId
375 * This will return the XID of the current transaction (main or sub
376 * transaction), assigning one if it's not yet set. Be careful to call this
377 * only inside a valid xact.
380 GetCurrentTransactionId(void)
382 TransactionState s = CurrentTransactionState;
384 if (!TransactionIdIsValid(s->transactionId))
385 AssignTransactionId(s);
386 return s->transactionId;
390 * GetCurrentTransactionIdIfAny
392 * This will return the XID of the current sub xact, if one is assigned.
393 * It will return InvalidTransactionId if we are not currently inside a
394 * transaction, or inside a transaction that hasn't been assigned an XID yet.
397 GetCurrentTransactionIdIfAny(void)
399 return CurrentTransactionState->transactionId;
403 * MarkCurrentTransactionIdLoggedIfAny
405 * Remember that the current xid - if it is assigned - now has been wal logged.
408 MarkCurrentTransactionIdLoggedIfAny(void)
410 if (TransactionIdIsValid(CurrentTransactionState->transactionId))
411 CurrentTransactionState->didLogXid = true;
416 * GetStableLatestTransactionId
418 * Get the transaction's XID if it has one, else read the next-to-be-assigned
419 * XID. Once we have a value, return that same value for the remainder of the
420 * current transaction. This is meant to provide the reference point for the
421 * age(xid) function, but might be useful for other maintenance tasks as well.
424 GetStableLatestTransactionId(void)
426 static LocalTransactionId lxid = InvalidLocalTransactionId;
427 static TransactionId stablexid = InvalidTransactionId;
429 if (lxid != MyProc->lxid)
432 stablexid = GetTopTransactionIdIfAny();
433 if (!TransactionIdIsValid(stablexid))
434 stablexid = ReadNewTransactionId();
437 Assert(TransactionIdIsValid(stablexid));
443 * AssignTransactionId
445 * Assigns a new permanent XID to the given TransactionState.
446 * We do not assign XIDs to transactions until/unless this is called.
447 * Also, any parent TransactionStates that don't yet have XIDs are assigned
448 * one; this maintains the invariant that a child transaction has an XID
449 * following its parent's.
452 AssignTransactionId(TransactionState s)
454 bool isSubXact = (s->parent != NULL);
455 ResourceOwner currentOwner;
456 bool log_unknown_top = false;
458 /* Assert that caller didn't screw up */
459 Assert(!TransactionIdIsValid(s->transactionId));
460 Assert(s->state == TRANS_INPROGRESS);
463 * Ensure parent(s) have XIDs, so that a child always has an XID later
464 * than its parent. Musn't recurse here, or we might get a stack overflow
465 * if we're at the bottom of a huge stack of subtransactions none of which
468 if (isSubXact && !TransactionIdIsValid(s->parent->transactionId))
470 TransactionState p = s->parent;
471 TransactionState *parents;
472 size_t parentOffset = 0;
474 parents = palloc(sizeof(TransactionState) * s->nestingLevel);
475 while (p != NULL && !TransactionIdIsValid(p->transactionId))
477 parents[parentOffset++] = p;
482 * This is technically a recursive call, but the recursion will never
483 * be more than one layer deep.
485 while (parentOffset != 0)
486 AssignTransactionId(parents[--parentOffset]);
492 * When wal_level=logical, guarantee that a subtransaction's xid can only
493 * be seen in the WAL stream if its toplevel xid has been logged before.
494 * If necessary we log a xact_assignment record with fewer than
495 * PGPROC_MAX_CACHED_SUBXIDS. Note that it is fine if didLogXid isn't set
496 * for a transaction even though it appears in a WAL record, we just might
497 * superfluously log something. That can happen when an xid is included
498 * somewhere inside a wal record, but not in XLogRecord->xl_xid, like in
501 if (isSubXact && XLogLogicalInfoActive() &&
502 !TopTransactionStateData.didLogXid)
503 log_unknown_top = true;
506 * Generate a new Xid and record it in PG_PROC and pg_subtrans.
508 * NB: we must make the subtrans entry BEFORE the Xid appears anywhere in
509 * shared storage other than PG_PROC; because if there's no room for it in
510 * PG_PROC, the subtrans entry is needed to ensure that other backends see
511 * the Xid as "running". See GetNewTransactionId.
513 s->transactionId = GetNewTransactionId(isSubXact);
516 SubTransSetParent(s->transactionId, s->parent->transactionId, false);
519 * If it's a top-level transaction, the predicate locking system needs to
520 * be told about it too.
523 RegisterPredicateLockingXid(s->transactionId);
526 * Acquire lock on the transaction XID. (We assume this cannot block.) We
527 * have to ensure that the lock is assigned to the transaction's own
530 currentOwner = CurrentResourceOwner;
533 CurrentResourceOwner = s->curTransactionOwner;
534 XactLockTableInsert(s->transactionId);
538 /* Ensure CurrentResourceOwner is restored on error */
539 CurrentResourceOwner = currentOwner;
543 CurrentResourceOwner = currentOwner;
546 * Every PGPROC_MAX_CACHED_SUBXIDS assigned transaction ids within each
547 * top-level transaction we issue a WAL record for the assignment. We
548 * include the top-level xid and all the subxids that have not yet been
549 * reported using XLOG_XACT_ASSIGNMENT records.
551 * This is required to limit the amount of shared memory required in a hot
552 * standby server to keep track of in-progress XIDs. See notes for
553 * RecordKnownAssignedTransactionIds().
555 * We don't keep track of the immediate parent of each subxid, only the
556 * top-level transaction that each subxact belongs to. This is correct in
557 * recovery only because aborted subtransactions are separately WAL
560 * This is correct even for the case where several levels above us didn't
561 * have an xid assigned as we recursed up to them beforehand.
563 if (isSubXact && XLogStandbyInfoActive())
565 unreportedXids[nUnreportedXids] = s->transactionId;
569 * ensure this test matches similar one in
570 * RecoverPreparedTransactions()
572 if (nUnreportedXids >= PGPROC_MAX_CACHED_SUBXIDS ||
575 xl_xact_assignment xlrec;
578 * xtop is always set by now because we recurse up transaction
579 * stack to the highest unassigned xid and then come back down
581 xlrec.xtop = GetTopTransactionId();
582 Assert(TransactionIdIsValid(xlrec.xtop));
583 xlrec.nsubxacts = nUnreportedXids;
586 XLogRegisterData((char *) &xlrec, MinSizeOfXactAssignment);
587 XLogRegisterData((char *) unreportedXids,
588 nUnreportedXids * sizeof(TransactionId));
590 (void) XLogInsert(RM_XACT_ID, XLOG_XACT_ASSIGNMENT);
593 /* mark top, not current xact as having been logged */
594 TopTransactionStateData.didLogXid = true;
600 * GetCurrentSubTransactionId
603 GetCurrentSubTransactionId(void)
605 TransactionState s = CurrentTransactionState;
607 return s->subTransactionId;
611 * SubTransactionIsActive
613 * Test if the specified subxact ID is still active. Note caller is
614 * responsible for checking whether this ID is relevant to the current xact.
617 SubTransactionIsActive(SubTransactionId subxid)
621 for (s = CurrentTransactionState; s != NULL; s = s->parent)
623 if (s->state == TRANS_ABORT)
625 if (s->subTransactionId == subxid)
633 * GetCurrentCommandId
635 * "used" must be TRUE if the caller intends to use the command ID to mark
636 * inserted/updated/deleted tuples. FALSE means the ID is being fetched
637 * for read-only purposes (ie, as a snapshot validity cutoff). See
638 * CommandCounterIncrement() for discussion.
641 GetCurrentCommandId(bool used)
643 /* this is global to a transaction, not subtransaction-local */
645 currentCommandIdUsed = true;
646 return currentCommandId;
650 * GetCurrentTransactionStartTimestamp
653 GetCurrentTransactionStartTimestamp(void)
655 return xactStartTimestamp;
659 * GetCurrentStatementStartTimestamp
662 GetCurrentStatementStartTimestamp(void)
664 return stmtStartTimestamp;
668 * GetCurrentTransactionStopTimestamp
670 * We return current time if the transaction stop time hasn't been set
671 * (which can happen if we decide we don't need to log an XLOG record).
674 GetCurrentTransactionStopTimestamp(void)
676 if (xactStopTimestamp != 0)
677 return xactStopTimestamp;
678 return GetCurrentTimestamp();
682 * SetCurrentStatementStartTimestamp
685 SetCurrentStatementStartTimestamp(void)
687 stmtStartTimestamp = GetCurrentTimestamp();
691 * SetCurrentTransactionStopTimestamp
694 SetCurrentTransactionStopTimestamp(void)
696 xactStopTimestamp = GetCurrentTimestamp();
700 * GetCurrentTransactionNestLevel
702 * Note: this will return zero when not inside any transaction, one when
703 * inside a top-level transaction, etc.
706 GetCurrentTransactionNestLevel(void)
708 TransactionState s = CurrentTransactionState;
710 return s->nestingLevel;
715 * TransactionIdIsCurrentTransactionId
718 TransactionIdIsCurrentTransactionId(TransactionId xid)
723 * We always say that BootstrapTransactionId is "not my transaction ID"
724 * even when it is (ie, during bootstrap). Along with the fact that
725 * transam.c always treats BootstrapTransactionId as already committed,
726 * this causes the tqual.c routines to see all tuples as committed, which
727 * is what we need during bootstrap. (Bootstrap mode only inserts tuples,
728 * it never updates or deletes them, so all tuples can be presumed good
731 * Likewise, InvalidTransactionId and FrozenTransactionId are certainly
732 * not my transaction ID, so we can just return "false" immediately for
733 * any non-normal XID.
735 if (!TransactionIdIsNormal(xid))
739 * We will return true for the Xid of the current subtransaction, any of
740 * its subcommitted children, any of its parents, or any of their
741 * previously subcommitted children. However, a transaction being aborted
742 * is no longer "current", even though it may still have an entry on the
745 for (s = CurrentTransactionState; s != NULL; s = s->parent)
750 if (s->state == TRANS_ABORT)
752 if (!TransactionIdIsValid(s->transactionId))
753 continue; /* it can't have any child XIDs either */
754 if (TransactionIdEquals(xid, s->transactionId))
756 /* As the childXids array is ordered, we can use binary search */
758 high = s->nChildXids - 1;
764 middle = low + (high - low) / 2;
765 probe = s->childXids[middle];
766 if (TransactionIdEquals(probe, xid))
768 else if (TransactionIdPrecedes(probe, xid))
779 * TransactionStartedDuringRecovery
781 * Returns true if the current transaction started while recovery was still
782 * in progress. Recovery might have ended since so RecoveryInProgress() might
783 * return false already.
786 TransactionStartedDuringRecovery(void)
788 return CurrentTransactionState->startedInRecovery;
792 * CommandCounterIncrement
795 CommandCounterIncrement(void)
798 * If the current value of the command counter hasn't been "used" to mark
799 * tuples, we need not increment it, since there's no need to distinguish
800 * a read-only command from others. This helps postpone command counter
801 * overflow, and keeps no-op CommandCounterIncrement operations cheap.
803 if (currentCommandIdUsed)
805 currentCommandId += 1;
806 if (currentCommandId == InvalidCommandId)
808 currentCommandId -= 1;
810 (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
811 errmsg("cannot have more than 2^32-2 commands in a transaction")));
813 currentCommandIdUsed = false;
815 /* Propagate new command ID into static snapshots */
816 SnapshotSetCommandId(currentCommandId);
819 * Make any catalog changes done by the just-completed command visible
820 * in the local syscache. We obviously don't need to do this after a
821 * read-only command. (But see hacks in inval.c to make real sure we
822 * don't think a command that queued inval messages was read-only.)
831 * Interface routine to allow commands to force a synchronous commit of the
832 * current top-level transaction
835 ForceSyncCommit(void)
837 forceSyncCommit = true;
841 /* ----------------------------------------------------------------
842 * StartTransaction stuff
843 * ----------------------------------------------------------------
852 AcceptInvalidationMessages();
861 TransactionState s = CurrentTransactionState;
864 * If this is the first time through, create a private context for
865 * AbortTransaction to work in. By reserving some space now, we can
866 * insulate AbortTransaction from out-of-memory scenarios. Like
867 * ErrorContext, we set it up with slow growth rate and a nonzero minimum
868 * size, so that space will be reserved immediately.
870 if (TransactionAbortContext == NULL)
871 TransactionAbortContext =
872 AllocSetContextCreate(TopMemoryContext,
873 "TransactionAbortContext",
879 * We shouldn't have a transaction context already.
881 Assert(TopTransactionContext == NULL);
884 * Create a toplevel context for the transaction.
886 TopTransactionContext =
887 AllocSetContextCreate(TopMemoryContext,
888 "TopTransactionContext",
889 ALLOCSET_DEFAULT_MINSIZE,
890 ALLOCSET_DEFAULT_INITSIZE,
891 ALLOCSET_DEFAULT_MAXSIZE);
894 * In a top-level transaction, CurTransactionContext is the same as
895 * TopTransactionContext.
897 CurTransactionContext = TopTransactionContext;
898 s->curTransactionContext = CurTransactionContext;
900 /* Make the CurTransactionContext active. */
901 MemoryContextSwitchTo(CurTransactionContext);
905 * AtStart_ResourceOwner
908 AtStart_ResourceOwner(void)
910 TransactionState s = CurrentTransactionState;
913 * We shouldn't have a transaction resource owner already.
915 Assert(TopTransactionResourceOwner == NULL);
918 * Create a toplevel resource owner for the transaction.
920 s->curTransactionOwner = ResourceOwnerCreate(NULL, "TopTransaction");
922 TopTransactionResourceOwner = s->curTransactionOwner;
923 CurTransactionResourceOwner = s->curTransactionOwner;
924 CurrentResourceOwner = s->curTransactionOwner;
927 /* ----------------------------------------------------------------
928 * StartSubTransaction stuff
929 * ----------------------------------------------------------------
936 AtSubStart_Memory(void)
938 TransactionState s = CurrentTransactionState;
940 Assert(CurTransactionContext != NULL);
943 * Create a CurTransactionContext, which will be used to hold data that
944 * survives subtransaction commit but disappears on subtransaction abort.
945 * We make it a child of the immediate parent's CurTransactionContext.
947 CurTransactionContext = AllocSetContextCreate(CurTransactionContext,
948 "CurTransactionContext",
949 ALLOCSET_DEFAULT_MINSIZE,
950 ALLOCSET_DEFAULT_INITSIZE,
951 ALLOCSET_DEFAULT_MAXSIZE);
952 s->curTransactionContext = CurTransactionContext;
954 /* Make the CurTransactionContext active. */
955 MemoryContextSwitchTo(CurTransactionContext);
959 * AtSubStart_ResourceOwner
962 AtSubStart_ResourceOwner(void)
964 TransactionState s = CurrentTransactionState;
966 Assert(s->parent != NULL);
969 * Create a resource owner for the subtransaction. We make it a child of
970 * the immediate parent's resource owner.
972 s->curTransactionOwner =
973 ResourceOwnerCreate(s->parent->curTransactionOwner,
976 CurTransactionResourceOwner = s->curTransactionOwner;
977 CurrentResourceOwner = s->curTransactionOwner;
980 /* ----------------------------------------------------------------
981 * CommitTransaction stuff
982 * ----------------------------------------------------------------
986 * RecordTransactionCommit
988 * Returns latest XID among xact and its children, or InvalidTransactionId
989 * if the xact has no XID. (We compute that here just because it's easier.)
992 RecordTransactionCommit(void)
994 TransactionId xid = GetTopTransactionIdIfAny();
995 bool markXidCommitted = TransactionIdIsValid(xid);
996 TransactionId latestXid = InvalidTransactionId;
1000 TransactionId *children;
1002 SharedInvalidationMessage *invalMessages = NULL;
1003 bool RelcacheInitFileInval = false;
1006 /* Get data needed for commit record */
1007 nrels = smgrGetPendingDeletes(true, &rels);
1008 nchildren = xactGetCommittedChildren(&children);
1009 if (XLogStandbyInfoActive())
1010 nmsgs = xactGetCommittedInvalidationMessages(&invalMessages,
1011 &RelcacheInitFileInval);
1012 wrote_xlog = (XactLastRecEnd != 0);
1015 * If we haven't been assigned an XID yet, we neither can, nor do we want
1016 * to write a COMMIT record.
1018 if (!markXidCommitted)
1021 * We expect that every smgrscheduleunlink is followed by a catalog
1022 * update, and hence XID assignment, so we shouldn't get here with any
1023 * pending deletes. Use a real test not just an Assert to check this,
1024 * since it's a bit fragile.
1027 elog(ERROR, "cannot commit a transaction that deleted files but has no xid");
1029 /* Can't have child XIDs either; AssignTransactionId enforces this */
1030 Assert(nchildren == 0);
1033 * If we didn't create XLOG entries, we're done here; otherwise we
1034 * should trigger flushing those entries the same as a commit record
1035 * would. This will primarily happen for HOT pruning and the like; we
1036 * want these to be flushed to disk in due time.
1044 * Begin commit critical section and insert the commit XLOG record.
1046 /* Tell bufmgr and smgr to prepare for commit */
1050 * Mark ourselves as within our "commit critical section". This
1051 * forces any concurrent checkpoint to wait until we've updated
1052 * pg_clog. Without this, it is possible for the checkpoint to set
1053 * REDO after the XLOG record but fail to flush the pg_clog update to
1054 * disk, leading to loss of the transaction commit if the system
1055 * crashes a little later.
1057 * Note: we could, but don't bother to, set this flag in
1058 * RecordTransactionAbort. That's because loss of a transaction abort
1059 * is noncritical; the presumption would be that it aborted, anyway.
1061 * It's safe to change the delayChkpt flag of our own backend without
1062 * holding the ProcArrayLock, since we're the only one modifying it.
1063 * This makes checkpoint's determination of which xacts are delayChkpt
1064 * a bit fuzzy, but it doesn't matter.
1066 START_CRIT_SECTION();
1067 MyPgXact->delayChkpt = true;
1069 SetCurrentTransactionStopTimestamp();
1071 XactLogCommitRecord(xactStopTimestamp,
1072 nchildren, children, nrels, rels,
1073 nmsgs, invalMessages,
1074 RelcacheInitFileInval, forceSyncCommit,
1075 InvalidTransactionId /* plain commit */);
1079 * We only need to log the commit timestamp separately if the node
1080 * identifier is a valid value; the commit record above already contains
1081 * the timestamp info otherwise, and will be used to load it.
1083 if (markXidCommitted)
1085 CommitTsNodeId node_id;
1087 node_id = CommitTsGetDefaultNodeId();
1088 TransactionTreeSetCommitTsData(xid, nchildren, children,
1090 node_id, node_id != InvalidCommitTsNodeId);
1094 * Check if we want to commit asynchronously. We can allow the XLOG flush
1095 * to happen asynchronously if synchronous_commit=off, or if the current
1096 * transaction has not performed any WAL-logged operation or didn't assign
1097 * a xid. The transaction can end up not writing any WAL, even if it has
1098 * a xid, if it only wrote to temporary and/or unlogged tables. It can
1099 * end up having written WAL without an xid if it did HOT pruning. In
1100 * case of a crash, the loss of such a transaction will be irrelevant;
1101 * temp tables will be lost anyway, unlogged tables will be truncated and
1102 * HOT pruning will be done again later. (Given the foregoing, you might
1103 * think that it would be unnecessary to emit the XLOG record at all in
1104 * this case, but we don't currently try to do that. It would certainly
1105 * cause problems at least in Hot Standby mode, where the
1106 * KnownAssignedXids machinery requires tracking every XID assignment. It
1107 * might be OK to skip it only when wal_level < hot_standby, but for now
1110 * However, if we're doing cleanup of any non-temp rels or committing any
1111 * command that wanted to force sync commit, then we must flush XLOG
1112 * immediately. (We must not allow asynchronous commit if there are any
1113 * non-temp tables to be deleted, because we might delete the files before
1114 * the COMMIT record is flushed to disk. We do allow asynchronous commit
1115 * if all to-be-deleted tables are temporary though, since they are lost
1116 * anyway if we crash.)
1118 if ((wrote_xlog && markXidCommitted &&
1119 synchronous_commit > SYNCHRONOUS_COMMIT_OFF) ||
1120 forceSyncCommit || nrels > 0)
1122 XLogFlush(XactLastRecEnd);
1125 * Now we may update the CLOG, if we wrote a COMMIT record above
1127 if (markXidCommitted)
1128 TransactionIdCommitTree(xid, nchildren, children);
1133 * Asynchronous commit case:
1135 * This enables possible committed transaction loss in the case of a
1136 * postmaster crash because WAL buffers are left unwritten. Ideally we
1137 * could issue the WAL write without the fsync, but some
1138 * wal_sync_methods do not allow separate write/fsync.
1140 * Report the latest async commit LSN, so that the WAL writer knows to
1141 * flush this commit.
1143 XLogSetAsyncXactLSN(XactLastRecEnd);
1146 * We must not immediately update the CLOG, since we didn't flush the
1147 * XLOG. Instead, we store the LSN up to which the XLOG must be
1148 * flushed before the CLOG may be updated.
1150 if (markXidCommitted)
1151 TransactionIdAsyncCommitTree(xid, nchildren, children, XactLastRecEnd);
1155 * If we entered a commit critical section, leave it now, and let
1156 * checkpoints proceed.
1158 if (markXidCommitted)
1160 MyPgXact->delayChkpt = false;
1164 /* Compute latestXid while we have the child XIDs handy */
1165 latestXid = TransactionIdLatest(xid, nchildren, children);
1168 * Wait for synchronous replication, if required. Similar to the decision
1169 * above about using committing asynchronously we only want to wait if
1170 * this backend assigned a xid and wrote WAL. No need to wait if a xid
1171 * was assigned due to temporary/unlogged tables or due to HOT pruning.
1173 * Note that at this stage we have marked clog, but still show as running
1174 * in the procarray and continue to hold locks.
1176 if (wrote_xlog && markXidCommitted)
1177 SyncRepWaitForLSN(XactLastRecEnd);
1179 /* Reset XactLastRecEnd until the next transaction writes something */
1183 /* Clean up local data */
1195 AtCCI_LocalCache(void)
1198 * Make any pending relation map changes visible. We must do this before
1199 * processing local sinval messages, so that the map changes will get
1200 * reflected into the relcache when relcache invals are processed.
1202 AtCCI_RelationMap();
1205 * Make catalog changes visible to me for the next command.
1207 CommandEndInvalidationMessages();
1214 AtCommit_Memory(void)
1217 * Now that we're "out" of a transaction, have the system allocate things
1218 * in the top memory context instead of per-transaction contexts.
1220 MemoryContextSwitchTo(TopMemoryContext);
1223 * Release all transaction-local memory.
1225 Assert(TopTransactionContext != NULL);
1226 MemoryContextDelete(TopTransactionContext);
1227 TopTransactionContext = NULL;
1228 CurTransactionContext = NULL;
1229 CurrentTransactionState->curTransactionContext = NULL;
1232 /* ----------------------------------------------------------------
1233 * CommitSubTransaction stuff
1234 * ----------------------------------------------------------------
1238 * AtSubCommit_Memory
1241 AtSubCommit_Memory(void)
1243 TransactionState s = CurrentTransactionState;
1245 Assert(s->parent != NULL);
1247 /* Return to parent transaction level's memory context. */
1248 CurTransactionContext = s->parent->curTransactionContext;
1249 MemoryContextSwitchTo(CurTransactionContext);
1252 * Ordinarily we cannot throw away the child's CurTransactionContext,
1253 * since the data it contains will be needed at upper commit. However, if
1254 * there isn't actually anything in it, we can throw it away. This avoids
1255 * a small memory leak in the common case of "trivial" subxacts.
1257 if (MemoryContextIsEmpty(s->curTransactionContext))
1259 MemoryContextDelete(s->curTransactionContext);
1260 s->curTransactionContext = NULL;
1265 * AtSubCommit_childXids
1267 * Pass my own XID and my child XIDs up to my parent as committed children.
1270 AtSubCommit_childXids(void)
1272 TransactionState s = CurrentTransactionState;
1275 Assert(s->parent != NULL);
1278 * The parent childXids array will need to hold my XID and all my
1279 * childXids, in addition to the XIDs already there.
1281 new_nChildXids = s->parent->nChildXids + s->nChildXids + 1;
1283 /* Allocate or enlarge the parent array if necessary */
1284 if (s->parent->maxChildXids < new_nChildXids)
1286 int new_maxChildXids;
1287 TransactionId *new_childXids;
1290 * Make it 2x what's needed right now, to avoid having to enlarge it
1291 * repeatedly. But we can't go above MaxAllocSize. (The latter limit
1292 * is what ensures that we don't need to worry about integer overflow
1293 * here or in the calculation of new_nChildXids.)
1295 new_maxChildXids = Min(new_nChildXids * 2,
1296 (int) (MaxAllocSize / sizeof(TransactionId)));
1298 if (new_maxChildXids < new_nChildXids)
1300 (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
1301 errmsg("maximum number of committed subtransactions (%d) exceeded",
1302 (int) (MaxAllocSize / sizeof(TransactionId)))));
1305 * We keep the child-XID arrays in TopTransactionContext; this avoids
1306 * setting up child-transaction contexts for what might be just a few
1307 * bytes of grandchild XIDs.
1309 if (s->parent->childXids == NULL)
1311 MemoryContextAlloc(TopTransactionContext,
1312 new_maxChildXids * sizeof(TransactionId));
1314 new_childXids = repalloc(s->parent->childXids,
1315 new_maxChildXids * sizeof(TransactionId));
1317 s->parent->childXids = new_childXids;
1318 s->parent->maxChildXids = new_maxChildXids;
1322 * Copy all my XIDs to parent's array.
1324 * Note: We rely on the fact that the XID of a child always follows that
1325 * of its parent. By copying the XID of this subtransaction before the
1326 * XIDs of its children, we ensure that the array stays ordered. Likewise,
1327 * all XIDs already in the array belong to subtransactions started and
1328 * subcommitted before us, so their XIDs must precede ours.
1330 s->parent->childXids[s->parent->nChildXids] = s->transactionId;
1332 if (s->nChildXids > 0)
1333 memcpy(&s->parent->childXids[s->parent->nChildXids + 1],
1335 s->nChildXids * sizeof(TransactionId));
1337 s->parent->nChildXids = new_nChildXids;
1339 /* Release child's array to avoid leakage */
1340 if (s->childXids != NULL)
1341 pfree(s->childXids);
1342 /* We must reset these to avoid double-free if fail later in commit */
1343 s->childXids = NULL;
1345 s->maxChildXids = 0;
1348 /* ----------------------------------------------------------------
1349 * AbortTransaction stuff
1350 * ----------------------------------------------------------------
1354 * RecordTransactionAbort
1356 * Returns latest XID among xact and its children, or InvalidTransactionId
1357 * if the xact has no XID. (We compute that here just because it's easier.)
1359 static TransactionId
1360 RecordTransactionAbort(bool isSubXact)
1362 TransactionId xid = GetCurrentTransactionIdIfAny();
1363 TransactionId latestXid;
1367 TransactionId *children;
1368 TimestampTz xact_time;
1371 * If we haven't been assigned an XID, nobody will care whether we aborted
1372 * or not. Hence, we're done in that case. It does not matter if we have
1373 * rels to delete (note that this routine is not responsible for actually
1374 * deleting 'em). We cannot have any child XIDs, either.
1376 if (!TransactionIdIsValid(xid))
1378 /* Reset XactLastRecEnd until the next transaction writes something */
1381 return InvalidTransactionId;
1385 * We have a valid XID, so we should write an ABORT record for it.
1387 * We do not flush XLOG to disk here, since the default assumption after a
1388 * crash would be that we aborted, anyway. For the same reason, we don't
1389 * need to worry about interlocking against checkpoint start.
1393 * Check that we haven't aborted halfway through RecordTransactionCommit.
1395 if (TransactionIdDidCommit(xid))
1396 elog(PANIC, "cannot abort transaction %u, it was already committed",
1399 /* Fetch the data we need for the abort record */
1400 nrels = smgrGetPendingDeletes(false, &rels);
1401 nchildren = xactGetCommittedChildren(&children);
1403 /* XXX do we really need a critical section here? */
1404 START_CRIT_SECTION();
1406 /* Write the ABORT record */
1408 xact_time = GetCurrentTimestamp();
1411 SetCurrentTransactionStopTimestamp();
1412 xact_time = xactStopTimestamp;
1415 XactLogAbortRecord(xact_time,
1416 nchildren, children,
1418 InvalidTransactionId);
1421 * Report the latest async abort LSN, so that the WAL writer knows to
1422 * flush this abort. There's nothing to be gained by delaying this, since
1423 * WALWriter may as well do this when it can. This is important with
1424 * streaming replication because if we don't flush WAL regularly we will
1425 * find that large aborts leave us with a long backlog for when commits
1426 * occur after the abort, increasing our window of data loss should
1427 * problems occur at that point.
1430 XLogSetAsyncXactLSN(XactLastRecEnd);
1433 * Mark the transaction aborted in clog. This is not absolutely necessary
1434 * but we may as well do it while we are here; also, in the subxact case
1435 * it is helpful because XactLockTableWait makes use of it to avoid
1436 * waiting for already-aborted subtransactions. It is OK to do it without
1437 * having flushed the ABORT record to disk, because in event of a crash
1438 * we'd be assumed to have aborted anyway.
1440 TransactionIdAbortTree(xid, nchildren, children);
1444 /* Compute latestXid while we have the child XIDs handy */
1445 latestXid = TransactionIdLatest(xid, nchildren, children);
1448 * If we're aborting a subtransaction, we can immediately remove failed
1449 * XIDs from PGPROC's cache of running child XIDs. We do that here for
1450 * subxacts, because we already have the child XID array at hand. For
1451 * main xacts, the equivalent happens just after this function returns.
1454 XidCacheRemoveRunningXids(xid, nchildren, children, latestXid);
1456 /* Reset XactLastRecEnd until the next transaction writes something */
1460 /* And clean up local data */
1471 AtAbort_Memory(void)
1474 * Switch into TransactionAbortContext, which should have some free space
1475 * even if nothing else does. We'll work in this context until we've
1476 * finished cleaning up.
1478 * It is barely possible to get here when we've not been able to create
1479 * TransactionAbortContext yet; if so use TopMemoryContext.
1481 if (TransactionAbortContext != NULL)
1482 MemoryContextSwitchTo(TransactionAbortContext);
1484 MemoryContextSwitchTo(TopMemoryContext);
1491 AtSubAbort_Memory(void)
1493 Assert(TransactionAbortContext != NULL);
1495 MemoryContextSwitchTo(TransactionAbortContext);
1500 * AtAbort_ResourceOwner
1503 AtAbort_ResourceOwner(void)
1506 * Make sure we have a valid ResourceOwner, if possible (else it will be
1507 * NULL, which is OK)
1509 CurrentResourceOwner = TopTransactionResourceOwner;
1513 * AtSubAbort_ResourceOwner
1516 AtSubAbort_ResourceOwner(void)
1518 TransactionState s = CurrentTransactionState;
1520 /* Make sure we have a valid ResourceOwner */
1521 CurrentResourceOwner = s->curTransactionOwner;
1526 * AtSubAbort_childXids
1529 AtSubAbort_childXids(void)
1531 TransactionState s = CurrentTransactionState;
1534 * We keep the child-XID arrays in TopTransactionContext (see
1535 * AtSubCommit_childXids). This means we'd better free the array
1536 * explicitly at abort to avoid leakage.
1538 if (s->childXids != NULL)
1539 pfree(s->childXids);
1540 s->childXids = NULL;
1542 s->maxChildXids = 0;
1545 * We could prune the unreportedXids array here. But we don't bother. That
1546 * would potentially reduce number of XLOG_XACT_ASSIGNMENT records but it
1547 * would likely introduce more CPU time into the more common paths, so we
1548 * choose not to do that.
1552 /* ----------------------------------------------------------------
1553 * CleanupTransaction stuff
1554 * ----------------------------------------------------------------
1561 AtCleanup_Memory(void)
1563 Assert(CurrentTransactionState->parent == NULL);
1566 * Now that we're "out" of a transaction, have the system allocate things
1567 * in the top memory context instead of per-transaction contexts.
1569 MemoryContextSwitchTo(TopMemoryContext);
1572 * Clear the special abort context for next time.
1574 if (TransactionAbortContext != NULL)
1575 MemoryContextResetAndDeleteChildren(TransactionAbortContext);
1578 * Release all transaction-local memory.
1580 if (TopTransactionContext != NULL)
1581 MemoryContextDelete(TopTransactionContext);
1582 TopTransactionContext = NULL;
1583 CurTransactionContext = NULL;
1584 CurrentTransactionState->curTransactionContext = NULL;
1588 /* ----------------------------------------------------------------
1589 * CleanupSubTransaction stuff
1590 * ----------------------------------------------------------------
1594 * AtSubCleanup_Memory
1597 AtSubCleanup_Memory(void)
1599 TransactionState s = CurrentTransactionState;
1601 Assert(s->parent != NULL);
1603 /* Make sure we're not in an about-to-be-deleted context */
1604 MemoryContextSwitchTo(s->parent->curTransactionContext);
1605 CurTransactionContext = s->parent->curTransactionContext;
1608 * Clear the special abort context for next time.
1610 if (TransactionAbortContext != NULL)
1611 MemoryContextResetAndDeleteChildren(TransactionAbortContext);
1614 * Delete the subxact local memory contexts. Its CurTransactionContext can
1615 * go too (note this also kills CurTransactionContexts from any children
1618 if (s->curTransactionContext)
1619 MemoryContextDelete(s->curTransactionContext);
1620 s->curTransactionContext = NULL;
1623 /* ----------------------------------------------------------------
1624 * interface routines
1625 * ----------------------------------------------------------------
1632 StartTransaction(void)
1635 VirtualTransactionId vxid;
1638 * Let's just make sure the state stack is empty
1640 s = &TopTransactionStateData;
1641 CurrentTransactionState = s;
1644 * check the current transaction state
1646 if (s->state != TRANS_DEFAULT)
1647 elog(WARNING, "StartTransaction while in %s state",
1648 TransStateAsString(s->state));
1651 * set the current transaction state information appropriately during
1654 s->state = TRANS_START;
1655 s->transactionId = InvalidTransactionId; /* until assigned */
1658 * Make sure we've reset xact state variables
1660 * If recovery is still in progress, mark this transaction as read-only.
1661 * We have lower level defences in XLogInsert and elsewhere to stop us
1662 * from modifying data during recovery, but this gives the normal
1663 * indication to the user that the transaction is read-only.
1665 if (RecoveryInProgress())
1667 s->startedInRecovery = true;
1668 XactReadOnly = true;
1672 s->startedInRecovery = false;
1673 XactReadOnly = DefaultXactReadOnly;
1675 XactDeferrable = DefaultXactDeferrable;
1676 XactIsoLevel = DefaultXactIsoLevel;
1677 forceSyncCommit = false;
1678 MyXactAccessedTempRel = false;
1681 * reinitialize within-transaction counters
1683 s->subTransactionId = TopSubTransactionId;
1684 currentSubTransactionId = TopSubTransactionId;
1685 currentCommandId = FirstCommandId;
1686 currentCommandIdUsed = false;
1689 * initialize reported xid accounting
1691 nUnreportedXids = 0;
1692 s->didLogXid = false;
1695 * must initialize resource-management stuff first
1698 AtStart_ResourceOwner();
1701 * Assign a new LocalTransactionId, and combine it with the backendId to
1702 * form a virtual transaction id.
1704 vxid.backendId = MyBackendId;
1705 vxid.localTransactionId = GetNextLocalTransactionId();
1708 * Lock the virtual transaction id before we announce it in the proc array
1710 VirtualXactLockTableInsert(vxid);
1713 * Advertise it in the proc array. We assume assignment of
1714 * LocalTransactionID is atomic, and the backendId should be set already.
1716 Assert(MyProc->backendId == vxid.backendId);
1717 MyProc->lxid = vxid.localTransactionId;
1719 TRACE_POSTGRESQL_TRANSACTION_START(vxid.localTransactionId);
1722 * set transaction_timestamp() (a/k/a now()). We want this to be the same
1723 * as the first command's statement_timestamp(), so don't do a fresh
1724 * GetCurrentTimestamp() call (which'd be expensive anyway). Also, mark
1725 * xactStopTimestamp as unset.
1727 xactStartTimestamp = stmtStartTimestamp;
1728 xactStopTimestamp = 0;
1729 pgstat_report_xact_timestamp(xactStartTimestamp);
1732 * initialize current transaction state fields
1734 * note: prevXactReadOnly is not used at the outermost level
1736 s->nestingLevel = 1;
1737 s->gucNestLevel = 1;
1738 s->childXids = NULL;
1740 s->maxChildXids = 0;
1741 GetUserIdAndSecContext(&s->prevUser, &s->prevSecContext);
1742 /* SecurityRestrictionContext should never be set outside a transaction */
1743 Assert(s->prevSecContext == 0);
1746 * initialize other subsystems for new transaction
1750 AfterTriggerBeginXact();
1753 * done with start processing, set current transaction state to "in
1756 s->state = TRANS_INPROGRESS;
1758 ShowTransactionState("StartTransaction");
1765 * NB: if you change this routine, better look at PrepareTransaction too!
1768 CommitTransaction(void)
1770 TransactionState s = CurrentTransactionState;
1771 TransactionId latestXid;
1773 ShowTransactionState("CommitTransaction");
1776 * check the current transaction state
1778 if (s->state != TRANS_INPROGRESS)
1779 elog(WARNING, "CommitTransaction while in %s state",
1780 TransStateAsString(s->state));
1781 Assert(s->parent == NULL);
1784 * Do pre-commit processing that involves calling user-defined code, such
1785 * as triggers. Since closing cursors could queue trigger actions,
1786 * triggers could open cursors, etc, we have to keep looping until there's
1787 * nothing left to do.
1792 * Fire all currently pending deferred triggers.
1794 AfterTriggerFireDeferred();
1797 * Close open portals (converting holdable ones into static portals).
1798 * If there weren't any, we are done ... otherwise loop back to check
1799 * if they queued deferred triggers. Lather, rinse, repeat.
1801 if (!PreCommit_Portals(false))
1805 CallXactCallbacks(XACT_EVENT_PRE_COMMIT);
1808 * The remaining actions cannot call any user-defined code, so it's safe
1809 * to start shutting down within-transaction services. But note that most
1810 * of this stuff could still throw an error, which would switch us into
1811 * the transaction-abort path.
1814 /* Shut down the deferred-trigger manager */
1815 AfterTriggerEndXact(true);
1818 * Let ON COMMIT management do its thing (must happen after closing
1819 * cursors, to avoid dangling-reference problems)
1821 PreCommit_on_commit_actions();
1823 /* close large objects before lower-level cleanup */
1824 AtEOXact_LargeObject(true);
1827 * Mark serializable transaction as complete for predicate locking
1828 * purposes. This should be done as late as we can put it and still allow
1829 * errors to be raised for failure patterns found at commit.
1831 PreCommit_CheckForSerializationFailure();
1834 * Insert notifications sent by NOTIFY commands into the queue. This
1835 * should be late in the pre-commit sequence to minimize time spent
1836 * holding the notify-insertion lock.
1840 /* Prevent cancel/die interrupt while cleaning up */
1843 /* Commit updates to the relation map --- do this as late as possible */
1844 AtEOXact_RelationMap(true);
1847 * set the current transaction state information appropriately during
1850 s->state = TRANS_COMMIT;
1853 * Here is where we really truly commit.
1855 latestXid = RecordTransactionCommit();
1857 TRACE_POSTGRESQL_TRANSACTION_COMMIT(MyProc->lxid);
1860 * Let others know about no transaction in progress by me. Note that this
1861 * must be done _before_ releasing locks we hold and _after_
1862 * RecordTransactionCommit.
1864 ProcArrayEndTransaction(MyProc, latestXid);
1867 * This is all post-commit cleanup. Note that if an error is raised here,
1868 * it's too late to abort the transaction. This should be just
1869 * noncritical resource releasing.
1871 * The ordering of operations is not entirely random. The idea is:
1872 * release resources visible to other backends (eg, files, buffer pins);
1873 * then release locks; then release backend-local resources. We want to
1874 * release locks at the point where any backend waiting for us will see
1875 * our transaction as being fully cleaned up.
1877 * Resources that can be associated with individual queries are handled by
1878 * the ResourceOwner mechanism. The other calls here are for backend-wide
1882 CallXactCallbacks(XACT_EVENT_COMMIT);
1884 ResourceOwnerRelease(TopTransactionResourceOwner,
1885 RESOURCE_RELEASE_BEFORE_LOCKS,
1888 /* Check we've released all buffer pins */
1889 AtEOXact_Buffers(true);
1891 /* Clean up the relation cache */
1892 AtEOXact_RelationCache(true);
1895 * Make catalog changes visible to all backends. This has to happen after
1896 * relcache references are dropped (see comments for
1897 * AtEOXact_RelationCache), but before locks are released (if anyone is
1898 * waiting for lock on a relation we've modified, we want them to know
1899 * about the catalog change before they start using the relation).
1901 AtEOXact_Inval(true);
1903 AtEOXact_MultiXact();
1905 ResourceOwnerRelease(TopTransactionResourceOwner,
1906 RESOURCE_RELEASE_LOCKS,
1908 ResourceOwnerRelease(TopTransactionResourceOwner,
1909 RESOURCE_RELEASE_AFTER_LOCKS,
1913 * Likewise, dropping of files deleted during the transaction is best done
1914 * after releasing relcache and buffer pins. (This is not strictly
1915 * necessary during commit, since such pins should have been released
1916 * already, but this ordering is definitely critical during abort.) Since
1917 * this may take many seconds, also delay until after releasing locks.
1918 * Other backends will observe the attendant catalog changes and not
1919 * attempt to access affected files.
1921 smgrDoPendingDeletes(true);
1923 /* Check we've released all catcache entries */
1924 AtEOXact_CatCache(true);
1927 AtEOXact_GUC(true, 1);
1929 AtEOXact_on_commit_actions(true);
1930 AtEOXact_Namespace(true);
1933 AtEOXact_ComboCid();
1934 AtEOXact_HashTables(true);
1935 AtEOXact_PgStat(true);
1936 AtEOXact_Snapshot(true);
1937 pgstat_report_xact_timestamp(0);
1939 CurrentResourceOwner = NULL;
1940 ResourceOwnerDelete(TopTransactionResourceOwner);
1941 s->curTransactionOwner = NULL;
1942 CurTransactionResourceOwner = NULL;
1943 TopTransactionResourceOwner = NULL;
1947 s->transactionId = InvalidTransactionId;
1948 s->subTransactionId = InvalidSubTransactionId;
1949 s->nestingLevel = 0;
1950 s->gucNestLevel = 0;
1951 s->childXids = NULL;
1953 s->maxChildXids = 0;
1956 * done with commit processing, set current transaction state back to
1959 s->state = TRANS_DEFAULT;
1961 RESUME_INTERRUPTS();
1966 * PrepareTransaction
1968 * NB: if you change this routine, better look at CommitTransaction too!
1971 PrepareTransaction(void)
1973 TransactionState s = CurrentTransactionState;
1974 TransactionId xid = GetCurrentTransactionId();
1975 GlobalTransaction gxact;
1976 TimestampTz prepared_at;
1978 ShowTransactionState("PrepareTransaction");
1981 * check the current transaction state
1983 if (s->state != TRANS_INPROGRESS)
1984 elog(WARNING, "PrepareTransaction while in %s state",
1985 TransStateAsString(s->state));
1986 Assert(s->parent == NULL);
1989 * Do pre-commit processing that involves calling user-defined code, such
1990 * as triggers. Since closing cursors could queue trigger actions,
1991 * triggers could open cursors, etc, we have to keep looping until there's
1992 * nothing left to do.
1997 * Fire all currently pending deferred triggers.
1999 AfterTriggerFireDeferred();
2002 * Close open portals (converting holdable ones into static portals).
2003 * If there weren't any, we are done ... otherwise loop back to check
2004 * if they queued deferred triggers. Lather, rinse, repeat.
2006 if (!PreCommit_Portals(true))
2010 CallXactCallbacks(XACT_EVENT_PRE_PREPARE);
2013 * The remaining actions cannot call any user-defined code, so it's safe
2014 * to start shutting down within-transaction services. But note that most
2015 * of this stuff could still throw an error, which would switch us into
2016 * the transaction-abort path.
2019 /* Shut down the deferred-trigger manager */
2020 AfterTriggerEndXact(true);
2023 * Let ON COMMIT management do its thing (must happen after closing
2024 * cursors, to avoid dangling-reference problems)
2026 PreCommit_on_commit_actions();
2028 /* close large objects before lower-level cleanup */
2029 AtEOXact_LargeObject(true);
2032 * Mark serializable transaction as complete for predicate locking
2033 * purposes. This should be done as late as we can put it and still allow
2034 * errors to be raised for failure patterns found at commit.
2036 PreCommit_CheckForSerializationFailure();
2038 /* NOTIFY will be handled below */
2041 * Don't allow PREPARE TRANSACTION if we've accessed a temporary table in
2042 * this transaction. Having the prepared xact hold locks on another
2043 * backend's temp table seems a bad idea --- for instance it would prevent
2044 * the backend from exiting. There are other problems too, such as how to
2045 * clean up the source backend's local buffers and ON COMMIT state if the
2046 * prepared xact includes a DROP of a temp table.
2048 * We must check this after executing any ON COMMIT actions, because they
2049 * might still access a temp relation.
2051 * XXX In principle this could be relaxed to allow some useful special
2052 * cases, such as a temp table created and dropped all within the
2053 * transaction. That seems to require much more bookkeeping though.
2055 if (MyXactAccessedTempRel)
2057 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2058 errmsg("cannot PREPARE a transaction that has operated on temporary tables")));
2061 * Likewise, don't allow PREPARE after pg_export_snapshot. This could be
2062 * supported if we added cleanup logic to twophase.c, but for now it
2063 * doesn't seem worth the trouble.
2065 if (XactHasExportedSnapshots())
2067 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2068 errmsg("cannot PREPARE a transaction that has exported snapshots")));
2070 /* Prevent cancel/die interrupt while cleaning up */
2074 * set the current transaction state information appropriately during
2075 * prepare processing
2077 s->state = TRANS_PREPARE;
2079 prepared_at = GetCurrentTimestamp();
2081 /* Tell bufmgr and smgr to prepare for commit */
2085 * Reserve the GID for this transaction. This could fail if the requested
2086 * GID is invalid or already in use.
2088 gxact = MarkAsPreparing(xid, prepareGID, prepared_at,
2089 GetUserId(), MyDatabaseId);
2093 * Collect data for the 2PC state file. Note that in general, no actual
2094 * state change should happen in the called modules during this step,
2095 * since it's still possible to fail before commit, and in that case we
2096 * want transaction abort to be able to clean up. (In particular, the
2097 * AtPrepare routines may error out if they find cases they cannot
2098 * handle.) State cleanup should happen in the PostPrepare routines
2099 * below. However, some modules can go ahead and clear state here because
2100 * they wouldn't do anything with it during abort anyway.
2102 * Note: because the 2PC state file records will be replayed in the same
2103 * order they are made, the order of these calls has to match the order in
2104 * which we want things to happen during COMMIT PREPARED or ROLLBACK
2105 * PREPARED; in particular, pay attention to whether things should happen
2106 * before or after releasing the transaction's locks.
2108 StartPrepare(gxact);
2112 AtPrepare_PredicateLocks();
2114 AtPrepare_MultiXact();
2115 AtPrepare_RelationMap();
2118 * Here is where we really truly prepare.
2120 * We have to record transaction prepares even if we didn't make any
2121 * updates, because the transaction manager might get confused if we lose
2122 * a global transaction.
2127 * Now we clean up backend-internal state and release internal resources.
2130 /* Reset XactLastRecEnd until the next transaction writes something */
2134 * Let others know about no transaction in progress by me. This has to be
2135 * done *after* the prepared transaction has been marked valid, else
2136 * someone may think it is unlocked and recyclable.
2138 ProcArrayClearTransaction(MyProc);
2141 * In normal commit-processing, this is all non-critical post-transaction
2142 * cleanup. When the transaction is prepared, however, it's important that
2143 * the locks and other per-backend resources are transfered to the
2144 * prepared transaction's PGPROC entry. Note that if an error is raised
2145 * here, it's too late to abort the transaction. XXX: This probably should
2146 * be in a critical section, to force a PANIC if any of this fails, but
2147 * that cure could be worse than the disease.
2150 CallXactCallbacks(XACT_EVENT_PREPARE);
2152 ResourceOwnerRelease(TopTransactionResourceOwner,
2153 RESOURCE_RELEASE_BEFORE_LOCKS,
2156 /* Check we've released all buffer pins */
2157 AtEOXact_Buffers(true);
2159 /* Clean up the relation cache */
2160 AtEOXact_RelationCache(true);
2162 /* notify doesn't need a postprepare call */
2164 PostPrepare_PgStat();
2166 PostPrepare_Inval();
2170 PostPrepare_MultiXact(xid);
2172 PostPrepare_Locks(xid);
2173 PostPrepare_PredicateLocks(xid);
2175 ResourceOwnerRelease(TopTransactionResourceOwner,
2176 RESOURCE_RELEASE_LOCKS,
2178 ResourceOwnerRelease(TopTransactionResourceOwner,
2179 RESOURCE_RELEASE_AFTER_LOCKS,
2183 * Allow another backend to finish the transaction. After
2184 * PostPrepare_Twophase(), the transaction is completely detached from
2185 * our backend. The rest is just non-critical cleanup of backend-local
2188 PostPrepare_Twophase();
2190 /* Check we've released all catcache entries */
2191 AtEOXact_CatCache(true);
2193 /* PREPARE acts the same as COMMIT as far as GUC is concerned */
2194 AtEOXact_GUC(true, 1);
2196 AtEOXact_on_commit_actions(true);
2197 AtEOXact_Namespace(true);
2200 AtEOXact_ComboCid();
2201 AtEOXact_HashTables(true);
2202 /* don't call AtEOXact_PgStat here; we fixed pgstat state above */
2203 AtEOXact_Snapshot(true);
2204 pgstat_report_xact_timestamp(0);
2206 CurrentResourceOwner = NULL;
2207 ResourceOwnerDelete(TopTransactionResourceOwner);
2208 s->curTransactionOwner = NULL;
2209 CurTransactionResourceOwner = NULL;
2210 TopTransactionResourceOwner = NULL;
2214 s->transactionId = InvalidTransactionId;
2215 s->subTransactionId = InvalidSubTransactionId;
2216 s->nestingLevel = 0;
2217 s->gucNestLevel = 0;
2218 s->childXids = NULL;
2220 s->maxChildXids = 0;
2223 * done with 1st phase commit processing, set current transaction state
2226 s->state = TRANS_DEFAULT;
2228 RESUME_INTERRUPTS();
2236 AbortTransaction(void)
2238 TransactionState s = CurrentTransactionState;
2239 TransactionId latestXid;
2241 /* Prevent cancel/die interrupt while cleaning up */
2244 /* Make sure we have a valid memory context and resource owner */
2246 AtAbort_ResourceOwner();
2249 * Release any LW locks we might be holding as quickly as possible.
2250 * (Regular locks, however, must be held till we finish aborting.)
2251 * Releasing LW locks is critical since we might try to grab them again
2252 * while cleaning up!
2256 /* Clean up buffer I/O and buffer context locks, too */
2260 /* Reset WAL record construction state */
2261 XLogResetInsertion();
2264 * Also clean up any open wait for lock, since the lock manager will choke
2265 * if we try to wait for another lock before doing this.
2270 * If any timeout events are still active, make sure the timeout interrupt
2271 * is scheduled. This covers possible loss of a timeout interrupt due to
2272 * longjmp'ing out of the SIGINT handler (see notes in handle_sig_alarm).
2273 * We delay this till after LockErrorCleanup so that we don't uselessly
2274 * reschedule lock or deadlock check timeouts.
2276 reschedule_timeouts();
2279 * Re-enable signals, in case we got here by longjmp'ing out of a signal
2280 * handler. We do this fairly early in the sequence so that the timeout
2281 * infrastructure will be functional if needed while aborting.
2283 PG_SETMASK(&UnBlockSig);
2286 * check the current transaction state
2288 if (s->state != TRANS_INPROGRESS && s->state != TRANS_PREPARE)
2289 elog(WARNING, "AbortTransaction while in %s state",
2290 TransStateAsString(s->state));
2291 Assert(s->parent == NULL);
2294 * set the current transaction state information appropriately during the
2297 s->state = TRANS_ABORT;
2300 * Reset user ID which might have been changed transiently. We need this
2301 * to clean up in case control escaped out of a SECURITY DEFINER function
2302 * or other local change of CurrentUserId; therefore, the prior value of
2303 * SecurityRestrictionContext also needs to be restored.
2305 * (Note: it is not necessary to restore session authorization or role
2306 * settings here because those can only be changed via GUC, and GUC will
2307 * take care of rolling them back if need be.)
2309 SetUserIdAndSecContext(s->prevUser, s->prevSecContext);
2312 * do abort processing
2314 AfterTriggerEndXact(false); /* 'false' means it's abort */
2316 AtEOXact_LargeObject(false);
2318 AtEOXact_RelationMap(false);
2322 * Advertise the fact that we aborted in pg_clog (assuming that we got as
2323 * far as assigning an XID to advertise).
2325 latestXid = RecordTransactionAbort(false);
2327 TRACE_POSTGRESQL_TRANSACTION_ABORT(MyProc->lxid);
2330 * Let others know about no transaction in progress by me. Note that this
2331 * must be done _before_ releasing locks we hold and _after_
2332 * RecordTransactionAbort.
2334 ProcArrayEndTransaction(MyProc, latestXid);
2337 * Post-abort cleanup. See notes in CommitTransaction() concerning
2338 * ordering. We can skip all of it if the transaction failed before
2339 * creating a resource owner.
2341 if (TopTransactionResourceOwner != NULL)
2343 CallXactCallbacks(XACT_EVENT_ABORT);
2345 ResourceOwnerRelease(TopTransactionResourceOwner,
2346 RESOURCE_RELEASE_BEFORE_LOCKS,
2348 AtEOXact_Buffers(false);
2349 AtEOXact_RelationCache(false);
2350 AtEOXact_Inval(false);
2351 AtEOXact_MultiXact();
2352 ResourceOwnerRelease(TopTransactionResourceOwner,
2353 RESOURCE_RELEASE_LOCKS,
2355 ResourceOwnerRelease(TopTransactionResourceOwner,
2356 RESOURCE_RELEASE_AFTER_LOCKS,
2358 smgrDoPendingDeletes(false);
2359 AtEOXact_CatCache(false);
2361 AtEOXact_GUC(false, 1);
2362 AtEOXact_SPI(false);
2363 AtEOXact_on_commit_actions(false);
2364 AtEOXact_Namespace(false);
2367 AtEOXact_ComboCid();
2368 AtEOXact_HashTables(false);
2369 AtEOXact_PgStat(false);
2370 pgstat_report_xact_timestamp(0);
2374 * State remains TRANS_ABORT until CleanupTransaction().
2376 RESUME_INTERRUPTS();
2380 * CleanupTransaction
2383 CleanupTransaction(void)
2385 TransactionState s = CurrentTransactionState;
2388 * State should still be TRANS_ABORT from AbortTransaction().
2390 if (s->state != TRANS_ABORT)
2391 elog(FATAL, "CleanupTransaction: unexpected state %s",
2392 TransStateAsString(s->state));
2395 * do abort cleanup processing
2397 AtCleanup_Portals(); /* now safe to release portal memory */
2398 AtEOXact_Snapshot(false); /* and release the transaction's snapshots */
2400 CurrentResourceOwner = NULL; /* and resource owner */
2401 if (TopTransactionResourceOwner)
2402 ResourceOwnerDelete(TopTransactionResourceOwner);
2403 s->curTransactionOwner = NULL;
2404 CurTransactionResourceOwner = NULL;
2405 TopTransactionResourceOwner = NULL;
2407 AtCleanup_Memory(); /* and transaction memory */
2409 s->transactionId = InvalidTransactionId;
2410 s->subTransactionId = InvalidSubTransactionId;
2411 s->nestingLevel = 0;
2412 s->gucNestLevel = 0;
2413 s->childXids = NULL;
2415 s->maxChildXids = 0;
2418 * done with abort processing, set current transaction state back to
2421 s->state = TRANS_DEFAULT;
2425 * StartTransactionCommand
2428 StartTransactionCommand(void)
2430 TransactionState s = CurrentTransactionState;
2432 switch (s->blockState)
2435 * if we aren't in a transaction block, we just do our usual start
2438 case TBLOCK_DEFAULT:
2440 s->blockState = TBLOCK_STARTED;
2444 * We are somewhere in a transaction block or subtransaction and
2445 * about to start a new command. For now we do nothing, but
2446 * someday we may do command-local resource initialization. (Note
2447 * that any needed CommandCounterIncrement was done by the
2448 * previous CommitTransactionCommand.)
2450 case TBLOCK_INPROGRESS:
2451 case TBLOCK_SUBINPROGRESS:
2455 * Here we are in a failed transaction block (one of the commands
2456 * caused an abort) so we do nothing but remain in the abort
2457 * state. Eventually we will get a ROLLBACK command which will
2458 * get us out of this state. (It is up to other code to ensure
2459 * that no commands other than ROLLBACK will be processed in these
2463 case TBLOCK_SUBABORT:
2466 /* These cases are invalid. */
2467 case TBLOCK_STARTED:
2469 case TBLOCK_SUBBEGIN:
2471 case TBLOCK_SUBRELEASE:
2472 case TBLOCK_SUBCOMMIT:
2473 case TBLOCK_ABORT_END:
2474 case TBLOCK_SUBABORT_END:
2475 case TBLOCK_ABORT_PENDING:
2476 case TBLOCK_SUBABORT_PENDING:
2477 case TBLOCK_SUBRESTART:
2478 case TBLOCK_SUBABORT_RESTART:
2479 case TBLOCK_PREPARE:
2480 elog(ERROR, "StartTransactionCommand: unexpected state %s",
2481 BlockStateAsString(s->blockState));
2486 * We must switch to CurTransactionContext before returning. This is
2487 * already done if we called StartTransaction, otherwise not.
2489 Assert(CurTransactionContext != NULL);
2490 MemoryContextSwitchTo(CurTransactionContext);
2494 * CommitTransactionCommand
2497 CommitTransactionCommand(void)
2499 TransactionState s = CurrentTransactionState;
2501 switch (s->blockState)
2504 * This shouldn't happen, because it means the previous
2505 * StartTransactionCommand didn't set the STARTED state
2508 case TBLOCK_DEFAULT:
2509 elog(FATAL, "CommitTransactionCommand: unexpected state %s",
2510 BlockStateAsString(s->blockState));
2514 * If we aren't in a transaction block, just do our usual
2515 * transaction commit, and return to the idle state.
2517 case TBLOCK_STARTED:
2518 CommitTransaction();
2519 s->blockState = TBLOCK_DEFAULT;
2523 * We are completing a "BEGIN TRANSACTION" command, so we change
2524 * to the "transaction block in progress" state and return. (We
2525 * assume the BEGIN did nothing to the database, so we need no
2526 * CommandCounterIncrement.)
2529 s->blockState = TBLOCK_INPROGRESS;
2533 * This is the case when we have finished executing a command
2534 * someplace within a transaction block. We increment the command
2535 * counter and return.
2537 case TBLOCK_INPROGRESS:
2538 case TBLOCK_SUBINPROGRESS:
2539 CommandCounterIncrement();
2543 * We are completing a "COMMIT" command. Do it and return to the
2547 CommitTransaction();
2548 s->blockState = TBLOCK_DEFAULT;
2552 * Here we are in the middle of a transaction block but one of the
2553 * commands caused an abort so we do nothing but remain in the
2554 * abort state. Eventually we will get a ROLLBACK comand.
2557 case TBLOCK_SUBABORT:
2561 * Here we were in an aborted transaction block and we just got
2562 * the ROLLBACK command from the user, so clean up the
2563 * already-aborted transaction and return to the idle state.
2565 case TBLOCK_ABORT_END:
2566 CleanupTransaction();
2567 s->blockState = TBLOCK_DEFAULT;
2571 * Here we were in a perfectly good transaction block but the user
2572 * told us to ROLLBACK anyway. We have to abort the transaction
2573 * and then clean up.
2575 case TBLOCK_ABORT_PENDING:
2577 CleanupTransaction();
2578 s->blockState = TBLOCK_DEFAULT;
2582 * We are completing a "PREPARE TRANSACTION" command. Do it and
2583 * return to the idle state.
2585 case TBLOCK_PREPARE:
2586 PrepareTransaction();
2587 s->blockState = TBLOCK_DEFAULT;
2591 * We were just issued a SAVEPOINT inside a transaction block.
2592 * Start a subtransaction. (DefineSavepoint already did
2593 * PushTransaction, so as to have someplace to put the SUBBEGIN
2596 case TBLOCK_SUBBEGIN:
2597 StartSubTransaction();
2598 s->blockState = TBLOCK_SUBINPROGRESS;
2602 * We were issued a RELEASE command, so we end the current
2603 * subtransaction and return to the parent transaction. The parent
2604 * might be ended too, so repeat till we find an INPROGRESS
2605 * transaction or subtransaction.
2607 case TBLOCK_SUBRELEASE:
2610 CommitSubTransaction();
2611 s = CurrentTransactionState; /* changed by pop */
2612 } while (s->blockState == TBLOCK_SUBRELEASE);
2614 Assert(s->blockState == TBLOCK_INPROGRESS ||
2615 s->blockState == TBLOCK_SUBINPROGRESS);
2619 * We were issued a COMMIT, so we end the current subtransaction
2620 * hierarchy and perform final commit. We do this by rolling up
2621 * any subtransactions into their parent, which leads to O(N^2)
2622 * operations with respect to resource owners - this isn't that
2623 * bad until we approach a thousands of savepoints but is
2624 * necessary for correctness should after triggers create new
2627 case TBLOCK_SUBCOMMIT:
2630 CommitSubTransaction();
2631 s = CurrentTransactionState; /* changed by pop */
2632 } while (s->blockState == TBLOCK_SUBCOMMIT);
2633 /* If we had a COMMIT command, finish off the main xact too */
2634 if (s->blockState == TBLOCK_END)
2636 Assert(s->parent == NULL);
2637 CommitTransaction();
2638 s->blockState = TBLOCK_DEFAULT;
2640 else if (s->blockState == TBLOCK_PREPARE)
2642 Assert(s->parent == NULL);
2643 PrepareTransaction();
2644 s->blockState = TBLOCK_DEFAULT;
2647 elog(ERROR, "CommitTransactionCommand: unexpected state %s",
2648 BlockStateAsString(s->blockState));
2652 * The current already-failed subtransaction is ending due to a
2653 * ROLLBACK or ROLLBACK TO command, so pop it and recursively
2654 * examine the parent (which could be in any of several states).
2656 case TBLOCK_SUBABORT_END:
2657 CleanupSubTransaction();
2658 CommitTransactionCommand();
2662 * As above, but it's not dead yet, so abort first.
2664 case TBLOCK_SUBABORT_PENDING:
2665 AbortSubTransaction();
2666 CleanupSubTransaction();
2667 CommitTransactionCommand();
2671 * The current subtransaction is the target of a ROLLBACK TO
2672 * command. Abort and pop it, then start a new subtransaction
2673 * with the same name.
2675 case TBLOCK_SUBRESTART:
2680 /* save name and keep Cleanup from freeing it */
2683 savepointLevel = s->savepointLevel;
2685 AbortSubTransaction();
2686 CleanupSubTransaction();
2688 DefineSavepoint(NULL);
2689 s = CurrentTransactionState; /* changed by push */
2691 s->savepointLevel = savepointLevel;
2693 /* This is the same as TBLOCK_SUBBEGIN case */
2694 AssertState(s->blockState == TBLOCK_SUBBEGIN);
2695 StartSubTransaction();
2696 s->blockState = TBLOCK_SUBINPROGRESS;
2701 * Same as above, but the subtransaction had already failed, so we
2702 * don't need AbortSubTransaction.
2704 case TBLOCK_SUBABORT_RESTART:
2709 /* save name and keep Cleanup from freeing it */
2712 savepointLevel = s->savepointLevel;
2714 CleanupSubTransaction();
2716 DefineSavepoint(NULL);
2717 s = CurrentTransactionState; /* changed by push */
2719 s->savepointLevel = savepointLevel;
2721 /* This is the same as TBLOCK_SUBBEGIN case */
2722 AssertState(s->blockState == TBLOCK_SUBBEGIN);
2723 StartSubTransaction();
2724 s->blockState = TBLOCK_SUBINPROGRESS;
2731 * AbortCurrentTransaction
2734 AbortCurrentTransaction(void)
2736 TransactionState s = CurrentTransactionState;
2738 switch (s->blockState)
2740 case TBLOCK_DEFAULT:
2741 if (s->state == TRANS_DEFAULT)
2743 /* we are idle, so nothing to do */
2748 * We can get here after an error during transaction start
2749 * (state will be TRANS_START). Need to clean up the
2750 * incompletely started transaction. First, adjust the
2751 * low-level state to suppress warning message from
2754 if (s->state == TRANS_START)
2755 s->state = TRANS_INPROGRESS;
2757 CleanupTransaction();
2762 * if we aren't in a transaction block, we just do the basic abort
2763 * & cleanup transaction.
2765 case TBLOCK_STARTED:
2767 CleanupTransaction();
2768 s->blockState = TBLOCK_DEFAULT;
2772 * If we are in TBLOCK_BEGIN it means something screwed up right
2773 * after reading "BEGIN TRANSACTION". We assume that the user
2774 * will interpret the error as meaning the BEGIN failed to get him
2775 * into a transaction block, so we should abort and return to idle
2780 CleanupTransaction();
2781 s->blockState = TBLOCK_DEFAULT;
2785 * We are somewhere in a transaction block and we've gotten a
2786 * failure, so we abort the transaction and set up the persistent
2787 * ABORT state. We will stay in ABORT until we get a ROLLBACK.
2789 case TBLOCK_INPROGRESS:
2791 s->blockState = TBLOCK_ABORT;
2792 /* CleanupTransaction happens when we exit TBLOCK_ABORT_END */
2796 * Here, we failed while trying to COMMIT. Clean up the
2797 * transaction and return to idle state (we do not want to stay in
2802 CleanupTransaction();
2803 s->blockState = TBLOCK_DEFAULT;
2807 * Here, we are already in an aborted transaction state and are
2808 * waiting for a ROLLBACK, but for some reason we failed again! So
2809 * we just remain in the abort state.
2812 case TBLOCK_SUBABORT:
2816 * We are in a failed transaction and we got the ROLLBACK command.
2817 * We have already aborted, we just need to cleanup and go to idle
2820 case TBLOCK_ABORT_END:
2821 CleanupTransaction();
2822 s->blockState = TBLOCK_DEFAULT;
2826 * We are in a live transaction and we got a ROLLBACK command.
2827 * Abort, cleanup, go to idle state.
2829 case TBLOCK_ABORT_PENDING:
2831 CleanupTransaction();
2832 s->blockState = TBLOCK_DEFAULT;
2836 * Here, we failed while trying to PREPARE. Clean up the
2837 * transaction and return to idle state (we do not want to stay in
2840 case TBLOCK_PREPARE:
2842 CleanupTransaction();
2843 s->blockState = TBLOCK_DEFAULT;
2847 * We got an error inside a subtransaction. Abort just the
2848 * subtransaction, and go to the persistent SUBABORT state until
2851 case TBLOCK_SUBINPROGRESS:
2852 AbortSubTransaction();
2853 s->blockState = TBLOCK_SUBABORT;
2857 * If we failed while trying to create a subtransaction, clean up
2858 * the broken subtransaction and abort the parent. The same
2859 * applies if we get a failure while ending a subtransaction.
2861 case TBLOCK_SUBBEGIN:
2862 case TBLOCK_SUBRELEASE:
2863 case TBLOCK_SUBCOMMIT:
2864 case TBLOCK_SUBABORT_PENDING:
2865 case TBLOCK_SUBRESTART:
2866 AbortSubTransaction();
2867 CleanupSubTransaction();
2868 AbortCurrentTransaction();
2872 * Same as above, except the Abort() was already done.
2874 case TBLOCK_SUBABORT_END:
2875 case TBLOCK_SUBABORT_RESTART:
2876 CleanupSubTransaction();
2877 AbortCurrentTransaction();
2883 * PreventTransactionChain
2885 * This routine is to be called by statements that must not run inside
2886 * a transaction block, typically because they have non-rollback-able
2887 * side effects or do internal commits.
2889 * If we have already started a transaction block, issue an error; also issue
2890 * an error if we appear to be running inside a user-defined function (which
2891 * could issue more commands and possibly cause a failure after the statement
2892 * completes). Subtransactions are verboten too.
2894 * isTopLevel: passed down from ProcessUtility to determine whether we are
2895 * inside a function or multi-query querystring. (We will always fail if
2896 * this is false, but it's convenient to centralize the check here instead of
2897 * making callers do it.)
2898 * stmtType: statement type name, for error messages.
2901 PreventTransactionChain(bool isTopLevel, const char *stmtType)
2904 * xact block already started?
2906 if (IsTransactionBlock())
2908 (errcode(ERRCODE_ACTIVE_SQL_TRANSACTION),
2909 /* translator: %s represents an SQL statement name */
2910 errmsg("%s cannot run inside a transaction block",
2916 if (IsSubTransaction())
2918 (errcode(ERRCODE_ACTIVE_SQL_TRANSACTION),
2919 /* translator: %s represents an SQL statement name */
2920 errmsg("%s cannot run inside a subtransaction",
2924 * inside a function call?
2928 (errcode(ERRCODE_ACTIVE_SQL_TRANSACTION),
2929 /* translator: %s represents an SQL statement name */
2930 errmsg("%s cannot be executed from a function or multi-command string",
2933 /* If we got past IsTransactionBlock test, should be in default state */
2934 if (CurrentTransactionState->blockState != TBLOCK_DEFAULT &&
2935 CurrentTransactionState->blockState != TBLOCK_STARTED)
2936 elog(FATAL, "cannot prevent transaction chain");
2941 * These two functions allow for warnings or errors if a command is
2942 * executed outside of a transaction block.
2944 * While top-level transaction control commands (BEGIN/COMMIT/ABORT) and
2945 * SET that have no effect issue warnings, all other no-effect commands
2949 WarnNoTransactionChain(bool isTopLevel, const char *stmtType)
2951 CheckTransactionChain(isTopLevel, false, stmtType);
2955 RequireTransactionChain(bool isTopLevel, const char *stmtType)
2957 CheckTransactionChain(isTopLevel, true, stmtType);
2961 * RequireTransactionChain
2963 * This routine is to be called by statements that must run inside
2964 * a transaction block, because they have no effects that persist past
2965 * transaction end (and so calling them outside a transaction block
2966 * is presumably an error). DECLARE CURSOR is an example.
2968 * If we appear to be running inside a user-defined function, we do not
2969 * issue anything, since the function could issue more commands that make
2970 * use of the current statement's results. Likewise subtransactions.
2971 * Thus this is an inverse for PreventTransactionChain.
2973 * isTopLevel: passed down from ProcessUtility to determine whether we are
2974 * inside a function.
2975 * stmtType: statement type name, for warning or error messages.
2978 CheckTransactionChain(bool isTopLevel, bool throwError, const char *stmtType)
2981 * xact block already started?
2983 if (IsTransactionBlock())
2989 if (IsSubTransaction())
2993 * inside a function call?
2998 ereport(throwError ? ERROR : WARNING,
2999 (errcode(ERRCODE_NO_ACTIVE_SQL_TRANSACTION),
3000 /* translator: %s represents an SQL statement name */
3001 errmsg("%s can only be used in transaction blocks",
3007 * IsInTransactionChain
3009 * This routine is for statements that need to behave differently inside
3010 * a transaction block than when running as single commands. ANALYZE is
3011 * currently the only example.
3013 * isTopLevel: passed down from ProcessUtility to determine whether we are
3014 * inside a function.
3017 IsInTransactionChain(bool isTopLevel)
3020 * Return true on same conditions that would make PreventTransactionChain
3023 if (IsTransactionBlock())
3026 if (IsSubTransaction())
3032 if (CurrentTransactionState->blockState != TBLOCK_DEFAULT &&
3033 CurrentTransactionState->blockState != TBLOCK_STARTED)
3041 * Register or deregister callback functions for start- and end-of-xact
3044 * These functions are intended for use by dynamically loaded modules.
3045 * For built-in modules we generally just hardwire the appropriate calls
3046 * (mainly because it's easier to control the order that way, where needed).
3048 * At transaction end, the callback occurs post-commit or post-abort, so the
3049 * callback functions can only do noncritical cleanup.
3052 RegisterXactCallback(XactCallback callback, void *arg)
3054 XactCallbackItem *item;
3056 item = (XactCallbackItem *)
3057 MemoryContextAlloc(TopMemoryContext, sizeof(XactCallbackItem));
3058 item->callback = callback;
3060 item->next = Xact_callbacks;
3061 Xact_callbacks = item;
3065 UnregisterXactCallback(XactCallback callback, void *arg)
3067 XactCallbackItem *item;
3068 XactCallbackItem *prev;
3071 for (item = Xact_callbacks; item; prev = item, item = item->next)
3073 if (item->callback == callback && item->arg == arg)
3076 prev->next = item->next;
3078 Xact_callbacks = item->next;
3086 CallXactCallbacks(XactEvent event)
3088 XactCallbackItem *item;
3090 for (item = Xact_callbacks; item; item = item->next)
3091 (*item->callback) (event, item->arg);
3096 * Register or deregister callback functions for start- and end-of-subxact
3099 * Pretty much same as above, but for subtransaction events.
3101 * At subtransaction end, the callback occurs post-subcommit or post-subabort,
3102 * so the callback functions can only do noncritical cleanup. At
3103 * subtransaction start, the callback is called when the subtransaction has
3104 * finished initializing.
3107 RegisterSubXactCallback(SubXactCallback callback, void *arg)
3109 SubXactCallbackItem *item;
3111 item = (SubXactCallbackItem *)
3112 MemoryContextAlloc(TopMemoryContext, sizeof(SubXactCallbackItem));
3113 item->callback = callback;
3115 item->next = SubXact_callbacks;
3116 SubXact_callbacks = item;
3120 UnregisterSubXactCallback(SubXactCallback callback, void *arg)
3122 SubXactCallbackItem *item;
3123 SubXactCallbackItem *prev;
3126 for (item = SubXact_callbacks; item; prev = item, item = item->next)
3128 if (item->callback == callback && item->arg == arg)
3131 prev->next = item->next;
3133 SubXact_callbacks = item->next;
3141 CallSubXactCallbacks(SubXactEvent event,
3142 SubTransactionId mySubid,
3143 SubTransactionId parentSubid)
3145 SubXactCallbackItem *item;
3147 for (item = SubXact_callbacks; item; item = item->next)
3148 (*item->callback) (event, mySubid, parentSubid, item->arg);
3152 /* ----------------------------------------------------------------
3153 * transaction block support
3154 * ----------------------------------------------------------------
3158 * BeginTransactionBlock
3159 * This executes a BEGIN command.
3162 BeginTransactionBlock(void)
3164 TransactionState s = CurrentTransactionState;
3166 switch (s->blockState)
3169 * We are not inside a transaction block, so allow one to begin.
3171 case TBLOCK_STARTED:
3172 s->blockState = TBLOCK_BEGIN;
3176 * Already a transaction block in progress.
3178 case TBLOCK_INPROGRESS:
3179 case TBLOCK_SUBINPROGRESS:
3181 case TBLOCK_SUBABORT:
3183 (errcode(ERRCODE_ACTIVE_SQL_TRANSACTION),
3184 errmsg("there is already a transaction in progress")));
3187 /* These cases are invalid. */
3188 case TBLOCK_DEFAULT:
3190 case TBLOCK_SUBBEGIN:
3192 case TBLOCK_SUBRELEASE:
3193 case TBLOCK_SUBCOMMIT:
3194 case TBLOCK_ABORT_END:
3195 case TBLOCK_SUBABORT_END:
3196 case TBLOCK_ABORT_PENDING:
3197 case TBLOCK_SUBABORT_PENDING:
3198 case TBLOCK_SUBRESTART:
3199 case TBLOCK_SUBABORT_RESTART:
3200 case TBLOCK_PREPARE:
3201 elog(FATAL, "BeginTransactionBlock: unexpected state %s",
3202 BlockStateAsString(s->blockState));
3208 * PrepareTransactionBlock
3209 * This executes a PREPARE command.
3211 * Since PREPARE may actually do a ROLLBACK, the result indicates what
3212 * happened: TRUE for PREPARE, FALSE for ROLLBACK.
3214 * Note that we don't actually do anything here except change blockState.
3215 * The real work will be done in the upcoming PrepareTransaction().
3216 * We do it this way because it's not convenient to change memory context,
3217 * resource owner, etc while executing inside a Portal.
3220 PrepareTransactionBlock(char *gid)
3225 /* Set up to commit the current transaction */
3226 result = EndTransactionBlock();
3228 /* If successful, change outer tblock state to PREPARE */
3231 s = CurrentTransactionState;
3233 while (s->parent != NULL)
3236 if (s->blockState == TBLOCK_END)
3238 /* Save GID where PrepareTransaction can find it again */
3239 prepareGID = MemoryContextStrdup(TopTransactionContext, gid);
3241 s->blockState = TBLOCK_PREPARE;
3246 * ignore case where we are not in a transaction;
3247 * EndTransactionBlock already issued a warning.
3249 Assert(s->blockState == TBLOCK_STARTED);
3250 /* Don't send back a PREPARE result tag... */
3259 * EndTransactionBlock
3260 * This executes a COMMIT command.
3262 * Since COMMIT may actually do a ROLLBACK, the result indicates what
3263 * happened: TRUE for COMMIT, FALSE for ROLLBACK.
3265 * Note that we don't actually do anything here except change blockState.
3266 * The real work will be done in the upcoming CommitTransactionCommand().
3267 * We do it this way because it's not convenient to change memory context,
3268 * resource owner, etc while executing inside a Portal.
3271 EndTransactionBlock(void)
3273 TransactionState s = CurrentTransactionState;
3274 bool result = false;
3276 switch (s->blockState)
3279 * We are in a transaction block, so tell CommitTransactionCommand
3282 case TBLOCK_INPROGRESS:
3283 s->blockState = TBLOCK_END;
3288 * We are in a failed transaction block. Tell
3289 * CommitTransactionCommand it's time to exit the block.
3292 s->blockState = TBLOCK_ABORT_END;
3296 * We are in a live subtransaction block. Set up to subcommit all
3297 * open subtransactions and then commit the main transaction.
3299 case TBLOCK_SUBINPROGRESS:
3300 while (s->parent != NULL)
3302 if (s->blockState == TBLOCK_SUBINPROGRESS)
3303 s->blockState = TBLOCK_SUBCOMMIT;
3305 elog(FATAL, "EndTransactionBlock: unexpected state %s",
3306 BlockStateAsString(s->blockState));
3309 if (s->blockState == TBLOCK_INPROGRESS)
3310 s->blockState = TBLOCK_END;
3312 elog(FATAL, "EndTransactionBlock: unexpected state %s",
3313 BlockStateAsString(s->blockState));
3318 * Here we are inside an aborted subtransaction. Treat the COMMIT
3319 * as ROLLBACK: set up to abort everything and exit the main
3322 case TBLOCK_SUBABORT:
3323 while (s->parent != NULL)
3325 if (s->blockState == TBLOCK_SUBINPROGRESS)
3326 s->blockState = TBLOCK_SUBABORT_PENDING;
3327 else if (s->blockState == TBLOCK_SUBABORT)
3328 s->blockState = TBLOCK_SUBABORT_END;
3330 elog(FATAL, "EndTransactionBlock: unexpected state %s",
3331 BlockStateAsString(s->blockState));
3334 if (s->blockState == TBLOCK_INPROGRESS)
3335 s->blockState = TBLOCK_ABORT_PENDING;
3336 else if (s->blockState == TBLOCK_ABORT)
3337 s->blockState = TBLOCK_ABORT_END;
3339 elog(FATAL, "EndTransactionBlock: unexpected state %s",
3340 BlockStateAsString(s->blockState));
3344 * The user issued COMMIT when not inside a transaction. Issue a
3345 * WARNING, staying in TBLOCK_STARTED state. The upcoming call to
3346 * CommitTransactionCommand() will then close the transaction and
3347 * put us back into the default state.
3349 case TBLOCK_STARTED:
3351 (errcode(ERRCODE_NO_ACTIVE_SQL_TRANSACTION),
3352 errmsg("there is no transaction in progress")));
3356 /* These cases are invalid. */
3357 case TBLOCK_DEFAULT:
3359 case TBLOCK_SUBBEGIN:
3361 case TBLOCK_SUBRELEASE:
3362 case TBLOCK_SUBCOMMIT:
3363 case TBLOCK_ABORT_END:
3364 case TBLOCK_SUBABORT_END:
3365 case TBLOCK_ABORT_PENDING:
3366 case TBLOCK_SUBABORT_PENDING:
3367 case TBLOCK_SUBRESTART:
3368 case TBLOCK_SUBABORT_RESTART:
3369 case TBLOCK_PREPARE:
3370 elog(FATAL, "EndTransactionBlock: unexpected state %s",
3371 BlockStateAsString(s->blockState));
3379 * UserAbortTransactionBlock
3380 * This executes a ROLLBACK command.
3382 * As above, we don't actually do anything here except change blockState.
3385 UserAbortTransactionBlock(void)
3387 TransactionState s = CurrentTransactionState;
3389 switch (s->blockState)
3392 * We are inside a transaction block and we got a ROLLBACK command
3393 * from the user, so tell CommitTransactionCommand to abort and
3394 * exit the transaction block.
3396 case TBLOCK_INPROGRESS:
3397 s->blockState = TBLOCK_ABORT_PENDING;
3401 * We are inside a failed transaction block and we got a ROLLBACK
3402 * command from the user. Abort processing is already done, so
3403 * CommitTransactionCommand just has to cleanup and go back to
3407 s->blockState = TBLOCK_ABORT_END;
3411 * We are inside a subtransaction. Mark everything up to top
3412 * level as exitable.
3414 case TBLOCK_SUBINPROGRESS:
3415 case TBLOCK_SUBABORT:
3416 while (s->parent != NULL)
3418 if (s->blockState == TBLOCK_SUBINPROGRESS)
3419 s->blockState = TBLOCK_SUBABORT_PENDING;
3420 else if (s->blockState == TBLOCK_SUBABORT)
3421 s->blockState = TBLOCK_SUBABORT_END;
3423 elog(FATAL, "UserAbortTransactionBlock: unexpected state %s",
3424 BlockStateAsString(s->blockState));
3427 if (s->blockState == TBLOCK_INPROGRESS)
3428 s->blockState = TBLOCK_ABORT_PENDING;
3429 else if (s->blockState == TBLOCK_ABORT)
3430 s->blockState = TBLOCK_ABORT_END;
3432 elog(FATAL, "UserAbortTransactionBlock: unexpected state %s",
3433 BlockStateAsString(s->blockState));
3437 * The user issued ABORT when not inside a transaction. Issue a
3438 * WARNING and go to abort state. The upcoming call to
3439 * CommitTransactionCommand() will then put us back into the
3442 case TBLOCK_STARTED:
3444 (errcode(ERRCODE_NO_ACTIVE_SQL_TRANSACTION),
3445 errmsg("there is no transaction in progress")));
3446 s->blockState = TBLOCK_ABORT_PENDING;
3449 /* These cases are invalid. */
3450 case TBLOCK_DEFAULT:
3452 case TBLOCK_SUBBEGIN:
3454 case TBLOCK_SUBRELEASE:
3455 case TBLOCK_SUBCOMMIT:
3456 case TBLOCK_ABORT_END:
3457 case TBLOCK_SUBABORT_END:
3458 case TBLOCK_ABORT_PENDING:
3459 case TBLOCK_SUBABORT_PENDING:
3460 case TBLOCK_SUBRESTART:
3461 case TBLOCK_SUBABORT_RESTART:
3462 case TBLOCK_PREPARE:
3463 elog(FATAL, "UserAbortTransactionBlock: unexpected state %s",
3464 BlockStateAsString(s->blockState));
3471 * This executes a SAVEPOINT command.
3474 DefineSavepoint(char *name)
3476 TransactionState s = CurrentTransactionState;
3478 switch (s->blockState)
3480 case TBLOCK_INPROGRESS:
3481 case TBLOCK_SUBINPROGRESS:
3482 /* Normal subtransaction start */
3484 s = CurrentTransactionState; /* changed by push */
3487 * Savepoint names, like the TransactionState block itself, live
3488 * in TopTransactionContext.
3491 s->name = MemoryContextStrdup(TopTransactionContext, name);
3494 /* These cases are invalid. */
3495 case TBLOCK_DEFAULT:
3496 case TBLOCK_STARTED:
3498 case TBLOCK_SUBBEGIN:
3500 case TBLOCK_SUBRELEASE:
3501 case TBLOCK_SUBCOMMIT:
3503 case TBLOCK_SUBABORT:
3504 case TBLOCK_ABORT_END:
3505 case TBLOCK_SUBABORT_END:
3506 case TBLOCK_ABORT_PENDING:
3507 case TBLOCK_SUBABORT_PENDING:
3508 case TBLOCK_SUBRESTART:
3509 case TBLOCK_SUBABORT_RESTART:
3510 case TBLOCK_PREPARE:
3511 elog(FATAL, "DefineSavepoint: unexpected state %s",
3512 BlockStateAsString(s->blockState));
3519 * This executes a RELEASE command.
3521 * As above, we don't actually do anything here except change blockState.
3524 ReleaseSavepoint(List *options)
3526 TransactionState s = CurrentTransactionState;
3527 TransactionState target,
3532 switch (s->blockState)
3535 * We can't rollback to a savepoint if there is no savepoint
3538 case TBLOCK_INPROGRESS:
3540 (errcode(ERRCODE_S_E_INVALID_SPECIFICATION),
3541 errmsg("no such savepoint")));
3545 * We are in a non-aborted subtransaction. This is the only valid
3548 case TBLOCK_SUBINPROGRESS:
3551 /* These cases are invalid. */
3552 case TBLOCK_DEFAULT:
3553 case TBLOCK_STARTED:
3555 case TBLOCK_SUBBEGIN:
3557 case TBLOCK_SUBRELEASE:
3558 case TBLOCK_SUBCOMMIT:
3560 case TBLOCK_SUBABORT:
3561 case TBLOCK_ABORT_END:
3562 case TBLOCK_SUBABORT_END:
3563 case TBLOCK_ABORT_PENDING:
3564 case TBLOCK_SUBABORT_PENDING:
3565 case TBLOCK_SUBRESTART:
3566 case TBLOCK_SUBABORT_RESTART:
3567 case TBLOCK_PREPARE:
3568 elog(FATAL, "ReleaseSavepoint: unexpected state %s",
3569 BlockStateAsString(s->blockState));
3573 foreach(cell, options)
3575 DefElem *elem = lfirst(cell);
3577 if (strcmp(elem->defname, "savepoint_name") == 0)
3578 name = strVal(elem->arg);
3581 Assert(PointerIsValid(name));
3583 for (target = s; PointerIsValid(target); target = target->parent)
3585 if (PointerIsValid(target->name) && strcmp(target->name, name) == 0)
3589 if (!PointerIsValid(target))
3591 (errcode(ERRCODE_S_E_INVALID_SPECIFICATION),
3592 errmsg("no such savepoint")));
3594 /* disallow crossing savepoint level boundaries */
3595 if (target->savepointLevel != s->savepointLevel)
3597 (errcode(ERRCODE_S_E_INVALID_SPECIFICATION),
3598 errmsg("no such savepoint")));
3601 * Mark "commit pending" all subtransactions up to the target
3602 * subtransaction. The actual commits will happen when control gets to
3603 * CommitTransactionCommand.
3605 xact = CurrentTransactionState;
3608 Assert(xact->blockState == TBLOCK_SUBINPROGRESS);
3609 xact->blockState = TBLOCK_SUBRELEASE;
3612 xact = xact->parent;
3613 Assert(PointerIsValid(xact));
3618 * RollbackToSavepoint
3619 * This executes a ROLLBACK TO <savepoint> command.
3621 * As above, we don't actually do anything here except change blockState.
3624 RollbackToSavepoint(List *options)
3626 TransactionState s = CurrentTransactionState;
3627 TransactionState target,
3632 switch (s->blockState)
3635 * We can't rollback to a savepoint if there is no savepoint
3638 case TBLOCK_INPROGRESS:
3641 (errcode(ERRCODE_S_E_INVALID_SPECIFICATION),
3642 errmsg("no such savepoint")));
3646 * There is at least one savepoint, so proceed.
3648 case TBLOCK_SUBINPROGRESS:
3649 case TBLOCK_SUBABORT:
3652 /* These cases are invalid. */
3653 case TBLOCK_DEFAULT:
3654 case TBLOCK_STARTED:
3656 case TBLOCK_SUBBEGIN:
3658 case TBLOCK_SUBRELEASE:
3659 case TBLOCK_SUBCOMMIT:
3660 case TBLOCK_ABORT_END:
3661 case TBLOCK_SUBABORT_END:
3662 case TBLOCK_ABORT_PENDING:
3663 case TBLOCK_SUBABORT_PENDING:
3664 case TBLOCK_SUBRESTART:
3665 case TBLOCK_SUBABORT_RESTART:
3666 case TBLOCK_PREPARE:
3667 elog(FATAL, "RollbackToSavepoint: unexpected state %s",
3668 BlockStateAsString(s->blockState));
3672 foreach(cell, options)
3674 DefElem *elem = lfirst(cell);
3676 if (strcmp(elem->defname, "savepoint_name") == 0)
3677 name = strVal(elem->arg);
3680 Assert(PointerIsValid(name));
3682 for (target = s; PointerIsValid(target); target = target->parent)
3684 if (PointerIsValid(target->name) && strcmp(target->name, name) == 0)
3688 if (!PointerIsValid(target))
3690 (errcode(ERRCODE_S_E_INVALID_SPECIFICATION),
3691 errmsg("no such savepoint")));
3693 /* disallow crossing savepoint level boundaries */
3694 if (target->savepointLevel != s->savepointLevel)
3696 (errcode(ERRCODE_S_E_INVALID_SPECIFICATION),
3697 errmsg("no such savepoint")));
3700 * Mark "abort pending" all subtransactions up to the target
3701 * subtransaction. The actual aborts will happen when control gets to
3702 * CommitTransactionCommand.
3704 xact = CurrentTransactionState;
3709 if (xact->blockState == TBLOCK_SUBINPROGRESS)
3710 xact->blockState = TBLOCK_SUBABORT_PENDING;
3711 else if (xact->blockState == TBLOCK_SUBABORT)
3712 xact->blockState = TBLOCK_SUBABORT_END;
3714 elog(FATAL, "RollbackToSavepoint: unexpected state %s",
3715 BlockStateAsString(xact->blockState));
3716 xact = xact->parent;
3717 Assert(PointerIsValid(xact));
3720 /* And mark the target as "restart pending" */
3721 if (xact->blockState == TBLOCK_SUBINPROGRESS)
3722 xact->blockState = TBLOCK_SUBRESTART;
3723 else if (xact->blockState == TBLOCK_SUBABORT)
3724 xact->blockState = TBLOCK_SUBABORT_RESTART;
3726 elog(FATAL, "RollbackToSavepoint: unexpected state %s",
3727 BlockStateAsString(xact->blockState));
3731 * BeginInternalSubTransaction
3732 * This is the same as DefineSavepoint except it allows TBLOCK_STARTED,
3733 * TBLOCK_END, and TBLOCK_PREPARE states, and therefore it can safely be
3734 * used in functions that might be called when not inside a BEGIN block
3735 * or when running deferred triggers at COMMIT/PREPARE time. Also, it
3736 * automatically does CommitTransactionCommand/StartTransactionCommand
3737 * instead of expecting the caller to do it.
3740 BeginInternalSubTransaction(char *name)
3742 TransactionState s = CurrentTransactionState;
3744 switch (s->blockState)
3746 case TBLOCK_STARTED:
3747 case TBLOCK_INPROGRESS:
3749 case TBLOCK_PREPARE:
3750 case TBLOCK_SUBINPROGRESS:
3751 /* Normal subtransaction start */
3753 s = CurrentTransactionState; /* changed by push */
3756 * Savepoint names, like the TransactionState block itself, live
3757 * in TopTransactionContext.
3760 s->name = MemoryContextStrdup(TopTransactionContext, name);
3763 /* These cases are invalid. */
3764 case TBLOCK_DEFAULT:
3766 case TBLOCK_SUBBEGIN:
3767 case TBLOCK_SUBRELEASE:
3768 case TBLOCK_SUBCOMMIT:
3770 case TBLOCK_SUBABORT:
3771 case TBLOCK_ABORT_END:
3772 case TBLOCK_SUBABORT_END:
3773 case TBLOCK_ABORT_PENDING:
3774 case TBLOCK_SUBABORT_PENDING:
3775 case TBLOCK_SUBRESTART:
3776 case TBLOCK_SUBABORT_RESTART:
3777 elog(FATAL, "BeginInternalSubTransaction: unexpected state %s",
3778 BlockStateAsString(s->blockState));
3782 CommitTransactionCommand();
3783 StartTransactionCommand();
3787 * ReleaseCurrentSubTransaction
3789 * RELEASE (ie, commit) the innermost subtransaction, regardless of its
3790 * savepoint name (if any).
3791 * NB: do NOT use CommitTransactionCommand/StartTransactionCommand with this.
3794 ReleaseCurrentSubTransaction(void)
3796 TransactionState s = CurrentTransactionState;
3798 if (s->blockState != TBLOCK_SUBINPROGRESS)
3799 elog(ERROR, "ReleaseCurrentSubTransaction: unexpected state %s",
3800 BlockStateAsString(s->blockState));
3801 Assert(s->state == TRANS_INPROGRESS);
3802 MemoryContextSwitchTo(CurTransactionContext);
3803 CommitSubTransaction();
3804 s = CurrentTransactionState; /* changed by pop */
3805 Assert(s->state == TRANS_INPROGRESS);
3809 * RollbackAndReleaseCurrentSubTransaction
3811 * ROLLBACK and RELEASE (ie, abort) the innermost subtransaction, regardless
3812 * of its savepoint name (if any).
3813 * NB: do NOT use CommitTransactionCommand/StartTransactionCommand with this.
3816 RollbackAndReleaseCurrentSubTransaction(void)
3818 TransactionState s = CurrentTransactionState;
3820 switch (s->blockState)
3822 /* Must be in a subtransaction */
3823 case TBLOCK_SUBINPROGRESS:
3824 case TBLOCK_SUBABORT:
3827 /* These cases are invalid. */
3828 case TBLOCK_DEFAULT:
3829 case TBLOCK_STARTED:
3831 case TBLOCK_SUBBEGIN:
3832 case TBLOCK_INPROGRESS:
3834 case TBLOCK_SUBRELEASE:
3835 case TBLOCK_SUBCOMMIT:
3837 case TBLOCK_ABORT_END:
3838 case TBLOCK_SUBABORT_END:
3839 case TBLOCK_ABORT_PENDING:
3840 case TBLOCK_SUBABORT_PENDING:
3841 case TBLOCK_SUBRESTART:
3842 case TBLOCK_SUBABORT_RESTART:
3843 case TBLOCK_PREPARE:
3844 elog(FATAL, "RollbackAndReleaseCurrentSubTransaction: unexpected state %s",
3845 BlockStateAsString(s->blockState));
3850 * Abort the current subtransaction, if needed.
3852 if (s->blockState == TBLOCK_SUBINPROGRESS)
3853 AbortSubTransaction();
3855 /* And clean it up, too */
3856 CleanupSubTransaction();
3858 s = CurrentTransactionState; /* changed by pop */
3859 AssertState(s->blockState == TBLOCK_SUBINPROGRESS ||
3860 s->blockState == TBLOCK_INPROGRESS ||
3861 s->blockState == TBLOCK_STARTED);
3865 * AbortOutOfAnyTransaction
3867 * This routine is provided for error recovery purposes. It aborts any
3868 * active transaction or transaction block, leaving the system in a known
3872 AbortOutOfAnyTransaction(void)
3874 TransactionState s = CurrentTransactionState;
3877 * Get out of any transaction or nested transaction
3881 switch (s->blockState)
3883 case TBLOCK_DEFAULT:
3884 if (s->state == TRANS_DEFAULT)
3886 /* Not in a transaction, do nothing */
3891 * We can get here after an error during transaction start
3892 * (state will be TRANS_START). Need to clean up the
3893 * incompletely started transaction. First, adjust the
3894 * low-level state to suppress warning message from
3897 if (s->state == TRANS_START)
3898 s->state = TRANS_INPROGRESS;
3900 CleanupTransaction();
3903 case TBLOCK_STARTED:
3905 case TBLOCK_INPROGRESS:
3907 case TBLOCK_ABORT_PENDING:
3908 case TBLOCK_PREPARE:
3909 /* In a transaction, so clean up */
3911 CleanupTransaction();
3912 s->blockState = TBLOCK_DEFAULT;
3915 case TBLOCK_ABORT_END:
3916 /* AbortTransaction already done, still need Cleanup */
3917 CleanupTransaction();
3918 s->blockState = TBLOCK_DEFAULT;
3922 * In a subtransaction, so clean it up and abort parent too
3924 case TBLOCK_SUBBEGIN:
3925 case TBLOCK_SUBINPROGRESS:
3926 case TBLOCK_SUBRELEASE:
3927 case TBLOCK_SUBCOMMIT:
3928 case TBLOCK_SUBABORT_PENDING:
3929 case TBLOCK_SUBRESTART:
3930 AbortSubTransaction();
3931 CleanupSubTransaction();
3932 s = CurrentTransactionState; /* changed by pop */
3935 case TBLOCK_SUBABORT:
3936 case TBLOCK_SUBABORT_END:
3937 case TBLOCK_SUBABORT_RESTART:
3938 /* As above, but AbortSubTransaction already done */
3939 CleanupSubTransaction();
3940 s = CurrentTransactionState; /* changed by pop */
3943 } while (s->blockState != TBLOCK_DEFAULT);
3945 /* Should be out of all subxacts now */
3946 Assert(s->parent == NULL);
3950 * IsTransactionBlock --- are we within a transaction block?
3953 IsTransactionBlock(void)
3955 TransactionState s = CurrentTransactionState;
3957 if (s->blockState == TBLOCK_DEFAULT || s->blockState == TBLOCK_STARTED)
3964 * IsTransactionOrTransactionBlock --- are we within either a transaction
3965 * or a transaction block? (The backend is only really "idle" when this
3968 * This should match up with IsTransactionBlock and IsTransactionState.
3971 IsTransactionOrTransactionBlock(void)
3973 TransactionState s = CurrentTransactionState;
3975 if (s->blockState == TBLOCK_DEFAULT)
3982 * TransactionBlockStatusCode - return status code to send in ReadyForQuery
3985 TransactionBlockStatusCode(void)
3987 TransactionState s = CurrentTransactionState;
3989 switch (s->blockState)
3991 case TBLOCK_DEFAULT:
3992 case TBLOCK_STARTED:
3993 return 'I'; /* idle --- not in transaction */
3995 case TBLOCK_SUBBEGIN:
3996 case TBLOCK_INPROGRESS:
3997 case TBLOCK_SUBINPROGRESS:
3999 case TBLOCK_SUBRELEASE:
4000 case TBLOCK_SUBCOMMIT:
4001 case TBLOCK_PREPARE:
4002 return 'T'; /* in transaction */
4004 case TBLOCK_SUBABORT:
4005 case TBLOCK_ABORT_END:
4006 case TBLOCK_SUBABORT_END:
4007 case TBLOCK_ABORT_PENDING:
4008 case TBLOCK_SUBABORT_PENDING:
4009 case TBLOCK_SUBRESTART:
4010 case TBLOCK_SUBABORT_RESTART:
4011 return 'E'; /* in failed transaction */
4014 /* should never get here */
4015 elog(FATAL, "invalid transaction block state: %s",
4016 BlockStateAsString(s->blockState));
4017 return 0; /* keep compiler quiet */
4024 IsSubTransaction(void)
4026 TransactionState s = CurrentTransactionState;
4028 if (s->nestingLevel >= 2)
4035 * StartSubTransaction
4037 * If you're wondering why this is separate from PushTransaction: it's because
4038 * we can't conveniently do this stuff right inside DefineSavepoint. The
4039 * SAVEPOINT utility command will be executed inside a Portal, and if we
4040 * muck with CurrentMemoryContext or CurrentResourceOwner then exit from
4041 * the Portal will undo those settings. So we make DefineSavepoint just
4042 * push a dummy transaction block, and when control returns to the main
4043 * idle loop, CommitTransactionCommand will be called, and we'll come here
4044 * to finish starting the subtransaction.
4047 StartSubTransaction(void)
4049 TransactionState s = CurrentTransactionState;
4051 if (s->state != TRANS_DEFAULT)
4052 elog(WARNING, "StartSubTransaction while in %s state",
4053 TransStateAsString(s->state));
4055 s->state = TRANS_START;
4058 * Initialize subsystems for new subtransaction
4060 * must initialize resource-management stuff first
4062 AtSubStart_Memory();
4063 AtSubStart_ResourceOwner();
4064 AtSubStart_Notify();
4065 AfterTriggerBeginSubXact();
4067 s->state = TRANS_INPROGRESS;
4070 * Call start-of-subxact callbacks
4072 CallSubXactCallbacks(SUBXACT_EVENT_START_SUB, s->subTransactionId,
4073 s->parent->subTransactionId);
4075 ShowTransactionState("StartSubTransaction");
4079 * CommitSubTransaction
4081 * The caller has to make sure to always reassign CurrentTransactionState
4082 * if it has a local pointer to it after calling this function.
4085 CommitSubTransaction(void)
4087 TransactionState s = CurrentTransactionState;
4089 ShowTransactionState("CommitSubTransaction");
4091 if (s->state != TRANS_INPROGRESS)
4092 elog(WARNING, "CommitSubTransaction while in %s state",
4093 TransStateAsString(s->state));
4095 /* Pre-commit processing goes here */
4097 CallSubXactCallbacks(SUBXACT_EVENT_PRE_COMMIT_SUB, s->subTransactionId,
4098 s->parent->subTransactionId);
4100 /* Do the actual "commit", such as it is */
4101 s->state = TRANS_COMMIT;
4103 /* Must CCI to ensure commands of subtransaction are seen as done */
4104 CommandCounterIncrement();
4107 * Prior to 8.4 we marked subcommit in clog at this point. We now only
4108 * perform that step, if required, as part of the atomic update of the
4109 * whole transaction tree at top level commit or abort.
4112 /* Post-commit cleanup */
4113 if (TransactionIdIsValid(s->transactionId))
4114 AtSubCommit_childXids();
4115 AfterTriggerEndSubXact(true);
4116 AtSubCommit_Portals(s->subTransactionId,
4117 s->parent->subTransactionId,
4118 s->parent->curTransactionOwner);
4119 AtEOSubXact_LargeObject(true, s->subTransactionId,
4120 s->parent->subTransactionId);
4121 AtSubCommit_Notify();
4123 CallSubXactCallbacks(SUBXACT_EVENT_COMMIT_SUB, s->subTransactionId,
4124 s->parent->subTransactionId);
4126 ResourceOwnerRelease(s->curTransactionOwner,
4127 RESOURCE_RELEASE_BEFORE_LOCKS,
4129 AtEOSubXact_RelationCache(true, s->subTransactionId,
4130 s->parent->subTransactionId);
4131 AtEOSubXact_Inval(true);
4135 * The only lock we actually release here is the subtransaction XID lock.
4137 CurrentResourceOwner = s->curTransactionOwner;
4138 if (TransactionIdIsValid(s->transactionId))
4139 XactLockTableDelete(s->transactionId);
4142 * Other locks should get transferred to their parent resource owner.
4144 ResourceOwnerRelease(s->curTransactionOwner,
4145 RESOURCE_RELEASE_LOCKS,
4147 ResourceOwnerRelease(s->curTransactionOwner,
4148 RESOURCE_RELEASE_AFTER_LOCKS,
4151 AtEOXact_GUC(true, s->gucNestLevel);
4152 AtEOSubXact_SPI(true, s->subTransactionId);
4153 AtEOSubXact_on_commit_actions(true, s->subTransactionId,
4154 s->parent->subTransactionId);
4155 AtEOSubXact_Namespace(true, s->subTransactionId,
4156 s->parent->subTransactionId);
4157 AtEOSubXact_Files(true, s->subTransactionId,
4158 s->parent->subTransactionId);
4159 AtEOSubXact_HashTables(true, s->nestingLevel);
4160 AtEOSubXact_PgStat(true, s->nestingLevel);
4161 AtSubCommit_Snapshot(s->nestingLevel);
4164 * We need to restore the upper transaction's read-only state, in case the
4165 * upper is read-write while the child is read-only; GUC will incorrectly
4166 * think it should leave the child state in place.
4168 XactReadOnly = s->prevXactReadOnly;
4170 CurrentResourceOwner = s->parent->curTransactionOwner;
4171 CurTransactionResourceOwner = s->parent->curTransactionOwner;
4172 ResourceOwnerDelete(s->curTransactionOwner);
4173 s->curTransactionOwner = NULL;
4175 AtSubCommit_Memory();
4177 s->state = TRANS_DEFAULT;
4183 * AbortSubTransaction
4186 AbortSubTransaction(void)
4188 TransactionState s = CurrentTransactionState;
4190 /* Prevent cancel/die interrupt while cleaning up */
4193 /* Make sure we have a valid memory context and resource owner */
4194 AtSubAbort_Memory();
4195 AtSubAbort_ResourceOwner();
4198 * Release any LW locks we might be holding as quickly as possible.
4199 * (Regular locks, however, must be held till we finish aborting.)
4200 * Releasing LW locks is critical since we might try to grab them again
4201 * while cleaning up!
4203 * FIXME This may be incorrect --- Are there some locks we should keep?
4204 * Buffer locks, for example? I don't think so but I'm not sure.
4211 /* Reset WAL record construction state */
4212 XLogResetInsertion();
4215 * Also clean up any open wait for lock, since the lock manager will choke
4216 * if we try to wait for another lock before doing this.
4221 * If any timeout events are still active, make sure the timeout interrupt
4222 * is scheduled. This covers possible loss of a timeout interrupt due to
4223 * longjmp'ing out of the SIGINT handler (see notes in handle_sig_alarm).
4224 * We delay this till after LockErrorCleanup so that we don't uselessly
4225 * reschedule lock or deadlock check timeouts.
4227 reschedule_timeouts();
4230 * Re-enable signals, in case we got here by longjmp'ing out of a signal
4231 * handler. We do this fairly early in the sequence so that the timeout
4232 * infrastructure will be functional if needed while aborting.
4234 PG_SETMASK(&UnBlockSig);
4237 * check the current transaction state
4239 ShowTransactionState("AbortSubTransaction");
4241 if (s->state != TRANS_INPROGRESS)
4242 elog(WARNING, "AbortSubTransaction while in %s state",
4243 TransStateAsString(s->state));
4245 s->state = TRANS_ABORT;
4248 * Reset user ID which might have been changed transiently. (See notes in
4249 * AbortTransaction.)
4251 SetUserIdAndSecContext(s->prevUser, s->prevSecContext);
4254 * We can skip all this stuff if the subxact failed before creating a
4257 if (s->curTransactionOwner)
4259 AfterTriggerEndSubXact(false);
4260 AtSubAbort_Portals(s->subTransactionId,
4261 s->parent->subTransactionId,
4262 s->parent->curTransactionOwner);
4263 AtEOSubXact_LargeObject(false, s->subTransactionId,
4264 s->parent->subTransactionId);
4265 AtSubAbort_Notify();
4267 /* Advertise the fact that we aborted in pg_clog. */
4268 (void) RecordTransactionAbort(true);
4270 /* Post-abort cleanup */
4271 if (TransactionIdIsValid(s->transactionId))
4272 AtSubAbort_childXids();
4274 CallSubXactCallbacks(SUBXACT_EVENT_ABORT_SUB, s->subTransactionId,
4275 s->parent->subTransactionId);
4277 ResourceOwnerRelease(s->curTransactionOwner,
4278 RESOURCE_RELEASE_BEFORE_LOCKS,
4280 AtEOSubXact_RelationCache(false, s->subTransactionId,
4281 s->parent->subTransactionId);
4282 AtEOSubXact_Inval(false);
4283 ResourceOwnerRelease(s->curTransactionOwner,
4284 RESOURCE_RELEASE_LOCKS,
4286 ResourceOwnerRelease(s->curTransactionOwner,
4287 RESOURCE_RELEASE_AFTER_LOCKS,
4291 AtEOXact_GUC(false, s->gucNestLevel);
4292 AtEOSubXact_SPI(false, s->subTransactionId);
4293 AtEOSubXact_on_commit_actions(false, s->subTransactionId,
4294 s->parent->subTransactionId);
4295 AtEOSubXact_Namespace(false, s->subTransactionId,
4296 s->parent->subTransactionId);
4297 AtEOSubXact_Files(false, s->subTransactionId,
4298 s->parent->subTransactionId);
4299 AtEOSubXact_HashTables(false, s->nestingLevel);
4300 AtEOSubXact_PgStat(false, s->nestingLevel);
4301 AtSubAbort_Snapshot(s->nestingLevel);
4305 * Restore the upper transaction's read-only state, too. This should be
4306 * redundant with GUC's cleanup but we may as well do it for consistency
4307 * with the commit case.
4309 XactReadOnly = s->prevXactReadOnly;
4311 RESUME_INTERRUPTS();
4315 * CleanupSubTransaction
4317 * The caller has to make sure to always reassign CurrentTransactionState
4318 * if it has a local pointer to it after calling this function.
4321 CleanupSubTransaction(void)
4323 TransactionState s = CurrentTransactionState;
4325 ShowTransactionState("CleanupSubTransaction");
4327 if (s->state != TRANS_ABORT)
4328 elog(WARNING, "CleanupSubTransaction while in %s state",
4329 TransStateAsString(s->state));
4331 AtSubCleanup_Portals(s->subTransactionId);
4333 CurrentResourceOwner = s->parent->curTransactionOwner;
4334 CurTransactionResourceOwner = s->parent->curTransactionOwner;
4335 if (s->curTransactionOwner)
4336 ResourceOwnerDelete(s->curTransactionOwner);
4337 s->curTransactionOwner = NULL;
4339 AtSubCleanup_Memory();
4341 s->state = TRANS_DEFAULT;
4348 * Create transaction state stack entry for a subtransaction
4350 * The caller has to make sure to always reassign CurrentTransactionState
4351 * if it has a local pointer to it after calling this function.
4354 PushTransaction(void)
4356 TransactionState p = CurrentTransactionState;
4360 * We keep subtransaction state nodes in TopTransactionContext.
4362 s = (TransactionState)
4363 MemoryContextAllocZero(TopTransactionContext,
4364 sizeof(TransactionStateData));
4367 * Assign a subtransaction ID, watching out for counter wraparound.
4369 currentSubTransactionId += 1;
4370 if (currentSubTransactionId == InvalidSubTransactionId)
4372 currentSubTransactionId -= 1;
4375 (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
4376 errmsg("cannot have more than 2^32-1 subtransactions in a transaction")));
4380 * We can now stack a minimally valid subtransaction without fear of
4383 s->transactionId = InvalidTransactionId; /* until assigned */
4384 s->subTransactionId = currentSubTransactionId;
4386 s->nestingLevel = p->nestingLevel + 1;
4387 s->gucNestLevel = NewGUCNestLevel();
4388 s->savepointLevel = p->savepointLevel;
4389 s->state = TRANS_DEFAULT;
4390 s->blockState = TBLOCK_SUBBEGIN;
4391 GetUserIdAndSecContext(&s->prevUser, &s->prevSecContext);
4392 s->prevXactReadOnly = XactReadOnly;
4394 CurrentTransactionState = s;
4397 * AbortSubTransaction and CleanupSubTransaction have to be able to cope
4398 * with the subtransaction from here on out; in particular they should not
4399 * assume that it necessarily has a transaction context, resource owner,
4406 * Pop back to parent transaction state
4408 * The caller has to make sure to always reassign CurrentTransactionState
4409 * if it has a local pointer to it after calling this function.
4412 PopTransaction(void)
4414 TransactionState s = CurrentTransactionState;
4416 if (s->state != TRANS_DEFAULT)
4417 elog(WARNING, "PopTransaction while in %s state",
4418 TransStateAsString(s->state));
4420 if (s->parent == NULL)
4421 elog(FATAL, "PopTransaction with no parent");
4423 CurrentTransactionState = s->parent;
4425 /* Let's just make sure CurTransactionContext is good */
4426 CurTransactionContext = s->parent->curTransactionContext;
4427 MemoryContextSwitchTo(CurTransactionContext);
4429 /* Ditto for ResourceOwner links */
4430 CurTransactionResourceOwner = s->parent->curTransactionOwner;
4431 CurrentResourceOwner = s->parent->curTransactionOwner;
4433 /* Free the old child structure */
4440 * ShowTransactionState
4444 ShowTransactionState(const char *str)
4446 /* skip work if message will definitely not be printed */
4447 if (log_min_messages <= DEBUG3 || client_min_messages <= DEBUG3)
4449 elog(DEBUG3, "%s", str);
4450 ShowTransactionStateRec(CurrentTransactionState);
4455 * ShowTransactionStateRec
4456 * Recursive subroutine for ShowTransactionState
4459 ShowTransactionStateRec(TransactionState s)
4463 initStringInfo(&buf);
4465 if (s->nChildXids > 0)
4469 appendStringInfo(&buf, "%u", s->childXids[0]);
4470 for (i = 1; i < s->nChildXids; i++)
4471 appendStringInfo(&buf, " %u", s->childXids[i]);
4475 ShowTransactionStateRec(s->parent);
4477 /* use ereport to suppress computation if msg will not be printed */
4479 (errmsg_internal("name: %s; blockState: %13s; state: %7s, xid/subid/cid: %u/%u/%u%s, nestlvl: %d, children: %s",
4480 PointerIsValid(s->name) ? s->name : "unnamed",
4481 BlockStateAsString(s->blockState),
4482 TransStateAsString(s->state),
4483 (unsigned int) s->transactionId,
4484 (unsigned int) s->subTransactionId,
4485 (unsigned int) currentCommandId,
4486 currentCommandIdUsed ? " (used)" : "",
4487 s->nestingLevel, buf.data)));
4493 * BlockStateAsString
4497 BlockStateAsString(TBlockState blockState)
4501 case TBLOCK_DEFAULT:
4503 case TBLOCK_STARTED:
4507 case TBLOCK_INPROGRESS:
4508 return "INPROGRESS";
4513 case TBLOCK_ABORT_END:
4515 case TBLOCK_ABORT_PENDING:
4516 return "ABORT PEND";
4517 case TBLOCK_PREPARE:
4519 case TBLOCK_SUBBEGIN:
4521 case TBLOCK_SUBINPROGRESS:
4522 return "SUB INPROGRS";
4523 case TBLOCK_SUBRELEASE:
4524 return "SUB RELEASE";
4525 case TBLOCK_SUBCOMMIT:
4526 return "SUB COMMIT";
4527 case TBLOCK_SUBABORT:
4529 case TBLOCK_SUBABORT_END:
4530 return "SUB ABORT END";
4531 case TBLOCK_SUBABORT_PENDING:
4532 return "SUB ABRT PEND";
4533 case TBLOCK_SUBRESTART:
4534 return "SUB RESTART";
4535 case TBLOCK_SUBABORT_RESTART:
4536 return "SUB AB RESTRT";
4538 return "UNRECOGNIZED";
4542 * TransStateAsString
4546 TransStateAsString(TransState state)
4554 case TRANS_INPROGRESS:
4563 return "UNRECOGNIZED";
4567 * xactGetCommittedChildren
4569 * Gets the list of committed children of the current transaction. The return
4570 * value is the number of child transactions. *ptr is set to point to an
4571 * array of TransactionIds. The array is allocated in TopTransactionContext;
4572 * the caller should *not* pfree() it (this is a change from pre-8.4 code!).
4573 * If there are no subxacts, *ptr is set to NULL.
4576 xactGetCommittedChildren(TransactionId **ptr)
4578 TransactionState s = CurrentTransactionState;
4580 if (s->nChildXids == 0)
4583 *ptr = s->childXids;
4585 return s->nChildXids;
4589 * XLOG support routines
4594 * Log the commit record for a plain or twophase transaction commit.
4596 * A 2pc commit will be emitted when twophase_xid is valid, a plain one
4600 XactLogCommitRecord(TimestampTz commit_time,
4601 int nsubxacts, TransactionId *subxacts,
4602 int nrels, RelFileNode *rels,
4603 int nmsgs, SharedInvalidationMessage *msgs,
4604 bool relcacheInval, bool forceSync,
4605 TransactionId twophase_xid)
4607 xl_xact_commit xlrec;
4608 xl_xact_xinfo xl_xinfo;
4609 xl_xact_dbinfo xl_dbinfo;
4610 xl_xact_subxacts xl_subxacts;
4611 xl_xact_relfilenodes xl_relfilenodes;
4612 xl_xact_invals xl_invals;
4613 xl_xact_twophase xl_twophase;
4617 Assert(CritSectionCount > 0);
4621 /* decide between a plain and 2pc commit */
4622 if (!TransactionIdIsValid(twophase_xid))
4623 info = XLOG_XACT_COMMIT;
4625 info = XLOG_XACT_COMMIT_PREPARED;
4627 /* First figure out and collect all the information needed */
4629 xlrec.xact_time = commit_time;
4632 xl_xinfo.xinfo |= XACT_COMPLETION_UPDATE_RELCACHE_FILE;
4633 if (forceSyncCommit)
4634 xl_xinfo.xinfo |= XACT_COMPLETION_FORCE_SYNC_COMMIT;
4637 * Relcache invalidations requires information about the current database
4638 * and so does logical decoding.
4640 if (nmsgs > 0 || XLogLogicalInfoActive())
4642 xl_xinfo.xinfo |= XACT_XINFO_HAS_DBINFO;
4643 xl_dbinfo.dbId = MyDatabaseId;
4644 xl_dbinfo.tsId = MyDatabaseTableSpace;
4649 xl_xinfo.xinfo |= XACT_XINFO_HAS_SUBXACTS;
4650 xl_subxacts.nsubxacts = nsubxacts;
4655 xl_xinfo.xinfo |= XACT_XINFO_HAS_RELFILENODES;
4656 xl_relfilenodes.nrels = nrels;
4661 xl_xinfo.xinfo |= XACT_XINFO_HAS_INVALS;
4662 xl_invals.nmsgs = nmsgs;
4665 if (TransactionIdIsValid(twophase_xid))
4667 xl_xinfo.xinfo |= XACT_XINFO_HAS_TWOPHASE;
4668 xl_twophase.xid = twophase_xid;
4671 if (xl_xinfo.xinfo != 0)
4672 info |= XLOG_XACT_HAS_INFO;
4674 /* Then include all the collected data into the commit record. */
4678 XLogRegisterData((char *) (&xlrec), sizeof(xl_xact_commit));
4680 if (xl_xinfo.xinfo != 0)
4681 XLogRegisterData((char *) (&xl_xinfo.xinfo), sizeof(xl_xinfo.xinfo));
4683 if (xl_xinfo.xinfo & XACT_XINFO_HAS_DBINFO)
4684 XLogRegisterData((char *) (&xl_dbinfo), sizeof(xl_dbinfo));
4686 if (xl_xinfo.xinfo & XACT_XINFO_HAS_SUBXACTS)
4688 XLogRegisterData((char *) (&xl_subxacts),
4689 MinSizeOfXactSubxacts);
4690 XLogRegisterData((char *) subxacts,
4691 nsubxacts * sizeof(TransactionId));
4694 if (xl_xinfo.xinfo & XACT_XINFO_HAS_RELFILENODES)
4696 XLogRegisterData((char *) (&xl_relfilenodes),
4697 MinSizeOfXactRelfilenodes);
4698 XLogRegisterData((char *) rels,
4699 nrels * sizeof(RelFileNode));
4702 if (xl_xinfo.xinfo & XACT_XINFO_HAS_INVALS)
4704 XLogRegisterData((char *) (&xl_invals), MinSizeOfXactInvals);
4705 XLogRegisterData((char *) msgs,
4706 nmsgs * sizeof(SharedInvalidationMessage));
4709 if (xl_xinfo.xinfo & XACT_XINFO_HAS_TWOPHASE)
4710 XLogRegisterData((char *) (&xl_twophase), sizeof(xl_xact_twophase));
4712 return XLogInsert(RM_XACT_ID, info);
4716 * Log the commit record for a plain or twophase transaction abort.
4718 * A 2pc abort will be emitted when twophase_xid is valid, a plain one
4722 XactLogAbortRecord(TimestampTz abort_time,
4723 int nsubxacts, TransactionId *subxacts,
4724 int nrels, RelFileNode *rels,
4725 TransactionId twophase_xid)
4727 xl_xact_abort xlrec;
4728 xl_xact_xinfo xl_xinfo;
4729 xl_xact_subxacts xl_subxacts;
4730 xl_xact_relfilenodes xl_relfilenodes;
4731 xl_xact_twophase xl_twophase;
4735 Assert(CritSectionCount > 0);
4739 /* decide between a plain and 2pc abort */
4740 if (!TransactionIdIsValid(twophase_xid))
4741 info = XLOG_XACT_ABORT;
4743 info = XLOG_XACT_ABORT_PREPARED;
4746 /* First figure out and collect all the information needed */
4748 xlrec.xact_time = abort_time;
4752 xl_xinfo.xinfo |= XACT_XINFO_HAS_SUBXACTS;
4753 xl_subxacts.nsubxacts = nsubxacts;
4758 xl_xinfo.xinfo |= XACT_XINFO_HAS_RELFILENODES;
4759 xl_relfilenodes.nrels = nrels;
4762 if (TransactionIdIsValid(twophase_xid))
4764 xl_xinfo.xinfo |= XACT_XINFO_HAS_TWOPHASE;
4765 xl_twophase.xid = twophase_xid;
4768 if (xl_xinfo.xinfo != 0)
4769 info |= XLOG_XACT_HAS_INFO;
4771 /* Then include all the collected data into the abort record. */
4775 XLogRegisterData((char *) (&xlrec), MinSizeOfXactAbort);
4777 if (xl_xinfo.xinfo != 0)
4778 XLogRegisterData((char *) (&xl_xinfo), sizeof(xl_xinfo));
4780 if (xl_xinfo.xinfo & XACT_XINFO_HAS_SUBXACTS)
4782 XLogRegisterData((char *) (&xl_subxacts),
4783 MinSizeOfXactSubxacts);
4784 XLogRegisterData((char *) subxacts,
4785 nsubxacts * sizeof(TransactionId));
4788 if (xl_xinfo.xinfo & XACT_XINFO_HAS_RELFILENODES)
4790 XLogRegisterData((char *) (&xl_relfilenodes),
4791 MinSizeOfXactRelfilenodes);
4792 XLogRegisterData((char *) rels,
4793 nrels * sizeof(RelFileNode));
4796 if (xl_xinfo.xinfo & XACT_XINFO_HAS_TWOPHASE)
4797 XLogRegisterData((char *) (&xl_twophase), sizeof(xl_xact_twophase));
4799 return XLogInsert(RM_XACT_ID, info);
4803 * Before 9.0 this was a fairly short function, but now it performs many
4804 * actions for which the order of execution is critical.
4807 xact_redo_commit(xl_xact_parsed_commit *parsed,
4811 TransactionId max_xid;
4814 max_xid = TransactionIdLatest(xid, parsed->nsubxacts, parsed->subxacts);
4817 * Make sure nextXid is beyond any XID mentioned in the record.
4819 * We don't expect anyone else to modify nextXid, hence we don't need to
4820 * hold a lock while checking this. We still acquire the lock to modify
4823 if (TransactionIdFollowsOrEquals(max_xid,
4824 ShmemVariableCache->nextXid))
4826 LWLockAcquire(XidGenLock, LW_EXCLUSIVE);
4827 ShmemVariableCache->nextXid = max_xid;
4828 TransactionIdAdvance(ShmemVariableCache->nextXid);
4829 LWLockRelease(XidGenLock);
4832 /* Set the transaction commit timestamp and metadata */
4833 TransactionTreeSetCommitTsData(xid, parsed->nsubxacts, parsed->subxacts,
4834 parsed->xact_time, InvalidCommitTsNodeId,
4837 if (standbyState == STANDBY_DISABLED)
4840 * Mark the transaction committed in pg_clog.
4842 TransactionIdCommitTree(xid, parsed->nsubxacts, parsed->subxacts);
4847 * If a transaction completion record arrives that has as-yet
4848 * unobserved subtransactions then this will not have been fully
4849 * handled by the call to RecordKnownAssignedTransactionIds() in the
4850 * main recovery loop in xlog.c. So we need to do bookkeeping again to
4851 * cover that case. This is confusing and it is easy to think this
4852 * call is irrelevant, which has happened three times in development
4853 * already. Leave it in.
4855 RecordKnownAssignedTransactionIds(max_xid);
4858 * Mark the transaction committed in pg_clog. We use async commit
4859 * protocol during recovery to provide information on database
4860 * consistency for when users try to set hint bits. It is important
4861 * that we do not set hint bits until the minRecoveryPoint is past
4862 * this commit record. This ensures that if we crash we don't see hint
4863 * bits set on changes made by transactions that haven't yet
4864 * recovered. It's unlikely but it's good to be safe.
4866 TransactionIdAsyncCommitTree(
4867 xid, parsed->nsubxacts, parsed->subxacts, lsn);
4870 * We must mark clog before we update the ProcArray.
4872 ExpireTreeKnownAssignedTransactionIds(
4873 xid, parsed->nsubxacts, parsed->subxacts, max_xid);
4876 * Send any cache invalidations attached to the commit. We must
4877 * maintain the same order of invalidation then release locks as
4878 * occurs in CommitTransaction().
4880 ProcessCommittedInvalidationMessages(
4881 parsed->msgs, parsed->nmsgs,
4882 XactCompletionRelcacheInitFileInval(parsed->xinfo),
4883 parsed->dbId, parsed->tsId);
4886 * Release locks, if any. We do this for both two phase and normal one
4887 * phase transactions. In effect we are ignoring the prepare phase and
4888 * just going straight to lock release. At commit we release all locks
4889 * via their top-level xid only, so no need to provide subxact list,
4890 * which will save time when replaying commits.
4892 StandbyReleaseLockTree(xid, 0, NULL);
4895 /* Make sure files supposed to be dropped are dropped */
4896 if (parsed->nrels > 0)
4899 * First update minimum recovery point to cover this WAL record. Once
4900 * a relation is deleted, there's no going back. The buffer manager
4901 * enforces the WAL-first rule for normal updates to relation files,
4902 * so that the minimum recovery point is always updated before the
4903 * corresponding change in the data file is flushed to disk, but we
4904 * have to do the same here since we're bypassing the buffer manager.
4906 * Doing this before deleting the files means that if a deletion fails
4907 * for some reason, you cannot start up the system even after restart,
4908 * until you fix the underlying situation so that the deletion will
4909 * succeed. Alternatively, we could update the minimum recovery point
4910 * after deletion, but that would leave a small window where the
4911 * WAL-first rule would be violated.
4915 for (i = 0; i < parsed->nrels; i++)
4917 SMgrRelation srel = smgropen(parsed->xnodes[i], InvalidBackendId);
4920 for (fork = 0; fork <= MAX_FORKNUM; fork++)
4921 XLogDropRelation(parsed->xnodes[i], fork);
4922 smgrdounlink(srel, true);
4928 * We issue an XLogFlush() for the same reason we emit ForceSyncCommit()
4929 * in normal operation. For example, in CREATE DATABASE, we copy all files
4930 * from the template database, and then commit the transaction. If we
4931 * crash after all the files have been copied but before the commit, you
4932 * have files in the data directory without an entry in pg_database. To
4933 * minimize the window for that, we use ForceSyncCommit() to rush the
4934 * commit record to disk as quick as possible. We have the same window
4935 * during recovery, and forcing an XLogFlush() (which updates
4936 * minRecoveryPoint during recovery) helps to reduce that problem window,
4937 * for any user that requested ForceSyncCommit().
4939 if (XactCompletionForceSyncCommit(parsed->xinfo))
4945 * Be careful with the order of execution, as with xact_redo_commit().
4946 * The two functions are similar but differ in key places.
4948 * Note also that an abort can be for a subtransaction and its children,
4949 * not just for a top level abort. That means we have to consider
4950 * topxid != xid, whereas in commit we would find topxid == xid always
4951 * because subtransaction commit is never WAL logged.
4954 xact_redo_abort(xl_xact_parsed_abort *parsed, TransactionId xid)
4957 TransactionId max_xid;
4960 * Make sure nextXid is beyond any XID mentioned in the record.
4962 * We don't expect anyone else to modify nextXid, hence we don't need to
4963 * hold a lock while checking this. We still acquire the lock to modify
4966 max_xid = TransactionIdLatest(xid,
4970 if (TransactionIdFollowsOrEquals(max_xid,
4971 ShmemVariableCache->nextXid))
4973 LWLockAcquire(XidGenLock, LW_EXCLUSIVE);
4974 ShmemVariableCache->nextXid = max_xid;
4975 TransactionIdAdvance(ShmemVariableCache->nextXid);
4976 LWLockRelease(XidGenLock);
4979 if (standbyState == STANDBY_DISABLED)
4981 /* Mark the transaction aborted in pg_clog, no need for async stuff */
4982 TransactionIdAbortTree(xid, parsed->nsubxacts, parsed->subxacts);
4987 * If a transaction completion record arrives that has as-yet
4988 * unobserved subtransactions then this will not have been fully
4989 * handled by the call to RecordKnownAssignedTransactionIds() in the
4990 * main recovery loop in xlog.c. So we need to do bookkeeping again to
4991 * cover that case. This is confusing and it is easy to think this
4992 * call is irrelevant, which has happened three times in development
4993 * already. Leave it in.
4995 RecordKnownAssignedTransactionIds(max_xid);
4997 /* Mark the transaction aborted in pg_clog, no need for async stuff */
4998 TransactionIdAbortTree(xid, parsed->nsubxacts, parsed->subxacts);
5001 * We must update the ProcArray after we have marked clog.
5003 ExpireTreeKnownAssignedTransactionIds(
5004 xid, parsed->nsubxacts, parsed->subxacts, max_xid);
5007 * There are no flat files that need updating, nor invalidation
5008 * messages to send or undo.
5012 * Release locks, if any. There are no invalidations to send.
5014 StandbyReleaseLockTree(xid, parsed->nsubxacts, parsed->subxacts);
5017 /* Make sure files supposed to be dropped are dropped */
5018 for (i = 0; i < parsed->nrels; i++)
5020 SMgrRelation srel = smgropen(parsed->xnodes[i], InvalidBackendId);
5023 for (fork = 0; fork <= MAX_FORKNUM; fork++)
5024 XLogDropRelation(parsed->xnodes[i], fork);
5025 smgrdounlink(srel, true);
5031 xact_redo(XLogReaderState *record)
5033 uint8 info = XLogRecGetInfo(record) & XLOG_XACT_OPMASK;
5035 /* Backup blocks are not used in xact records */
5036 Assert(!XLogRecHasAnyBlockRefs(record));
5038 if (info == XLOG_XACT_COMMIT || info == XLOG_XACT_COMMIT_PREPARED)
5040 xl_xact_commit *xlrec = (xl_xact_commit *) XLogRecGetData(record);
5041 xl_xact_parsed_commit parsed;
5043 ParseCommitRecord(XLogRecGetInfo(record), xlrec,
5046 if (info == XLOG_XACT_COMMIT)
5048 Assert(!TransactionIdIsValid(parsed.twophase_xid));
5049 xact_redo_commit(&parsed, XLogRecGetXid(record),
5054 Assert(TransactionIdIsValid(parsed.twophase_xid));
5055 xact_redo_commit(&parsed, parsed.twophase_xid,
5057 RemoveTwoPhaseFile(parsed.twophase_xid, false);
5060 else if (info == XLOG_XACT_ABORT || info == XLOG_XACT_ABORT_PREPARED)
5062 xl_xact_abort *xlrec = (xl_xact_abort *) XLogRecGetData(record);
5063 xl_xact_parsed_abort parsed;
5065 ParseAbortRecord(XLogRecGetInfo(record), xlrec,
5068 if (info == XLOG_XACT_ABORT)
5070 Assert(!TransactionIdIsValid(parsed.twophase_xid));
5071 xact_redo_abort(&parsed, XLogRecGetXid(record));
5075 Assert(TransactionIdIsValid(parsed.twophase_xid));
5076 xact_redo_abort(&parsed, parsed.twophase_xid);
5077 RemoveTwoPhaseFile(parsed.twophase_xid, false);
5080 else if (info == XLOG_XACT_PREPARE)
5082 /* the record contents are exactly the 2PC file */
5083 RecreateTwoPhaseFile(XLogRecGetXid(record),
5084 XLogRecGetData(record), XLogRecGetDataLen(record));
5086 else if (info == XLOG_XACT_ASSIGNMENT)
5088 xl_xact_assignment *xlrec = (xl_xact_assignment *) XLogRecGetData(record);
5090 if (standbyState >= STANDBY_INITIALIZED)
5091 ProcArrayApplyXidAssignment(xlrec->xtop,
5092 xlrec->nsubxacts, xlrec->xsub);
5095 elog(PANIC, "xact_redo: unknown op code %u", info);