1 /*-------------------------------------------------------------------------
4 * top level transaction system support routines
6 * See src/backend/access/transam/README for more information.
8 * Portions Copyright (c) 1996-2013, 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/multixact.h"
24 #include "access/subtrans.h"
25 #include "access/transam.h"
26 #include "access/twophase.h"
27 #include "access/xact.h"
28 #include "access/xlogutils.h"
29 #include "catalog/catalog.h"
30 #include "catalog/namespace.h"
31 #include "catalog/storage.h"
32 #include "commands/async.h"
33 #include "commands/tablecmds.h"
34 #include "commands/trigger.h"
35 #include "executor/spi.h"
36 #include "libpq/be-fsstubs.h"
37 #include "miscadmin.h"
39 #include "replication/walsender.h"
40 #include "replication/syncrep.h"
41 #include "storage/fd.h"
42 #include "storage/lmgr.h"
43 #include "storage/predicate.h"
44 #include "storage/proc.h"
45 #include "storage/procarray.h"
46 #include "storage/sinvaladt.h"
47 #include "storage/smgr.h"
48 #include "utils/catcache.h"
49 #include "utils/combocid.h"
50 #include "utils/guc.h"
51 #include "utils/inval.h"
52 #include "utils/memutils.h"
53 #include "utils/relmapper.h"
54 #include "utils/snapmgr.h"
55 #include "utils/timestamp.h"
60 * User-tweakable parameters
62 int DefaultXactIsoLevel = XACT_READ_COMMITTED;
65 bool DefaultXactReadOnly = false;
68 bool DefaultXactDeferrable = false;
71 int synchronous_commit = SYNCHRONOUS_COMMIT_ON;
74 * MyXactAccessedTempRel is set when a temporary relation is accessed.
75 * We don't allow PREPARE TRANSACTION in that case. (This is global
76 * so that it can be set from heapam.c.)
78 bool MyXactAccessedTempRel = false;
82 * transaction states - transaction state from server perspective
84 typedef enum TransState
86 TRANS_DEFAULT, /* idle */
87 TRANS_START, /* transaction starting */
88 TRANS_INPROGRESS, /* inside a valid transaction */
89 TRANS_COMMIT, /* commit in progress */
90 TRANS_ABORT, /* abort in progress */
91 TRANS_PREPARE /* prepare in progress */
95 * transaction block states - transaction state of client queries
97 * Note: the subtransaction states are used only for non-topmost
98 * transactions; the others appear only in the topmost transaction.
100 typedef enum TBlockState
102 /* not-in-transaction-block states */
103 TBLOCK_DEFAULT, /* idle */
104 TBLOCK_STARTED, /* running single-query transaction */
106 /* transaction block states */
107 TBLOCK_BEGIN, /* starting transaction block */
108 TBLOCK_INPROGRESS, /* live transaction */
109 TBLOCK_END, /* COMMIT received */
110 TBLOCK_ABORT, /* failed xact, awaiting ROLLBACK */
111 TBLOCK_ABORT_END, /* failed xact, ROLLBACK received */
112 TBLOCK_ABORT_PENDING, /* live xact, ROLLBACK received */
113 TBLOCK_PREPARE, /* live xact, PREPARE received */
115 /* subtransaction states */
116 TBLOCK_SUBBEGIN, /* starting a subtransaction */
117 TBLOCK_SUBINPROGRESS, /* live subtransaction */
118 TBLOCK_SUBRELEASE, /* RELEASE received */
119 TBLOCK_SUBCOMMIT, /* COMMIT received while TBLOCK_SUBINPROGRESS */
120 TBLOCK_SUBABORT, /* failed subxact, awaiting ROLLBACK */
121 TBLOCK_SUBABORT_END, /* failed subxact, ROLLBACK received */
122 TBLOCK_SUBABORT_PENDING, /* live subxact, ROLLBACK received */
123 TBLOCK_SUBRESTART, /* live subxact, ROLLBACK TO received */
124 TBLOCK_SUBABORT_RESTART /* failed subxact, ROLLBACK TO received */
128 * transaction state structure
130 typedef struct TransactionStateData
132 TransactionId transactionId; /* my XID, or Invalid if none */
133 SubTransactionId subTransactionId; /* my subxact ID */
134 char *name; /* savepoint name, if any */
135 int savepointLevel; /* savepoint level */
136 TransState state; /* low-level state */
137 TBlockState blockState; /* high-level state */
138 int nestingLevel; /* transaction nesting depth */
139 int gucNestLevel; /* GUC context nesting depth */
140 MemoryContext curTransactionContext; /* my xact-lifetime context */
141 ResourceOwner curTransactionOwner; /* my query resources */
142 TransactionId *childXids; /* subcommitted child XIDs, in XID order */
143 int nChildXids; /* # of subcommitted child XIDs */
144 int maxChildXids; /* allocated size of childXids[] */
145 Oid prevUser; /* previous CurrentUserId setting */
146 int prevSecContext; /* previous SecurityRestrictionContext */
147 bool prevXactReadOnly; /* entry-time xact r/o state */
148 bool startedInRecovery; /* did we start in recovery? */
149 struct TransactionStateData *parent; /* back link to parent */
150 } TransactionStateData;
152 typedef TransactionStateData *TransactionState;
155 * CurrentTransactionState always points to the current transaction state
156 * block. It will point to TopTransactionStateData when not in a
157 * transaction at all, or when in a top-level transaction.
159 static TransactionStateData TopTransactionStateData = {
160 0, /* transaction id */
161 0, /* subtransaction id */
162 NULL, /* savepoint name */
163 0, /* savepoint level */
164 TRANS_DEFAULT, /* transaction state */
165 TBLOCK_DEFAULT, /* transaction block state from the client
167 0, /* transaction nesting depth */
168 0, /* GUC context nesting depth */
169 NULL, /* cur transaction context */
170 NULL, /* cur transaction resource owner */
171 NULL, /* subcommitted child Xids */
172 0, /* # of subcommitted child Xids */
173 0, /* allocated size of childXids[] */
174 InvalidOid, /* previous CurrentUserId setting */
175 0, /* previous SecurityRestrictionContext */
176 false, /* entry-time xact r/o state */
177 false, /* startedInRecovery */
178 NULL /* link to parent state block */
182 * unreportedXids holds XIDs of all subtransactions that have not yet been
183 * reported in a XLOG_XACT_ASSIGNMENT record.
185 static int nUnreportedXids;
186 static TransactionId unreportedXids[PGPROC_MAX_CACHED_SUBXIDS];
188 static TransactionState CurrentTransactionState = &TopTransactionStateData;
191 * The subtransaction ID and command ID assignment counters are global
192 * to a whole transaction, so we do not keep them in the state stack.
194 static SubTransactionId currentSubTransactionId;
195 static CommandId currentCommandId;
196 static bool currentCommandIdUsed;
199 * xactStartTimestamp is the value of transaction_timestamp().
200 * stmtStartTimestamp is the value of statement_timestamp().
201 * xactStopTimestamp is the time at which we log a commit or abort WAL record.
202 * These do not change as we enter and exit subtransactions, so we don't
203 * keep them inside the TransactionState stack.
205 static TimestampTz xactStartTimestamp;
206 static TimestampTz stmtStartTimestamp;
207 static TimestampTz xactStopTimestamp;
210 * GID to be used for preparing the current transaction. This is also
211 * global to a whole transaction, so we don't keep it in the state stack.
213 static char *prepareGID;
216 * Some commands want to force synchronous commit.
218 static bool forceSyncCommit = false;
221 * Private context for transaction-abort work --- we reserve space for this
222 * at startup to ensure that AbortTransaction and AbortSubTransaction can work
223 * when we've run out of memory.
225 static MemoryContext TransactionAbortContext = NULL;
228 * List of add-on start- and end-of-xact callbacks
230 typedef struct XactCallbackItem
232 struct XactCallbackItem *next;
233 XactCallback callback;
237 static XactCallbackItem *Xact_callbacks = NULL;
240 * List of add-on start- and end-of-subxact callbacks
242 typedef struct SubXactCallbackItem
244 struct SubXactCallbackItem *next;
245 SubXactCallback callback;
247 } SubXactCallbackItem;
249 static SubXactCallbackItem *SubXact_callbacks = NULL;
252 /* local function prototypes */
253 static void AssignTransactionId(TransactionState s);
254 static void AbortTransaction(void);
255 static void AtAbort_Memory(void);
256 static void AtCleanup_Memory(void);
257 static void AtAbort_ResourceOwner(void);
258 static void AtCCI_LocalCache(void);
259 static void AtCommit_Memory(void);
260 static void AtStart_Cache(void);
261 static void AtStart_Memory(void);
262 static void AtStart_ResourceOwner(void);
263 static void CallXactCallbacks(XactEvent event);
264 static void CallSubXactCallbacks(SubXactEvent event,
265 SubTransactionId mySubid,
266 SubTransactionId parentSubid);
267 static void CleanupTransaction(void);
268 static void CommitTransaction(void);
269 static TransactionId RecordTransactionAbort(bool isSubXact);
270 static void StartTransaction(void);
272 static void StartSubTransaction(void);
273 static void CommitSubTransaction(void);
274 static void AbortSubTransaction(void);
275 static void CleanupSubTransaction(void);
276 static void PushTransaction(void);
277 static void PopTransaction(void);
279 static void AtSubAbort_Memory(void);
280 static void AtSubCleanup_Memory(void);
281 static void AtSubAbort_ResourceOwner(void);
282 static void AtSubCommit_Memory(void);
283 static void AtSubStart_Memory(void);
284 static void AtSubStart_ResourceOwner(void);
286 static void ShowTransactionState(const char *str);
287 static void ShowTransactionStateRec(TransactionState state);
288 static const char *BlockStateAsString(TBlockState blockState);
289 static const char *TransStateAsString(TransState state);
292 /* ----------------------------------------------------------------
293 * transaction state accessors
294 * ----------------------------------------------------------------
300 * This returns true if we are inside a valid transaction; that is,
301 * it is safe to initiate database access, take heavyweight locks, etc.
304 IsTransactionState(void)
306 TransactionState s = CurrentTransactionState;
309 * TRANS_DEFAULT and TRANS_ABORT are obviously unsafe states. However, we
310 * also reject the startup/shutdown states TRANS_START, TRANS_COMMIT,
311 * TRANS_PREPARE since it might be too soon or too late within those
312 * transition states to do anything interesting. Hence, the only "valid"
313 * state is TRANS_INPROGRESS.
315 return (s->state == TRANS_INPROGRESS);
319 * IsAbortedTransactionBlockState
321 * This returns true if we are within an aborted transaction block.
324 IsAbortedTransactionBlockState(void)
326 TransactionState s = CurrentTransactionState;
328 if (s->blockState == TBLOCK_ABORT ||
329 s->blockState == TBLOCK_SUBABORT)
337 * GetTopTransactionId
339 * This will return the XID of the main transaction, assigning one if
340 * it's not yet set. Be careful to call this only inside a valid xact.
343 GetTopTransactionId(void)
345 if (!TransactionIdIsValid(TopTransactionStateData.transactionId))
346 AssignTransactionId(&TopTransactionStateData);
347 return TopTransactionStateData.transactionId;
351 * GetTopTransactionIdIfAny
353 * This will return the XID of the main transaction, if one is assigned.
354 * It will return InvalidTransactionId if we are not currently inside a
355 * transaction, or inside a transaction that hasn't yet been assigned an XID.
358 GetTopTransactionIdIfAny(void)
360 return TopTransactionStateData.transactionId;
364 * GetCurrentTransactionId
366 * This will return the XID of the current transaction (main or sub
367 * transaction), assigning one if it's not yet set. Be careful to call this
368 * only inside a valid xact.
371 GetCurrentTransactionId(void)
373 TransactionState s = CurrentTransactionState;
375 if (!TransactionIdIsValid(s->transactionId))
376 AssignTransactionId(s);
377 return s->transactionId;
381 * GetCurrentTransactionIdIfAny
383 * This will return the XID of the current sub xact, if one is assigned.
384 * It will return InvalidTransactionId if we are not currently inside a
385 * transaction, or inside a transaction that hasn't been assigned an XID yet.
388 GetCurrentTransactionIdIfAny(void)
390 return CurrentTransactionState->transactionId;
394 * GetStableLatestTransactionId
396 * Get the transaction's XID if it has one, else read the next-to-be-assigned
397 * XID. Once we have a value, return that same value for the remainder of the
398 * current transaction. This is meant to provide the reference point for the
399 * age(xid) function, but might be useful for other maintenance tasks as well.
402 GetStableLatestTransactionId(void)
404 static LocalTransactionId lxid = InvalidLocalTransactionId;
405 static TransactionId stablexid = InvalidTransactionId;
407 if (lxid != MyProc->lxid)
410 stablexid = GetTopTransactionIdIfAny();
411 if (!TransactionIdIsValid(stablexid))
412 stablexid = ReadNewTransactionId();
415 Assert(TransactionIdIsValid(stablexid));
421 * AssignTransactionId
423 * Assigns a new permanent XID to the given TransactionState.
424 * We do not assign XIDs to transactions until/unless this is called.
425 * Also, any parent TransactionStates that don't yet have XIDs are assigned
426 * one; this maintains the invariant that a child transaction has an XID
427 * following its parent's.
430 AssignTransactionId(TransactionState s)
432 bool isSubXact = (s->parent != NULL);
433 ResourceOwner currentOwner;
435 /* Assert that caller didn't screw up */
436 Assert(!TransactionIdIsValid(s->transactionId));
437 Assert(s->state == TRANS_INPROGRESS);
440 * Ensure parent(s) have XIDs, so that a child always has an XID later
441 * than its parent. Musn't recurse here, or we might get a stack overflow
442 * if we're at the bottom of a huge stack of subtransactions none of which
445 if (isSubXact && !TransactionIdIsValid(s->parent->transactionId))
447 TransactionState p = s->parent;
448 TransactionState *parents;
449 size_t parentOffset = 0;
451 parents = palloc(sizeof(TransactionState) * s->nestingLevel);
452 while (p != NULL && !TransactionIdIsValid(p->transactionId))
454 parents[parentOffset++] = p;
459 * This is technically a recursive call, but the recursion will never
460 * be more than one layer deep.
462 while (parentOffset != 0)
463 AssignTransactionId(parents[--parentOffset]);
469 * Generate a new Xid and record it in PG_PROC and pg_subtrans.
471 * NB: we must make the subtrans entry BEFORE the Xid appears anywhere in
472 * shared storage other than PG_PROC; because if there's no room for it in
473 * PG_PROC, the subtrans entry is needed to ensure that other backends see
474 * the Xid as "running". See GetNewTransactionId.
476 s->transactionId = GetNewTransactionId(isSubXact);
479 SubTransSetParent(s->transactionId, s->parent->transactionId, false);
482 * If it's a top-level transaction, the predicate locking system needs to
483 * be told about it too.
486 RegisterPredicateLockingXid(s->transactionId);
489 * Acquire lock on the transaction XID. (We assume this cannot block.) We
490 * have to ensure that the lock is assigned to the transaction's own
493 currentOwner = CurrentResourceOwner;
496 CurrentResourceOwner = s->curTransactionOwner;
497 XactLockTableInsert(s->transactionId);
501 /* Ensure CurrentResourceOwner is restored on error */
502 CurrentResourceOwner = currentOwner;
506 CurrentResourceOwner = currentOwner;
509 * Every PGPROC_MAX_CACHED_SUBXIDS assigned transaction ids within each
510 * top-level transaction we issue a WAL record for the assignment. We
511 * include the top-level xid and all the subxids that have not yet been
512 * reported using XLOG_XACT_ASSIGNMENT records.
514 * This is required to limit the amount of shared memory required in a hot
515 * standby server to keep track of in-progress XIDs. See notes for
516 * RecordKnownAssignedTransactionIds().
518 * We don't keep track of the immediate parent of each subxid, only the
519 * top-level transaction that each subxact belongs to. This is correct in
520 * recovery only because aborted subtransactions are separately WAL
523 if (isSubXact && XLogStandbyInfoActive())
525 unreportedXids[nUnreportedXids] = s->transactionId;
529 * ensure this test matches similar one in
530 * RecoverPreparedTransactions()
532 if (nUnreportedXids >= PGPROC_MAX_CACHED_SUBXIDS)
534 XLogRecData rdata[2];
535 xl_xact_assignment xlrec;
538 * xtop is always set by now because we recurse up transaction
539 * stack to the highest unassigned xid and then come back down
541 xlrec.xtop = GetTopTransactionId();
542 Assert(TransactionIdIsValid(xlrec.xtop));
543 xlrec.nsubxacts = nUnreportedXids;
545 rdata[0].data = (char *) &xlrec;
546 rdata[0].len = MinSizeOfXactAssignment;
547 rdata[0].buffer = InvalidBuffer;
548 rdata[0].next = &rdata[1];
550 rdata[1].data = (char *) unreportedXids;
551 rdata[1].len = PGPROC_MAX_CACHED_SUBXIDS * sizeof(TransactionId);
552 rdata[1].buffer = InvalidBuffer;
553 rdata[1].next = NULL;
555 (void) XLogInsert(RM_XACT_ID, XLOG_XACT_ASSIGNMENT, rdata);
563 * GetCurrentSubTransactionId
566 GetCurrentSubTransactionId(void)
568 TransactionState s = CurrentTransactionState;
570 return s->subTransactionId;
574 * SubTransactionIsActive
576 * Test if the specified subxact ID is still active. Note caller is
577 * responsible for checking whether this ID is relevant to the current xact.
580 SubTransactionIsActive(SubTransactionId subxid)
584 for (s = CurrentTransactionState; s != NULL; s = s->parent)
586 if (s->state == TRANS_ABORT)
588 if (s->subTransactionId == subxid)
596 * GetCurrentCommandId
598 * "used" must be TRUE if the caller intends to use the command ID to mark
599 * inserted/updated/deleted tuples. FALSE means the ID is being fetched
600 * for read-only purposes (ie, as a snapshot validity cutoff). See
601 * CommandCounterIncrement() for discussion.
604 GetCurrentCommandId(bool used)
606 /* this is global to a transaction, not subtransaction-local */
608 currentCommandIdUsed = true;
609 return currentCommandId;
613 * GetCurrentTransactionStartTimestamp
616 GetCurrentTransactionStartTimestamp(void)
618 return xactStartTimestamp;
622 * GetCurrentStatementStartTimestamp
625 GetCurrentStatementStartTimestamp(void)
627 return stmtStartTimestamp;
631 * GetCurrentTransactionStopTimestamp
633 * We return current time if the transaction stop time hasn't been set
634 * (which can happen if we decide we don't need to log an XLOG record).
637 GetCurrentTransactionStopTimestamp(void)
639 if (xactStopTimestamp != 0)
640 return xactStopTimestamp;
641 return GetCurrentTimestamp();
645 * SetCurrentStatementStartTimestamp
648 SetCurrentStatementStartTimestamp(void)
650 stmtStartTimestamp = GetCurrentTimestamp();
654 * SetCurrentTransactionStopTimestamp
657 SetCurrentTransactionStopTimestamp(void)
659 xactStopTimestamp = GetCurrentTimestamp();
663 * GetCurrentTransactionNestLevel
665 * Note: this will return zero when not inside any transaction, one when
666 * inside a top-level transaction, etc.
669 GetCurrentTransactionNestLevel(void)
671 TransactionState s = CurrentTransactionState;
673 return s->nestingLevel;
678 * TransactionIdIsCurrentTransactionId
681 TransactionIdIsCurrentTransactionId(TransactionId xid)
686 * We always say that BootstrapTransactionId is "not my transaction ID"
687 * even when it is (ie, during bootstrap). Along with the fact that
688 * transam.c always treats BootstrapTransactionId as already committed,
689 * this causes the tqual.c routines to see all tuples as committed, which
690 * is what we need during bootstrap. (Bootstrap mode only inserts tuples,
691 * it never updates or deletes them, so all tuples can be presumed good
694 * Likewise, InvalidTransactionId and FrozenTransactionId are certainly
695 * not my transaction ID, so we can just return "false" immediately for
696 * any non-normal XID.
698 if (!TransactionIdIsNormal(xid))
702 * We will return true for the Xid of the current subtransaction, any of
703 * its subcommitted children, any of its parents, or any of their
704 * previously subcommitted children. However, a transaction being aborted
705 * is no longer "current", even though it may still have an entry on the
708 for (s = CurrentTransactionState; s != NULL; s = s->parent)
713 if (s->state == TRANS_ABORT)
715 if (!TransactionIdIsValid(s->transactionId))
716 continue; /* it can't have any child XIDs either */
717 if (TransactionIdEquals(xid, s->transactionId))
719 /* As the childXids array is ordered, we can use binary search */
721 high = s->nChildXids - 1;
727 middle = low + (high - low) / 2;
728 probe = s->childXids[middle];
729 if (TransactionIdEquals(probe, xid))
731 else if (TransactionIdPrecedes(probe, xid))
742 * TransactionStartedDuringRecovery
744 * Returns true if the current transaction started while recovery was still
745 * in progress. Recovery might have ended since so RecoveryInProgress() might
746 * return false already.
749 TransactionStartedDuringRecovery(void)
751 return CurrentTransactionState->startedInRecovery;
755 * CommandCounterIncrement
758 CommandCounterIncrement(void)
761 * If the current value of the command counter hasn't been "used" to mark
762 * tuples, we need not increment it, since there's no need to distinguish
763 * a read-only command from others. This helps postpone command counter
764 * overflow, and keeps no-op CommandCounterIncrement operations cheap.
766 if (currentCommandIdUsed)
768 currentCommandId += 1;
769 if (currentCommandId == InvalidCommandId)
771 currentCommandId -= 1;
773 (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
774 errmsg("cannot have more than 2^32-2 commands in a transaction")));
776 currentCommandIdUsed = false;
778 /* Propagate new command ID into static snapshots */
779 SnapshotSetCommandId(currentCommandId);
782 * Make any catalog changes done by the just-completed command visible
783 * in the local syscache. We obviously don't need to do this after a
784 * read-only command. (But see hacks in inval.c to make real sure we
785 * don't think a command that queued inval messages was read-only.)
794 * Interface routine to allow commands to force a synchronous commit of the
795 * current top-level transaction
798 ForceSyncCommit(void)
800 forceSyncCommit = true;
804 /* ----------------------------------------------------------------
805 * StartTransaction stuff
806 * ----------------------------------------------------------------
815 AcceptInvalidationMessages();
824 TransactionState s = CurrentTransactionState;
827 * If this is the first time through, create a private context for
828 * AbortTransaction to work in. By reserving some space now, we can
829 * insulate AbortTransaction from out-of-memory scenarios. Like
830 * ErrorContext, we set it up with slow growth rate and a nonzero minimum
831 * size, so that space will be reserved immediately.
833 if (TransactionAbortContext == NULL)
834 TransactionAbortContext =
835 AllocSetContextCreate(TopMemoryContext,
836 "TransactionAbortContext",
842 * We shouldn't have a transaction context already.
844 Assert(TopTransactionContext == NULL);
847 * Create a toplevel context for the transaction.
849 TopTransactionContext =
850 AllocSetContextCreate(TopMemoryContext,
851 "TopTransactionContext",
852 ALLOCSET_DEFAULT_MINSIZE,
853 ALLOCSET_DEFAULT_INITSIZE,
854 ALLOCSET_DEFAULT_MAXSIZE);
857 * In a top-level transaction, CurTransactionContext is the same as
858 * TopTransactionContext.
860 CurTransactionContext = TopTransactionContext;
861 s->curTransactionContext = CurTransactionContext;
863 /* Make the CurTransactionContext active. */
864 MemoryContextSwitchTo(CurTransactionContext);
868 * AtStart_ResourceOwner
871 AtStart_ResourceOwner(void)
873 TransactionState s = CurrentTransactionState;
876 * We shouldn't have a transaction resource owner already.
878 Assert(TopTransactionResourceOwner == NULL);
881 * Create a toplevel resource owner for the transaction.
883 s->curTransactionOwner = ResourceOwnerCreate(NULL, "TopTransaction");
885 TopTransactionResourceOwner = s->curTransactionOwner;
886 CurTransactionResourceOwner = s->curTransactionOwner;
887 CurrentResourceOwner = s->curTransactionOwner;
890 /* ----------------------------------------------------------------
891 * StartSubTransaction stuff
892 * ----------------------------------------------------------------
899 AtSubStart_Memory(void)
901 TransactionState s = CurrentTransactionState;
903 Assert(CurTransactionContext != NULL);
906 * Create a CurTransactionContext, which will be used to hold data that
907 * survives subtransaction commit but disappears on subtransaction abort.
908 * We make it a child of the immediate parent's CurTransactionContext.
910 CurTransactionContext = AllocSetContextCreate(CurTransactionContext,
911 "CurTransactionContext",
912 ALLOCSET_DEFAULT_MINSIZE,
913 ALLOCSET_DEFAULT_INITSIZE,
914 ALLOCSET_DEFAULT_MAXSIZE);
915 s->curTransactionContext = CurTransactionContext;
917 /* Make the CurTransactionContext active. */
918 MemoryContextSwitchTo(CurTransactionContext);
922 * AtSubStart_ResourceOwner
925 AtSubStart_ResourceOwner(void)
927 TransactionState s = CurrentTransactionState;
929 Assert(s->parent != NULL);
932 * Create a resource owner for the subtransaction. We make it a child of
933 * the immediate parent's resource owner.
935 s->curTransactionOwner =
936 ResourceOwnerCreate(s->parent->curTransactionOwner,
939 CurTransactionResourceOwner = s->curTransactionOwner;
940 CurrentResourceOwner = s->curTransactionOwner;
943 /* ----------------------------------------------------------------
944 * CommitTransaction stuff
945 * ----------------------------------------------------------------
949 * RecordTransactionCommit
951 * Returns latest XID among xact and its children, or InvalidTransactionId
952 * if the xact has no XID. (We compute that here just because it's easier.)
955 RecordTransactionCommit(void)
957 TransactionId xid = GetTopTransactionIdIfAny();
958 bool markXidCommitted = TransactionIdIsValid(xid);
959 TransactionId latestXid = InvalidTransactionId;
963 TransactionId *children;
965 SharedInvalidationMessage *invalMessages = NULL;
966 bool RelcacheInitFileInval = false;
969 /* Get data needed for commit record */
970 nrels = smgrGetPendingDeletes(true, &rels);
971 nchildren = xactGetCommittedChildren(&children);
972 if (XLogStandbyInfoActive())
973 nmsgs = xactGetCommittedInvalidationMessages(&invalMessages,
974 &RelcacheInitFileInval);
975 wrote_xlog = (XactLastRecEnd != 0);
978 * If we haven't been assigned an XID yet, we neither can, nor do we want
979 * to write a COMMIT record.
981 if (!markXidCommitted)
984 * We expect that every smgrscheduleunlink is followed by a catalog
985 * update, and hence XID assignment, so we shouldn't get here with any
986 * pending deletes. Use a real test not just an Assert to check this,
987 * since it's a bit fragile.
990 elog(ERROR, "cannot commit a transaction that deleted files but has no xid");
992 /* Can't have child XIDs either; AssignTransactionId enforces this */
993 Assert(nchildren == 0);
996 * If we didn't create XLOG entries, we're done here; otherwise we
997 * should flush those entries the same as a commit record. (An
998 * example of a possible record that wouldn't cause an XID to be
999 * assigned is a sequence advance record due to nextval() --- we want
1000 * to flush that to disk before reporting commit.)
1008 * Begin commit critical section and insert the commit XLOG record.
1010 /* Tell bufmgr and smgr to prepare for commit */
1014 * Mark ourselves as within our "commit critical section". This
1015 * forces any concurrent checkpoint to wait until we've updated
1016 * pg_clog. Without this, it is possible for the checkpoint to set
1017 * REDO after the XLOG record but fail to flush the pg_clog update to
1018 * disk, leading to loss of the transaction commit if the system
1019 * crashes a little later.
1021 * Note: we could, but don't bother to, set this flag in
1022 * RecordTransactionAbort. That's because loss of a transaction abort
1023 * is noncritical; the presumption would be that it aborted, anyway.
1025 * It's safe to change the delayChkpt flag of our own backend without
1026 * holding the ProcArrayLock, since we're the only one modifying it.
1027 * This makes checkpoint's determination of which xacts are delayChkpt
1028 * a bit fuzzy, but it doesn't matter.
1030 START_CRIT_SECTION();
1031 MyPgXact->delayChkpt = true;
1033 SetCurrentTransactionStopTimestamp();
1036 * Do we need the long commit record? If not, use the compact format.
1038 if (nrels > 0 || nmsgs > 0 || RelcacheInitFileInval || forceSyncCommit)
1040 XLogRecData rdata[4];
1042 xl_xact_commit xlrec;
1045 * Set flags required for recovery processing of commits.
1048 if (RelcacheInitFileInval)
1049 xlrec.xinfo |= XACT_COMPLETION_UPDATE_RELCACHE_FILE;
1050 if (forceSyncCommit)
1051 xlrec.xinfo |= XACT_COMPLETION_FORCE_SYNC_COMMIT;
1053 xlrec.dbId = MyDatabaseId;
1054 xlrec.tsId = MyDatabaseTableSpace;
1056 xlrec.xact_time = xactStopTimestamp;
1057 xlrec.nrels = nrels;
1058 xlrec.nsubxacts = nchildren;
1059 xlrec.nmsgs = nmsgs;
1060 rdata[0].data = (char *) (&xlrec);
1061 rdata[0].len = MinSizeOfXactCommit;
1062 rdata[0].buffer = InvalidBuffer;
1063 /* dump rels to delete */
1066 rdata[0].next = &(rdata[1]);
1067 rdata[1].data = (char *) rels;
1068 rdata[1].len = nrels * sizeof(RelFileNode);
1069 rdata[1].buffer = InvalidBuffer;
1072 /* dump committed child Xids */
1075 rdata[lastrdata].next = &(rdata[2]);
1076 rdata[2].data = (char *) children;
1077 rdata[2].len = nchildren * sizeof(TransactionId);
1078 rdata[2].buffer = InvalidBuffer;
1081 /* dump shared cache invalidation messages */
1084 rdata[lastrdata].next = &(rdata[3]);
1085 rdata[3].data = (char *) invalMessages;
1086 rdata[3].len = nmsgs * sizeof(SharedInvalidationMessage);
1087 rdata[3].buffer = InvalidBuffer;
1090 rdata[lastrdata].next = NULL;
1092 (void) XLogInsert(RM_XACT_ID, XLOG_XACT_COMMIT, rdata);
1096 XLogRecData rdata[2];
1098 xl_xact_commit_compact xlrec;
1100 xlrec.xact_time = xactStopTimestamp;
1101 xlrec.nsubxacts = nchildren;
1102 rdata[0].data = (char *) (&xlrec);
1103 rdata[0].len = MinSizeOfXactCommitCompact;
1104 rdata[0].buffer = InvalidBuffer;
1105 /* dump committed child Xids */
1108 rdata[0].next = &(rdata[1]);
1109 rdata[1].data = (char *) children;
1110 rdata[1].len = nchildren * sizeof(TransactionId);
1111 rdata[1].buffer = InvalidBuffer;
1114 rdata[lastrdata].next = NULL;
1116 (void) XLogInsert(RM_XACT_ID, XLOG_XACT_COMMIT_COMPACT, rdata);
1121 * Check if we want to commit asynchronously. We can allow the XLOG flush
1122 * to happen asynchronously if synchronous_commit=off, or if the current
1123 * transaction has not performed any WAL-logged operation. The latter
1124 * case can arise if the current transaction wrote only to temporary
1125 * and/or unlogged tables. In case of a crash, the loss of such a
1126 * transaction will be irrelevant since temp tables will be lost anyway,
1127 * and unlogged tables will be truncated. (Given the foregoing, you might
1128 * think that it would be unnecessary to emit the XLOG record at all in
1129 * this case, but we don't currently try to do that. It would certainly
1130 * cause problems at least in Hot Standby mode, where the
1131 * KnownAssignedXids machinery requires tracking every XID assignment. It
1132 * might be OK to skip it only when wal_level < hot_standby, but for now
1135 * However, if we're doing cleanup of any non-temp rels or committing any
1136 * command that wanted to force sync commit, then we must flush XLOG
1137 * immediately. (We must not allow asynchronous commit if there are any
1138 * non-temp tables to be deleted, because we might delete the files before
1139 * the COMMIT record is flushed to disk. We do allow asynchronous commit
1140 * if all to-be-deleted tables are temporary though, since they are lost
1141 * anyway if we crash.)
1143 if ((wrote_xlog && synchronous_commit > SYNCHRONOUS_COMMIT_OFF) ||
1144 forceSyncCommit || nrels > 0)
1146 XLogFlush(XactLastRecEnd);
1149 * Now we may update the CLOG, if we wrote a COMMIT record above
1151 if (markXidCommitted)
1152 TransactionIdCommitTree(xid, nchildren, children);
1157 * Asynchronous commit case:
1159 * This enables possible committed transaction loss in the case of a
1160 * postmaster crash because WAL buffers are left unwritten. Ideally we
1161 * could issue the WAL write without the fsync, but some
1162 * wal_sync_methods do not allow separate write/fsync.
1164 * Report the latest async commit LSN, so that the WAL writer knows to
1165 * flush this commit.
1167 XLogSetAsyncXactLSN(XactLastRecEnd);
1170 * We must not immediately update the CLOG, since we didn't flush the
1171 * XLOG. Instead, we store the LSN up to which the XLOG must be
1172 * flushed before the CLOG may be updated.
1174 if (markXidCommitted)
1175 TransactionIdAsyncCommitTree(xid, nchildren, children, XactLastRecEnd);
1179 * If we entered a commit critical section, leave it now, and let
1180 * checkpoints proceed.
1182 if (markXidCommitted)
1184 MyPgXact->delayChkpt = false;
1188 /* Compute latestXid while we have the child XIDs handy */
1189 latestXid = TransactionIdLatest(xid, nchildren, children);
1192 * Wait for synchronous replication, if required.
1194 * Note that at this stage we have marked clog, but still show as running
1195 * in the procarray and continue to hold locks.
1198 SyncRepWaitForLSN(XactLastRecEnd);
1200 /* Reset XactLastRecEnd until the next transaction writes something */
1204 /* Clean up local data */
1216 AtCCI_LocalCache(void)
1219 * Make any pending relation map changes visible. We must do this before
1220 * processing local sinval messages, so that the map changes will get
1221 * reflected into the relcache when relcache invals are processed.
1223 AtCCI_RelationMap();
1226 * Make catalog changes visible to me for the next command.
1228 CommandEndInvalidationMessages();
1235 AtCommit_Memory(void)
1238 * Now that we're "out" of a transaction, have the system allocate things
1239 * in the top memory context instead of per-transaction contexts.
1241 MemoryContextSwitchTo(TopMemoryContext);
1244 * Release all transaction-local memory.
1246 Assert(TopTransactionContext != NULL);
1247 MemoryContextDelete(TopTransactionContext);
1248 TopTransactionContext = NULL;
1249 CurTransactionContext = NULL;
1250 CurrentTransactionState->curTransactionContext = NULL;
1253 /* ----------------------------------------------------------------
1254 * CommitSubTransaction stuff
1255 * ----------------------------------------------------------------
1259 * AtSubCommit_Memory
1262 AtSubCommit_Memory(void)
1264 TransactionState s = CurrentTransactionState;
1266 Assert(s->parent != NULL);
1268 /* Return to parent transaction level's memory context. */
1269 CurTransactionContext = s->parent->curTransactionContext;
1270 MemoryContextSwitchTo(CurTransactionContext);
1273 * Ordinarily we cannot throw away the child's CurTransactionContext,
1274 * since the data it contains will be needed at upper commit. However, if
1275 * there isn't actually anything in it, we can throw it away. This avoids
1276 * a small memory leak in the common case of "trivial" subxacts.
1278 if (MemoryContextIsEmpty(s->curTransactionContext))
1280 MemoryContextDelete(s->curTransactionContext);
1281 s->curTransactionContext = NULL;
1286 * AtSubCommit_childXids
1288 * Pass my own XID and my child XIDs up to my parent as committed children.
1291 AtSubCommit_childXids(void)
1293 TransactionState s = CurrentTransactionState;
1296 Assert(s->parent != NULL);
1299 * The parent childXids array will need to hold my XID and all my
1300 * childXids, in addition to the XIDs already there.
1302 new_nChildXids = s->parent->nChildXids + s->nChildXids + 1;
1304 /* Allocate or enlarge the parent array if necessary */
1305 if (s->parent->maxChildXids < new_nChildXids)
1307 int new_maxChildXids;
1308 TransactionId *new_childXids;
1311 * Make it 2x what's needed right now, to avoid having to enlarge it
1312 * repeatedly. But we can't go above MaxAllocSize. (The latter limit
1313 * is what ensures that we don't need to worry about integer overflow
1314 * here or in the calculation of new_nChildXids.)
1316 new_maxChildXids = Min(new_nChildXids * 2,
1317 (int) (MaxAllocSize / sizeof(TransactionId)));
1319 if (new_maxChildXids < new_nChildXids)
1321 (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
1322 errmsg("maximum number of committed subtransactions (%d) exceeded",
1323 (int) (MaxAllocSize / sizeof(TransactionId)))));
1326 * We keep the child-XID arrays in TopTransactionContext; this avoids
1327 * setting up child-transaction contexts for what might be just a few
1328 * bytes of grandchild XIDs.
1330 if (s->parent->childXids == NULL)
1332 MemoryContextAlloc(TopTransactionContext,
1333 new_maxChildXids * sizeof(TransactionId));
1335 new_childXids = repalloc(s->parent->childXids,
1336 new_maxChildXids * sizeof(TransactionId));
1338 s->parent->childXids = new_childXids;
1339 s->parent->maxChildXids = new_maxChildXids;
1343 * Copy all my XIDs to parent's array.
1345 * Note: We rely on the fact that the XID of a child always follows that
1346 * of its parent. By copying the XID of this subtransaction before the
1347 * XIDs of its children, we ensure that the array stays ordered. Likewise,
1348 * all XIDs already in the array belong to subtransactions started and
1349 * subcommitted before us, so their XIDs must precede ours.
1351 s->parent->childXids[s->parent->nChildXids] = s->transactionId;
1353 if (s->nChildXids > 0)
1354 memcpy(&s->parent->childXids[s->parent->nChildXids + 1],
1356 s->nChildXids * sizeof(TransactionId));
1358 s->parent->nChildXids = new_nChildXids;
1360 /* Release child's array to avoid leakage */
1361 if (s->childXids != NULL)
1362 pfree(s->childXids);
1363 /* We must reset these to avoid double-free if fail later in commit */
1364 s->childXids = NULL;
1366 s->maxChildXids = 0;
1369 /* ----------------------------------------------------------------
1370 * AbortTransaction stuff
1371 * ----------------------------------------------------------------
1375 * RecordTransactionAbort
1377 * Returns latest XID among xact and its children, or InvalidTransactionId
1378 * if the xact has no XID. (We compute that here just because it's easier.)
1380 static TransactionId
1381 RecordTransactionAbort(bool isSubXact)
1383 TransactionId xid = GetCurrentTransactionIdIfAny();
1384 TransactionId latestXid;
1388 TransactionId *children;
1389 XLogRecData rdata[3];
1391 xl_xact_abort xlrec;
1394 * If we haven't been assigned an XID, nobody will care whether we aborted
1395 * or not. Hence, we're done in that case. It does not matter if we have
1396 * rels to delete (note that this routine is not responsible for actually
1397 * deleting 'em). We cannot have any child XIDs, either.
1399 if (!TransactionIdIsValid(xid))
1401 /* Reset XactLastRecEnd until the next transaction writes something */
1404 return InvalidTransactionId;
1408 * We have a valid XID, so we should write an ABORT record for it.
1410 * We do not flush XLOG to disk here, since the default assumption after a
1411 * crash would be that we aborted, anyway. For the same reason, we don't
1412 * need to worry about interlocking against checkpoint start.
1416 * Check that we haven't aborted halfway through RecordTransactionCommit.
1418 if (TransactionIdDidCommit(xid))
1419 elog(PANIC, "cannot abort transaction %u, it was already committed",
1422 /* Fetch the data we need for the abort record */
1423 nrels = smgrGetPendingDeletes(false, &rels);
1424 nchildren = xactGetCommittedChildren(&children);
1426 /* XXX do we really need a critical section here? */
1427 START_CRIT_SECTION();
1429 /* Write the ABORT record */
1431 xlrec.xact_time = GetCurrentTimestamp();
1434 SetCurrentTransactionStopTimestamp();
1435 xlrec.xact_time = xactStopTimestamp;
1437 xlrec.nrels = nrels;
1438 xlrec.nsubxacts = nchildren;
1439 rdata[0].data = (char *) (&xlrec);
1440 rdata[0].len = MinSizeOfXactAbort;
1441 rdata[0].buffer = InvalidBuffer;
1442 /* dump rels to delete */
1445 rdata[0].next = &(rdata[1]);
1446 rdata[1].data = (char *) rels;
1447 rdata[1].len = nrels * sizeof(RelFileNode);
1448 rdata[1].buffer = InvalidBuffer;
1451 /* dump committed child Xids */
1454 rdata[lastrdata].next = &(rdata[2]);
1455 rdata[2].data = (char *) children;
1456 rdata[2].len = nchildren * sizeof(TransactionId);
1457 rdata[2].buffer = InvalidBuffer;
1460 rdata[lastrdata].next = NULL;
1462 (void) XLogInsert(RM_XACT_ID, XLOG_XACT_ABORT, rdata);
1465 * Report the latest async abort LSN, so that the WAL writer knows to
1466 * flush this abort. There's nothing to be gained by delaying this, since
1467 * WALWriter may as well do this when it can. This is important with
1468 * streaming replication because if we don't flush WAL regularly we will
1469 * find that large aborts leave us with a long backlog for when commits
1470 * occur after the abort, increasing our window of data loss should
1471 * problems occur at that point.
1474 XLogSetAsyncXactLSN(XactLastRecEnd);
1477 * Mark the transaction aborted in clog. This is not absolutely necessary
1478 * but we may as well do it while we are here; also, in the subxact case
1479 * it is helpful because XactLockTableWait makes use of it to avoid
1480 * waiting for already-aborted subtransactions. It is OK to do it without
1481 * having flushed the ABORT record to disk, because in event of a crash
1482 * we'd be assumed to have aborted anyway.
1484 TransactionIdAbortTree(xid, nchildren, children);
1488 /* Compute latestXid while we have the child XIDs handy */
1489 latestXid = TransactionIdLatest(xid, nchildren, children);
1492 * If we're aborting a subtransaction, we can immediately remove failed
1493 * XIDs from PGPROC's cache of running child XIDs. We do that here for
1494 * subxacts, because we already have the child XID array at hand. For
1495 * main xacts, the equivalent happens just after this function returns.
1498 XidCacheRemoveRunningXids(xid, nchildren, children, latestXid);
1500 /* Reset XactLastRecEnd until the next transaction writes something */
1504 /* And clean up local data */
1515 AtAbort_Memory(void)
1518 * Switch into TransactionAbortContext, which should have some free space
1519 * even if nothing else does. We'll work in this context until we've
1520 * finished cleaning up.
1522 * It is barely possible to get here when we've not been able to create
1523 * TransactionAbortContext yet; if so use TopMemoryContext.
1525 if (TransactionAbortContext != NULL)
1526 MemoryContextSwitchTo(TransactionAbortContext);
1528 MemoryContextSwitchTo(TopMemoryContext);
1535 AtSubAbort_Memory(void)
1537 Assert(TransactionAbortContext != NULL);
1539 MemoryContextSwitchTo(TransactionAbortContext);
1544 * AtAbort_ResourceOwner
1547 AtAbort_ResourceOwner(void)
1550 * Make sure we have a valid ResourceOwner, if possible (else it will be
1551 * NULL, which is OK)
1553 CurrentResourceOwner = TopTransactionResourceOwner;
1557 * AtSubAbort_ResourceOwner
1560 AtSubAbort_ResourceOwner(void)
1562 TransactionState s = CurrentTransactionState;
1564 /* Make sure we have a valid ResourceOwner */
1565 CurrentResourceOwner = s->curTransactionOwner;
1570 * AtSubAbort_childXids
1573 AtSubAbort_childXids(void)
1575 TransactionState s = CurrentTransactionState;
1578 * We keep the child-XID arrays in TopTransactionContext (see
1579 * AtSubCommit_childXids). This means we'd better free the array
1580 * explicitly at abort to avoid leakage.
1582 if (s->childXids != NULL)
1583 pfree(s->childXids);
1584 s->childXids = NULL;
1586 s->maxChildXids = 0;
1589 * We could prune the unreportedXids array here. But we don't bother. That
1590 * would potentially reduce number of XLOG_XACT_ASSIGNMENT records but it
1591 * would likely introduce more CPU time into the more common paths, so we
1592 * choose not to do that.
1596 /* ----------------------------------------------------------------
1597 * CleanupTransaction stuff
1598 * ----------------------------------------------------------------
1605 AtCleanup_Memory(void)
1607 Assert(CurrentTransactionState->parent == NULL);
1610 * Now that we're "out" of a transaction, have the system allocate things
1611 * in the top memory context instead of per-transaction contexts.
1613 MemoryContextSwitchTo(TopMemoryContext);
1616 * Clear the special abort context for next time.
1618 if (TransactionAbortContext != NULL)
1619 MemoryContextResetAndDeleteChildren(TransactionAbortContext);
1622 * Release all transaction-local memory.
1624 if (TopTransactionContext != NULL)
1625 MemoryContextDelete(TopTransactionContext);
1626 TopTransactionContext = NULL;
1627 CurTransactionContext = NULL;
1628 CurrentTransactionState->curTransactionContext = NULL;
1632 /* ----------------------------------------------------------------
1633 * CleanupSubTransaction stuff
1634 * ----------------------------------------------------------------
1638 * AtSubCleanup_Memory
1641 AtSubCleanup_Memory(void)
1643 TransactionState s = CurrentTransactionState;
1645 Assert(s->parent != NULL);
1647 /* Make sure we're not in an about-to-be-deleted context */
1648 MemoryContextSwitchTo(s->parent->curTransactionContext);
1649 CurTransactionContext = s->parent->curTransactionContext;
1652 * Clear the special abort context for next time.
1654 if (TransactionAbortContext != NULL)
1655 MemoryContextResetAndDeleteChildren(TransactionAbortContext);
1658 * Delete the subxact local memory contexts. Its CurTransactionContext can
1659 * go too (note this also kills CurTransactionContexts from any children
1662 if (s->curTransactionContext)
1663 MemoryContextDelete(s->curTransactionContext);
1664 s->curTransactionContext = NULL;
1667 /* ----------------------------------------------------------------
1668 * interface routines
1669 * ----------------------------------------------------------------
1676 StartTransaction(void)
1679 VirtualTransactionId vxid;
1682 * Let's just make sure the state stack is empty
1684 s = &TopTransactionStateData;
1685 CurrentTransactionState = s;
1688 * check the current transaction state
1690 if (s->state != TRANS_DEFAULT)
1691 elog(WARNING, "StartTransaction while in %s state",
1692 TransStateAsString(s->state));
1695 * set the current transaction state information appropriately during
1698 s->state = TRANS_START;
1699 s->transactionId = InvalidTransactionId; /* until assigned */
1702 * Make sure we've reset xact state variables
1704 * If recovery is still in progress, mark this transaction as read-only.
1705 * We have lower level defences in XLogInsert and elsewhere to stop us
1706 * from modifying data during recovery, but this gives the normal
1707 * indication to the user that the transaction is read-only.
1709 if (RecoveryInProgress())
1711 s->startedInRecovery = true;
1712 XactReadOnly = true;
1716 s->startedInRecovery = false;
1717 XactReadOnly = DefaultXactReadOnly;
1719 XactDeferrable = DefaultXactDeferrable;
1720 XactIsoLevel = DefaultXactIsoLevel;
1721 forceSyncCommit = false;
1722 MyXactAccessedTempRel = false;
1725 * reinitialize within-transaction counters
1727 s->subTransactionId = TopSubTransactionId;
1728 currentSubTransactionId = TopSubTransactionId;
1729 currentCommandId = FirstCommandId;
1730 currentCommandIdUsed = false;
1733 * initialize reported xid accounting
1735 nUnreportedXids = 0;
1738 * must initialize resource-management stuff first
1741 AtStart_ResourceOwner();
1744 * Assign a new LocalTransactionId, and combine it with the backendId to
1745 * form a virtual transaction id.
1747 vxid.backendId = MyBackendId;
1748 vxid.localTransactionId = GetNextLocalTransactionId();
1751 * Lock the virtual transaction id before we announce it in the proc array
1753 VirtualXactLockTableInsert(vxid);
1756 * Advertise it in the proc array. We assume assignment of
1757 * LocalTransactionID is atomic, and the backendId should be set already.
1759 Assert(MyProc->backendId == vxid.backendId);
1760 MyProc->lxid = vxid.localTransactionId;
1762 TRACE_POSTGRESQL_TRANSACTION_START(vxid.localTransactionId);
1765 * set transaction_timestamp() (a/k/a now()). We want this to be the same
1766 * as the first command's statement_timestamp(), so don't do a fresh
1767 * GetCurrentTimestamp() call (which'd be expensive anyway). Also, mark
1768 * xactStopTimestamp as unset.
1770 xactStartTimestamp = stmtStartTimestamp;
1771 xactStopTimestamp = 0;
1772 pgstat_report_xact_timestamp(xactStartTimestamp);
1775 * initialize current transaction state fields
1777 * note: prevXactReadOnly is not used at the outermost level
1779 s->nestingLevel = 1;
1780 s->gucNestLevel = 1;
1781 s->childXids = NULL;
1783 s->maxChildXids = 0;
1784 GetUserIdAndSecContext(&s->prevUser, &s->prevSecContext);
1785 /* SecurityRestrictionContext should never be set outside a transaction */
1786 Assert(s->prevSecContext == 0);
1789 * initialize other subsystems for new transaction
1794 AfterTriggerBeginXact();
1797 * done with start processing, set current transaction state to "in
1800 s->state = TRANS_INPROGRESS;
1802 ShowTransactionState("StartTransaction");
1809 * NB: if you change this routine, better look at PrepareTransaction too!
1812 CommitTransaction(void)
1814 TransactionState s = CurrentTransactionState;
1815 TransactionId latestXid;
1817 ShowTransactionState("CommitTransaction");
1820 * check the current transaction state
1822 if (s->state != TRANS_INPROGRESS)
1823 elog(WARNING, "CommitTransaction while in %s state",
1824 TransStateAsString(s->state));
1825 Assert(s->parent == NULL);
1828 * Do pre-commit processing that involves calling user-defined code, such
1829 * as triggers. Since closing cursors could queue trigger actions,
1830 * triggers could open cursors, etc, we have to keep looping until there's
1831 * nothing left to do.
1836 * Fire all currently pending deferred triggers.
1838 AfterTriggerFireDeferred();
1841 * Close open portals (converting holdable ones into static portals).
1842 * If there weren't any, we are done ... otherwise loop back to check
1843 * if they queued deferred triggers. Lather, rinse, repeat.
1845 if (!PreCommit_Portals(false))
1849 CallXactCallbacks(XACT_EVENT_PRE_COMMIT);
1852 * The remaining actions cannot call any user-defined code, so it's safe
1853 * to start shutting down within-transaction services. But note that most
1854 * of this stuff could still throw an error, which would switch us into
1855 * the transaction-abort path.
1858 /* Shut down the deferred-trigger manager */
1859 AfterTriggerEndXact(true);
1862 * Let ON COMMIT management do its thing (must happen after closing
1863 * cursors, to avoid dangling-reference problems)
1865 PreCommit_on_commit_actions();
1867 /* close large objects before lower-level cleanup */
1868 AtEOXact_LargeObject(true);
1871 * Mark serializable transaction as complete for predicate locking
1872 * purposes. This should be done as late as we can put it and still allow
1873 * errors to be raised for failure patterns found at commit.
1875 PreCommit_CheckForSerializationFailure();
1878 * Insert notifications sent by NOTIFY commands into the queue. This
1879 * should be late in the pre-commit sequence to minimize time spent
1880 * holding the notify-insertion lock.
1884 /* Prevent cancel/die interrupt while cleaning up */
1887 /* Commit updates to the relation map --- do this as late as possible */
1888 AtEOXact_RelationMap(true);
1891 * set the current transaction state information appropriately during
1894 s->state = TRANS_COMMIT;
1897 * Here is where we really truly commit.
1899 latestXid = RecordTransactionCommit();
1901 TRACE_POSTGRESQL_TRANSACTION_COMMIT(MyProc->lxid);
1904 * Let others know about no transaction in progress by me. Note that this
1905 * must be done _before_ releasing locks we hold and _after_
1906 * RecordTransactionCommit.
1908 ProcArrayEndTransaction(MyProc, latestXid);
1911 * This is all post-commit cleanup. Note that if an error is raised here,
1912 * it's too late to abort the transaction. This should be just
1913 * noncritical resource releasing.
1915 * The ordering of operations is not entirely random. The idea is:
1916 * release resources visible to other backends (eg, files, buffer pins);
1917 * then release locks; then release backend-local resources. We want to
1918 * release locks at the point where any backend waiting for us will see
1919 * our transaction as being fully cleaned up.
1921 * Resources that can be associated with individual queries are handled by
1922 * the ResourceOwner mechanism. The other calls here are for backend-wide
1926 CallXactCallbacks(XACT_EVENT_COMMIT);
1928 ResourceOwnerRelease(TopTransactionResourceOwner,
1929 RESOURCE_RELEASE_BEFORE_LOCKS,
1932 /* Check we've released all buffer pins */
1933 AtEOXact_Buffers(true);
1935 /* Clean up the relation cache */
1936 AtEOXact_RelationCache(true);
1939 * Make catalog changes visible to all backends. This has to happen after
1940 * relcache references are dropped (see comments for
1941 * AtEOXact_RelationCache), but before locks are released (if anyone is
1942 * waiting for lock on a relation we've modified, we want them to know
1943 * about the catalog change before they start using the relation).
1945 AtEOXact_Inval(true);
1947 AtEOXact_MultiXact();
1949 ResourceOwnerRelease(TopTransactionResourceOwner,
1950 RESOURCE_RELEASE_LOCKS,
1952 ResourceOwnerRelease(TopTransactionResourceOwner,
1953 RESOURCE_RELEASE_AFTER_LOCKS,
1957 * Likewise, dropping of files deleted during the transaction is best done
1958 * after releasing relcache and buffer pins. (This is not strictly
1959 * necessary during commit, since such pins should have been released
1960 * already, but this ordering is definitely critical during abort.) Since
1961 * this may take many seconds, also delay until after releasing locks.
1962 * Other backends will observe the attendant catalog changes and not
1963 * attempt to access affected files.
1965 smgrDoPendingDeletes(true);
1967 /* Check we've released all catcache entries */
1968 AtEOXact_CatCache(true);
1971 AtEOXact_GUC(true, 1);
1973 AtEOXact_on_commit_actions(true);
1974 AtEOXact_Namespace(true);
1977 AtEOXact_ComboCid();
1978 AtEOXact_HashTables(true);
1979 AtEOXact_PgStat(true);
1980 AtEOXact_Snapshot(true);
1981 pgstat_report_xact_timestamp(0);
1983 CurrentResourceOwner = NULL;
1984 ResourceOwnerDelete(TopTransactionResourceOwner);
1985 s->curTransactionOwner = NULL;
1986 CurTransactionResourceOwner = NULL;
1987 TopTransactionResourceOwner = NULL;
1991 s->transactionId = InvalidTransactionId;
1992 s->subTransactionId = InvalidSubTransactionId;
1993 s->nestingLevel = 0;
1994 s->gucNestLevel = 0;
1995 s->childXids = NULL;
1997 s->maxChildXids = 0;
2000 * done with commit processing, set current transaction state back to
2003 s->state = TRANS_DEFAULT;
2005 RESUME_INTERRUPTS();
2010 * PrepareTransaction
2012 * NB: if you change this routine, better look at CommitTransaction too!
2015 PrepareTransaction(void)
2017 TransactionState s = CurrentTransactionState;
2018 TransactionId xid = GetCurrentTransactionId();
2019 GlobalTransaction gxact;
2020 TimestampTz prepared_at;
2022 ShowTransactionState("PrepareTransaction");
2025 * check the current transaction state
2027 if (s->state != TRANS_INPROGRESS)
2028 elog(WARNING, "PrepareTransaction while in %s state",
2029 TransStateAsString(s->state));
2030 Assert(s->parent == NULL);
2033 * Do pre-commit processing that involves calling user-defined code, such
2034 * as triggers. Since closing cursors could queue trigger actions,
2035 * triggers could open cursors, etc, we have to keep looping until there's
2036 * nothing left to do.
2041 * Fire all currently pending deferred triggers.
2043 AfterTriggerFireDeferred();
2046 * Close open portals (converting holdable ones into static portals).
2047 * If there weren't any, we are done ... otherwise loop back to check
2048 * if they queued deferred triggers. Lather, rinse, repeat.
2050 if (!PreCommit_Portals(true))
2054 CallXactCallbacks(XACT_EVENT_PRE_PREPARE);
2057 * The remaining actions cannot call any user-defined code, so it's safe
2058 * to start shutting down within-transaction services. But note that most
2059 * of this stuff could still throw an error, which would switch us into
2060 * the transaction-abort path.
2063 /* Shut down the deferred-trigger manager */
2064 AfterTriggerEndXact(true);
2067 * Let ON COMMIT management do its thing (must happen after closing
2068 * cursors, to avoid dangling-reference problems)
2070 PreCommit_on_commit_actions();
2072 /* close large objects before lower-level cleanup */
2073 AtEOXact_LargeObject(true);
2076 * Mark serializable transaction as complete for predicate locking
2077 * purposes. This should be done as late as we can put it and still allow
2078 * errors to be raised for failure patterns found at commit.
2080 PreCommit_CheckForSerializationFailure();
2082 /* NOTIFY will be handled below */
2085 * Don't allow PREPARE TRANSACTION if we've accessed a temporary table in
2086 * this transaction. Having the prepared xact hold locks on another
2087 * backend's temp table seems a bad idea --- for instance it would prevent
2088 * the backend from exiting. There are other problems too, such as how to
2089 * clean up the source backend's local buffers and ON COMMIT state if the
2090 * prepared xact includes a DROP of a temp table.
2092 * We must check this after executing any ON COMMIT actions, because they
2093 * might still access a temp relation.
2095 * XXX In principle this could be relaxed to allow some useful special
2096 * cases, such as a temp table created and dropped all within the
2097 * transaction. That seems to require much more bookkeeping though.
2099 if (MyXactAccessedTempRel)
2101 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2102 errmsg("cannot PREPARE a transaction that has operated on temporary tables")));
2105 * Likewise, don't allow PREPARE after pg_export_snapshot. This could be
2106 * supported if we added cleanup logic to twophase.c, but for now it
2107 * doesn't seem worth the trouble.
2109 if (XactHasExportedSnapshots())
2111 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2112 errmsg("cannot PREPARE a transaction that has exported snapshots")));
2114 /* Prevent cancel/die interrupt while cleaning up */
2118 * set the current transaction state information appropriately during
2119 * prepare processing
2121 s->state = TRANS_PREPARE;
2123 prepared_at = GetCurrentTimestamp();
2125 /* Tell bufmgr and smgr to prepare for commit */
2129 * Reserve the GID for this transaction. This could fail if the requested
2130 * GID is invalid or already in use.
2132 gxact = MarkAsPreparing(xid, prepareGID, prepared_at,
2133 GetUserId(), MyDatabaseId);
2137 * Collect data for the 2PC state file. Note that in general, no actual
2138 * state change should happen in the called modules during this step,
2139 * since it's still possible to fail before commit, and in that case we
2140 * want transaction abort to be able to clean up. (In particular, the
2141 * AtPrepare routines may error out if they find cases they cannot
2142 * handle.) State cleanup should happen in the PostPrepare routines
2143 * below. However, some modules can go ahead and clear state here because
2144 * they wouldn't do anything with it during abort anyway.
2146 * Note: because the 2PC state file records will be replayed in the same
2147 * order they are made, the order of these calls has to match the order in
2148 * which we want things to happen during COMMIT PREPARED or ROLLBACK
2149 * PREPARED; in particular, pay attention to whether things should happen
2150 * before or after releasing the transaction's locks.
2152 StartPrepare(gxact);
2156 AtPrepare_PredicateLocks();
2158 AtPrepare_MultiXact();
2159 AtPrepare_RelationMap();
2162 * Here is where we really truly prepare.
2164 * We have to record transaction prepares even if we didn't make any
2165 * updates, because the transaction manager might get confused if we lose
2166 * a global transaction.
2171 * Now we clean up backend-internal state and release internal resources.
2174 /* Reset XactLastRecEnd until the next transaction writes something */
2178 * Let others know about no transaction in progress by me. This has to be
2179 * done *after* the prepared transaction has been marked valid, else
2180 * someone may think it is unlocked and recyclable.
2182 ProcArrayClearTransaction(MyProc);
2185 * This is all post-transaction cleanup. Note that if an error is raised
2186 * here, it's too late to abort the transaction. This should be just
2187 * noncritical resource releasing. See notes in CommitTransaction.
2190 CallXactCallbacks(XACT_EVENT_PREPARE);
2192 ResourceOwnerRelease(TopTransactionResourceOwner,
2193 RESOURCE_RELEASE_BEFORE_LOCKS,
2196 /* Check we've released all buffer pins */
2197 AtEOXact_Buffers(true);
2199 /* Clean up the relation cache */
2200 AtEOXact_RelationCache(true);
2202 /* notify doesn't need a postprepare call */
2204 PostPrepare_PgStat();
2206 PostPrepare_Inval();
2210 PostPrepare_MultiXact(xid);
2212 PostPrepare_Locks(xid);
2213 PostPrepare_PredicateLocks(xid);
2215 ResourceOwnerRelease(TopTransactionResourceOwner,
2216 RESOURCE_RELEASE_LOCKS,
2218 ResourceOwnerRelease(TopTransactionResourceOwner,
2219 RESOURCE_RELEASE_AFTER_LOCKS,
2222 /* Check we've released all catcache entries */
2223 AtEOXact_CatCache(true);
2225 /* PREPARE acts the same as COMMIT as far as GUC is concerned */
2226 AtEOXact_GUC(true, 1);
2228 AtEOXact_on_commit_actions(true);
2229 AtEOXact_Namespace(true);
2232 AtEOXact_ComboCid();
2233 AtEOXact_HashTables(true);
2234 /* don't call AtEOXact_PgStat here */
2235 AtEOXact_Snapshot(true);
2237 CurrentResourceOwner = NULL;
2238 ResourceOwnerDelete(TopTransactionResourceOwner);
2239 s->curTransactionOwner = NULL;
2240 CurTransactionResourceOwner = NULL;
2241 TopTransactionResourceOwner = NULL;
2245 s->transactionId = InvalidTransactionId;
2246 s->subTransactionId = InvalidSubTransactionId;
2247 s->nestingLevel = 0;
2248 s->gucNestLevel = 0;
2249 s->childXids = NULL;
2251 s->maxChildXids = 0;
2254 * done with 1st phase commit processing, set current transaction state
2257 s->state = TRANS_DEFAULT;
2259 RESUME_INTERRUPTS();
2267 AbortTransaction(void)
2269 TransactionState s = CurrentTransactionState;
2270 TransactionId latestXid;
2272 /* Prevent cancel/die interrupt while cleaning up */
2275 /* Make sure we have a valid memory context and resource owner */
2277 AtAbort_ResourceOwner();
2280 * Release any LW locks we might be holding as quickly as possible.
2281 * (Regular locks, however, must be held till we finish aborting.)
2282 * Releasing LW locks is critical since we might try to grab them again
2283 * while cleaning up!
2287 /* Clean up buffer I/O and buffer context locks, too */
2292 * Also clean up any open wait for lock, since the lock manager will choke
2293 * if we try to wait for another lock before doing this.
2298 * check the current transaction state
2300 if (s->state != TRANS_INPROGRESS && s->state != TRANS_PREPARE)
2301 elog(WARNING, "AbortTransaction while in %s state",
2302 TransStateAsString(s->state));
2303 Assert(s->parent == NULL);
2306 * set the current transaction state information appropriately during the
2309 s->state = TRANS_ABORT;
2312 * Reset user ID which might have been changed transiently. We need this
2313 * to clean up in case control escaped out of a SECURITY DEFINER function
2314 * or other local change of CurrentUserId; therefore, the prior value of
2315 * SecurityRestrictionContext also needs to be restored.
2317 * (Note: it is not necessary to restore session authorization or role
2318 * settings here because those can only be changed via GUC, and GUC will
2319 * take care of rolling them back if need be.)
2321 SetUserIdAndSecContext(s->prevUser, s->prevSecContext);
2324 * do abort processing
2326 AfterTriggerEndXact(false); /* 'false' means it's abort */
2328 AtEOXact_LargeObject(false);
2330 AtEOXact_RelationMap(false);
2333 * Advertise the fact that we aborted in pg_clog (assuming that we got as
2334 * far as assigning an XID to advertise).
2336 latestXid = RecordTransactionAbort(false);
2338 TRACE_POSTGRESQL_TRANSACTION_ABORT(MyProc->lxid);
2341 * Let others know about no transaction in progress by me. Note that this
2342 * must be done _before_ releasing locks we hold and _after_
2343 * RecordTransactionAbort.
2345 ProcArrayEndTransaction(MyProc, latestXid);
2348 * Post-abort cleanup. See notes in CommitTransaction() concerning
2349 * ordering. We can skip all of it if the transaction failed before
2350 * creating a resource owner.
2352 if (TopTransactionResourceOwner != NULL)
2354 CallXactCallbacks(XACT_EVENT_ABORT);
2356 ResourceOwnerRelease(TopTransactionResourceOwner,
2357 RESOURCE_RELEASE_BEFORE_LOCKS,
2359 AtEOXact_Buffers(false);
2360 AtEOXact_RelationCache(false);
2361 AtEOXact_Inval(false);
2362 AtEOXact_MultiXact();
2363 ResourceOwnerRelease(TopTransactionResourceOwner,
2364 RESOURCE_RELEASE_LOCKS,
2366 ResourceOwnerRelease(TopTransactionResourceOwner,
2367 RESOURCE_RELEASE_AFTER_LOCKS,
2369 smgrDoPendingDeletes(false);
2370 AtEOXact_CatCache(false);
2372 AtEOXact_GUC(false, 1);
2373 AtEOXact_SPI(false);
2374 AtEOXact_on_commit_actions(false);
2375 AtEOXact_Namespace(false);
2378 AtEOXact_ComboCid();
2379 AtEOXact_HashTables(false);
2380 AtEOXact_PgStat(false);
2381 pgstat_report_xact_timestamp(0);
2385 * State remains TRANS_ABORT until CleanupTransaction().
2387 RESUME_INTERRUPTS();
2391 * CleanupTransaction
2394 CleanupTransaction(void)
2396 TransactionState s = CurrentTransactionState;
2399 * State should still be TRANS_ABORT from AbortTransaction().
2401 if (s->state != TRANS_ABORT)
2402 elog(FATAL, "CleanupTransaction: unexpected state %s",
2403 TransStateAsString(s->state));
2406 * do abort cleanup processing
2408 AtCleanup_Portals(); /* now safe to release portal memory */
2409 AtEOXact_Snapshot(false); /* and release the transaction's snapshots */
2411 CurrentResourceOwner = NULL; /* and resource owner */
2412 if (TopTransactionResourceOwner)
2413 ResourceOwnerDelete(TopTransactionResourceOwner);
2414 s->curTransactionOwner = NULL;
2415 CurTransactionResourceOwner = NULL;
2416 TopTransactionResourceOwner = NULL;
2418 AtCleanup_Memory(); /* and transaction memory */
2420 s->transactionId = InvalidTransactionId;
2421 s->subTransactionId = InvalidSubTransactionId;
2422 s->nestingLevel = 0;
2423 s->gucNestLevel = 0;
2424 s->childXids = NULL;
2426 s->maxChildXids = 0;
2429 * done with abort processing, set current transaction state back to
2432 s->state = TRANS_DEFAULT;
2436 * StartTransactionCommand
2439 StartTransactionCommand(void)
2441 TransactionState s = CurrentTransactionState;
2443 switch (s->blockState)
2446 * if we aren't in a transaction block, we just do our usual start
2449 case TBLOCK_DEFAULT:
2451 s->blockState = TBLOCK_STARTED;
2455 * We are somewhere in a transaction block or subtransaction and
2456 * about to start a new command. For now we do nothing, but
2457 * someday we may do command-local resource initialization. (Note
2458 * that any needed CommandCounterIncrement was done by the
2459 * previous CommitTransactionCommand.)
2461 case TBLOCK_INPROGRESS:
2462 case TBLOCK_SUBINPROGRESS:
2466 * Here we are in a failed transaction block (one of the commands
2467 * caused an abort) so we do nothing but remain in the abort
2468 * state. Eventually we will get a ROLLBACK command which will
2469 * get us out of this state. (It is up to other code to ensure
2470 * that no commands other than ROLLBACK will be processed in these
2474 case TBLOCK_SUBABORT:
2477 /* These cases are invalid. */
2478 case TBLOCK_STARTED:
2480 case TBLOCK_SUBBEGIN:
2482 case TBLOCK_SUBRELEASE:
2483 case TBLOCK_SUBCOMMIT:
2484 case TBLOCK_ABORT_END:
2485 case TBLOCK_SUBABORT_END:
2486 case TBLOCK_ABORT_PENDING:
2487 case TBLOCK_SUBABORT_PENDING:
2488 case TBLOCK_SUBRESTART:
2489 case TBLOCK_SUBABORT_RESTART:
2490 case TBLOCK_PREPARE:
2491 elog(ERROR, "StartTransactionCommand: unexpected state %s",
2492 BlockStateAsString(s->blockState));
2497 * We must switch to CurTransactionContext before returning. This is
2498 * already done if we called StartTransaction, otherwise not.
2500 Assert(CurTransactionContext != NULL);
2501 MemoryContextSwitchTo(CurTransactionContext);
2505 * CommitTransactionCommand
2508 CommitTransactionCommand(void)
2510 TransactionState s = CurrentTransactionState;
2512 switch (s->blockState)
2515 * This shouldn't happen, because it means the previous
2516 * StartTransactionCommand didn't set the STARTED state
2519 case TBLOCK_DEFAULT:
2520 elog(FATAL, "CommitTransactionCommand: unexpected state %s",
2521 BlockStateAsString(s->blockState));
2525 * If we aren't in a transaction block, just do our usual
2526 * transaction commit, and return to the idle state.
2528 case TBLOCK_STARTED:
2529 CommitTransaction();
2530 s->blockState = TBLOCK_DEFAULT;
2534 * We are completing a "BEGIN TRANSACTION" command, so we change
2535 * to the "transaction block in progress" state and return. (We
2536 * assume the BEGIN did nothing to the database, so we need no
2537 * CommandCounterIncrement.)
2540 s->blockState = TBLOCK_INPROGRESS;
2544 * This is the case when we have finished executing a command
2545 * someplace within a transaction block. We increment the command
2546 * counter and return.
2548 case TBLOCK_INPROGRESS:
2549 case TBLOCK_SUBINPROGRESS:
2550 CommandCounterIncrement();
2554 * We are completing a "COMMIT" command. Do it and return to the
2558 CommitTransaction();
2559 s->blockState = TBLOCK_DEFAULT;
2563 * Here we are in the middle of a transaction block but one of the
2564 * commands caused an abort so we do nothing but remain in the
2565 * abort state. Eventually we will get a ROLLBACK comand.
2568 case TBLOCK_SUBABORT:
2572 * Here we were in an aborted transaction block and we just got
2573 * the ROLLBACK command from the user, so clean up the
2574 * already-aborted transaction and return to the idle state.
2576 case TBLOCK_ABORT_END:
2577 CleanupTransaction();
2578 s->blockState = TBLOCK_DEFAULT;
2582 * Here we were in a perfectly good transaction block but the user
2583 * told us to ROLLBACK anyway. We have to abort the transaction
2584 * and then clean up.
2586 case TBLOCK_ABORT_PENDING:
2588 CleanupTransaction();
2589 s->blockState = TBLOCK_DEFAULT;
2593 * We are completing a "PREPARE TRANSACTION" command. Do it and
2594 * return to the idle state.
2596 case TBLOCK_PREPARE:
2597 PrepareTransaction();
2598 s->blockState = TBLOCK_DEFAULT;
2602 * We were just issued a SAVEPOINT inside a transaction block.
2603 * Start a subtransaction. (DefineSavepoint already did
2604 * PushTransaction, so as to have someplace to put the SUBBEGIN
2607 case TBLOCK_SUBBEGIN:
2608 StartSubTransaction();
2609 s->blockState = TBLOCK_SUBINPROGRESS;
2613 * We were issued a RELEASE command, so we end the current
2614 * subtransaction and return to the parent transaction. The parent
2615 * might be ended too, so repeat till we find an INPROGRESS
2616 * transaction or subtransaction.
2618 case TBLOCK_SUBRELEASE:
2621 CommitSubTransaction();
2622 s = CurrentTransactionState; /* changed by pop */
2623 } while (s->blockState == TBLOCK_SUBRELEASE);
2625 Assert(s->blockState == TBLOCK_INPROGRESS ||
2626 s->blockState == TBLOCK_SUBINPROGRESS);
2630 * We were issued a COMMIT, so we end the current subtransaction
2631 * hierarchy and perform final commit. We do this by rolling up
2632 * any subtransactions into their parent, which leads to O(N^2)
2633 * operations with respect to resource owners - this isn't that
2634 * bad until we approach a thousands of savepoints but is
2635 * necessary for correctness should after triggers create new
2638 case TBLOCK_SUBCOMMIT:
2641 CommitSubTransaction();
2642 s = CurrentTransactionState; /* changed by pop */
2643 } while (s->blockState == TBLOCK_SUBCOMMIT);
2644 /* If we had a COMMIT command, finish off the main xact too */
2645 if (s->blockState == TBLOCK_END)
2647 Assert(s->parent == NULL);
2648 CommitTransaction();
2649 s->blockState = TBLOCK_DEFAULT;
2651 else if (s->blockState == TBLOCK_PREPARE)
2653 Assert(s->parent == NULL);
2654 PrepareTransaction();
2655 s->blockState = TBLOCK_DEFAULT;
2658 elog(ERROR, "CommitTransactionCommand: unexpected state %s",
2659 BlockStateAsString(s->blockState));
2663 * The current already-failed subtransaction is ending due to a
2664 * ROLLBACK or ROLLBACK TO command, so pop it and recursively
2665 * examine the parent (which could be in any of several states).
2667 case TBLOCK_SUBABORT_END:
2668 CleanupSubTransaction();
2669 CommitTransactionCommand();
2673 * As above, but it's not dead yet, so abort first.
2675 case TBLOCK_SUBABORT_PENDING:
2676 AbortSubTransaction();
2677 CleanupSubTransaction();
2678 CommitTransactionCommand();
2682 * The current subtransaction is the target of a ROLLBACK TO
2683 * command. Abort and pop it, then start a new subtransaction
2684 * with the same name.
2686 case TBLOCK_SUBRESTART:
2691 /* save name and keep Cleanup from freeing it */
2694 savepointLevel = s->savepointLevel;
2696 AbortSubTransaction();
2697 CleanupSubTransaction();
2699 DefineSavepoint(NULL);
2700 s = CurrentTransactionState; /* changed by push */
2702 s->savepointLevel = savepointLevel;
2704 /* This is the same as TBLOCK_SUBBEGIN case */
2705 AssertState(s->blockState == TBLOCK_SUBBEGIN);
2706 StartSubTransaction();
2707 s->blockState = TBLOCK_SUBINPROGRESS;
2712 * Same as above, but the subtransaction had already failed, so we
2713 * don't need AbortSubTransaction.
2715 case TBLOCK_SUBABORT_RESTART:
2720 /* save name and keep Cleanup from freeing it */
2723 savepointLevel = s->savepointLevel;
2725 CleanupSubTransaction();
2727 DefineSavepoint(NULL);
2728 s = CurrentTransactionState; /* changed by push */
2730 s->savepointLevel = savepointLevel;
2732 /* This is the same as TBLOCK_SUBBEGIN case */
2733 AssertState(s->blockState == TBLOCK_SUBBEGIN);
2734 StartSubTransaction();
2735 s->blockState = TBLOCK_SUBINPROGRESS;
2742 * AbortCurrentTransaction
2745 AbortCurrentTransaction(void)
2747 TransactionState s = CurrentTransactionState;
2749 switch (s->blockState)
2751 case TBLOCK_DEFAULT:
2752 if (s->state == TRANS_DEFAULT)
2754 /* we are idle, so nothing to do */
2759 * We can get here after an error during transaction start
2760 * (state will be TRANS_START). Need to clean up the
2761 * incompletely started transaction. First, adjust the
2762 * low-level state to suppress warning message from
2765 if (s->state == TRANS_START)
2766 s->state = TRANS_INPROGRESS;
2768 CleanupTransaction();
2773 * if we aren't in a transaction block, we just do the basic abort
2774 * & cleanup transaction.
2776 case TBLOCK_STARTED:
2778 CleanupTransaction();
2779 s->blockState = TBLOCK_DEFAULT;
2783 * If we are in TBLOCK_BEGIN it means something screwed up right
2784 * after reading "BEGIN TRANSACTION". We assume that the user
2785 * will interpret the error as meaning the BEGIN failed to get him
2786 * into a transaction block, so we should abort and return to idle
2791 CleanupTransaction();
2792 s->blockState = TBLOCK_DEFAULT;
2796 * We are somewhere in a transaction block and we've gotten a
2797 * failure, so we abort the transaction and set up the persistent
2798 * ABORT state. We will stay in ABORT until we get a ROLLBACK.
2800 case TBLOCK_INPROGRESS:
2802 s->blockState = TBLOCK_ABORT;
2803 /* CleanupTransaction happens when we exit TBLOCK_ABORT_END */
2807 * Here, we failed while trying to COMMIT. Clean up the
2808 * transaction and return to idle state (we do not want to stay in
2813 CleanupTransaction();
2814 s->blockState = TBLOCK_DEFAULT;
2818 * Here, we are already in an aborted transaction state and are
2819 * waiting for a ROLLBACK, but for some reason we failed again! So
2820 * we just remain in the abort state.
2823 case TBLOCK_SUBABORT:
2827 * We are in a failed transaction and we got the ROLLBACK command.
2828 * We have already aborted, we just need to cleanup and go to idle
2831 case TBLOCK_ABORT_END:
2832 CleanupTransaction();
2833 s->blockState = TBLOCK_DEFAULT;
2837 * We are in a live transaction and we got a ROLLBACK command.
2838 * Abort, cleanup, go to idle state.
2840 case TBLOCK_ABORT_PENDING:
2842 CleanupTransaction();
2843 s->blockState = TBLOCK_DEFAULT;
2847 * Here, we failed while trying to PREPARE. Clean up the
2848 * transaction and return to idle state (we do not want to stay in
2851 case TBLOCK_PREPARE:
2853 CleanupTransaction();
2854 s->blockState = TBLOCK_DEFAULT;
2858 * We got an error inside a subtransaction. Abort just the
2859 * subtransaction, and go to the persistent SUBABORT state until
2862 case TBLOCK_SUBINPROGRESS:
2863 AbortSubTransaction();
2864 s->blockState = TBLOCK_SUBABORT;
2868 * If we failed while trying to create a subtransaction, clean up
2869 * the broken subtransaction and abort the parent. The same
2870 * applies if we get a failure while ending a subtransaction.
2872 case TBLOCK_SUBBEGIN:
2873 case TBLOCK_SUBRELEASE:
2874 case TBLOCK_SUBCOMMIT:
2875 case TBLOCK_SUBABORT_PENDING:
2876 case TBLOCK_SUBRESTART:
2877 AbortSubTransaction();
2878 CleanupSubTransaction();
2879 AbortCurrentTransaction();
2883 * Same as above, except the Abort() was already done.
2885 case TBLOCK_SUBABORT_END:
2886 case TBLOCK_SUBABORT_RESTART:
2887 CleanupSubTransaction();
2888 AbortCurrentTransaction();
2894 * PreventTransactionChain
2896 * This routine is to be called by statements that must not run inside
2897 * a transaction block, typically because they have non-rollback-able
2898 * side effects or do internal commits.
2900 * If we have already started a transaction block, issue an error; also issue
2901 * an error if we appear to be running inside a user-defined function (which
2902 * could issue more commands and possibly cause a failure after the statement
2903 * completes). Subtransactions are verboten too.
2905 * isTopLevel: passed down from ProcessUtility to determine whether we are
2906 * inside a function or multi-query querystring. (We will always fail if
2907 * this is false, but it's convenient to centralize the check here instead of
2908 * making callers do it.)
2909 * stmtType: statement type name, for error messages.
2912 PreventTransactionChain(bool isTopLevel, const char *stmtType)
2915 * xact block already started?
2917 if (IsTransactionBlock())
2919 (errcode(ERRCODE_ACTIVE_SQL_TRANSACTION),
2920 /* translator: %s represents an SQL statement name */
2921 errmsg("%s cannot run inside a transaction block",
2927 if (IsSubTransaction())
2929 (errcode(ERRCODE_ACTIVE_SQL_TRANSACTION),
2930 /* translator: %s represents an SQL statement name */
2931 errmsg("%s cannot run inside a subtransaction",
2935 * inside a function call?
2939 (errcode(ERRCODE_ACTIVE_SQL_TRANSACTION),
2940 /* translator: %s represents an SQL statement name */
2941 errmsg("%s cannot be executed from a function or multi-command string",
2944 /* If we got past IsTransactionBlock test, should be in default state */
2945 if (CurrentTransactionState->blockState != TBLOCK_DEFAULT &&
2946 CurrentTransactionState->blockState != TBLOCK_STARTED)
2947 elog(FATAL, "cannot prevent transaction chain");
2952 * RequireTransactionChain
2954 * This routine is to be called by statements that must run inside
2955 * a transaction block, because they have no effects that persist past
2956 * transaction end (and so calling them outside a transaction block
2957 * is presumably an error). DECLARE CURSOR is an example.
2959 * If we appear to be running inside a user-defined function, we do not
2960 * issue an error, since the function could issue more commands that make
2961 * use of the current statement's results. Likewise subtransactions.
2962 * Thus this is an inverse for PreventTransactionChain.
2964 * isTopLevel: passed down from ProcessUtility to determine whether we are
2965 * inside a function.
2966 * stmtType: statement type name, for error messages.
2969 RequireTransactionChain(bool isTopLevel, const char *stmtType)
2972 * xact block already started?
2974 if (IsTransactionBlock())
2980 if (IsSubTransaction())
2984 * inside a function call?
2990 (errcode(ERRCODE_NO_ACTIVE_SQL_TRANSACTION),
2991 /* translator: %s represents an SQL statement name */
2992 errmsg("%s can only be used in transaction blocks",
2997 * IsInTransactionChain
2999 * This routine is for statements that need to behave differently inside
3000 * a transaction block than when running as single commands. ANALYZE is
3001 * currently the only example.
3003 * isTopLevel: passed down from ProcessUtility to determine whether we are
3004 * inside a function.
3007 IsInTransactionChain(bool isTopLevel)
3010 * Return true on same conditions that would make PreventTransactionChain
3013 if (IsTransactionBlock())
3016 if (IsSubTransaction())
3022 if (CurrentTransactionState->blockState != TBLOCK_DEFAULT &&
3023 CurrentTransactionState->blockState != TBLOCK_STARTED)
3031 * Register or deregister callback functions for start- and end-of-xact
3034 * These functions are intended for use by dynamically loaded modules.
3035 * For built-in modules we generally just hardwire the appropriate calls
3036 * (mainly because it's easier to control the order that way, where needed).
3038 * At transaction end, the callback occurs post-commit or post-abort, so the
3039 * callback functions can only do noncritical cleanup.
3042 RegisterXactCallback(XactCallback callback, void *arg)
3044 XactCallbackItem *item;
3046 item = (XactCallbackItem *)
3047 MemoryContextAlloc(TopMemoryContext, sizeof(XactCallbackItem));
3048 item->callback = callback;
3050 item->next = Xact_callbacks;
3051 Xact_callbacks = item;
3055 UnregisterXactCallback(XactCallback callback, void *arg)
3057 XactCallbackItem *item;
3058 XactCallbackItem *prev;
3061 for (item = Xact_callbacks; item; prev = item, item = item->next)
3063 if (item->callback == callback && item->arg == arg)
3066 prev->next = item->next;
3068 Xact_callbacks = item->next;
3076 CallXactCallbacks(XactEvent event)
3078 XactCallbackItem *item;
3080 for (item = Xact_callbacks; item; item = item->next)
3081 (*item->callback) (event, item->arg);
3086 * Register or deregister callback functions for start- and end-of-subxact
3089 * Pretty much same as above, but for subtransaction events.
3091 * At subtransaction end, the callback occurs post-subcommit or post-subabort,
3092 * so the callback functions can only do noncritical cleanup. At
3093 * subtransaction start, the callback is called when the subtransaction has
3094 * finished initializing.
3097 RegisterSubXactCallback(SubXactCallback callback, void *arg)
3099 SubXactCallbackItem *item;
3101 item = (SubXactCallbackItem *)
3102 MemoryContextAlloc(TopMemoryContext, sizeof(SubXactCallbackItem));
3103 item->callback = callback;
3105 item->next = SubXact_callbacks;
3106 SubXact_callbacks = item;
3110 UnregisterSubXactCallback(SubXactCallback callback, void *arg)
3112 SubXactCallbackItem *item;
3113 SubXactCallbackItem *prev;
3116 for (item = SubXact_callbacks; item; prev = item, item = item->next)
3118 if (item->callback == callback && item->arg == arg)
3121 prev->next = item->next;
3123 SubXact_callbacks = item->next;
3131 CallSubXactCallbacks(SubXactEvent event,
3132 SubTransactionId mySubid,
3133 SubTransactionId parentSubid)
3135 SubXactCallbackItem *item;
3137 for (item = SubXact_callbacks; item; item = item->next)
3138 (*item->callback) (event, mySubid, parentSubid, item->arg);
3142 /* ----------------------------------------------------------------
3143 * transaction block support
3144 * ----------------------------------------------------------------
3148 * BeginTransactionBlock
3149 * This executes a BEGIN command.
3152 BeginTransactionBlock(void)
3154 TransactionState s = CurrentTransactionState;
3156 switch (s->blockState)
3159 * We are not inside a transaction block, so allow one to begin.
3161 case TBLOCK_STARTED:
3162 s->blockState = TBLOCK_BEGIN;
3166 * Already a transaction block in progress.
3168 case TBLOCK_INPROGRESS:
3169 case TBLOCK_SUBINPROGRESS:
3171 case TBLOCK_SUBABORT:
3173 (errcode(ERRCODE_ACTIVE_SQL_TRANSACTION),
3174 errmsg("there is already a transaction in progress")));
3177 /* These cases are invalid. */
3178 case TBLOCK_DEFAULT:
3180 case TBLOCK_SUBBEGIN:
3182 case TBLOCK_SUBRELEASE:
3183 case TBLOCK_SUBCOMMIT:
3184 case TBLOCK_ABORT_END:
3185 case TBLOCK_SUBABORT_END:
3186 case TBLOCK_ABORT_PENDING:
3187 case TBLOCK_SUBABORT_PENDING:
3188 case TBLOCK_SUBRESTART:
3189 case TBLOCK_SUBABORT_RESTART:
3190 case TBLOCK_PREPARE:
3191 elog(FATAL, "BeginTransactionBlock: unexpected state %s",
3192 BlockStateAsString(s->blockState));
3198 * PrepareTransactionBlock
3199 * This executes a PREPARE command.
3201 * Since PREPARE may actually do a ROLLBACK, the result indicates what
3202 * happened: TRUE for PREPARE, FALSE for ROLLBACK.
3204 * Note that we don't actually do anything here except change blockState.
3205 * The real work will be done in the upcoming PrepareTransaction().
3206 * We do it this way because it's not convenient to change memory context,
3207 * resource owner, etc while executing inside a Portal.
3210 PrepareTransactionBlock(char *gid)
3215 /* Set up to commit the current transaction */
3216 result = EndTransactionBlock();
3218 /* If successful, change outer tblock state to PREPARE */
3221 s = CurrentTransactionState;
3223 while (s->parent != NULL)
3226 if (s->blockState == TBLOCK_END)
3228 /* Save GID where PrepareTransaction can find it again */
3229 prepareGID = MemoryContextStrdup(TopTransactionContext, gid);
3231 s->blockState = TBLOCK_PREPARE;
3236 * ignore case where we are not in a transaction;
3237 * EndTransactionBlock already issued a warning.
3239 Assert(s->blockState == TBLOCK_STARTED);
3240 /* Don't send back a PREPARE result tag... */
3249 * EndTransactionBlock
3250 * This executes a COMMIT command.
3252 * Since COMMIT may actually do a ROLLBACK, the result indicates what
3253 * happened: TRUE for COMMIT, FALSE for ROLLBACK.
3255 * Note that we don't actually do anything here except change blockState.
3256 * The real work will be done in the upcoming CommitTransactionCommand().
3257 * We do it this way because it's not convenient to change memory context,
3258 * resource owner, etc while executing inside a Portal.
3261 EndTransactionBlock(void)
3263 TransactionState s = CurrentTransactionState;
3264 bool result = false;
3266 switch (s->blockState)
3269 * We are in a transaction block, so tell CommitTransactionCommand
3272 case TBLOCK_INPROGRESS:
3273 s->blockState = TBLOCK_END;
3278 * We are in a failed transaction block. Tell
3279 * CommitTransactionCommand it's time to exit the block.
3282 s->blockState = TBLOCK_ABORT_END;
3286 * We are in a live subtransaction block. Set up to subcommit all
3287 * open subtransactions and then commit the main transaction.
3289 case TBLOCK_SUBINPROGRESS:
3290 while (s->parent != NULL)
3292 if (s->blockState == TBLOCK_SUBINPROGRESS)
3293 s->blockState = TBLOCK_SUBCOMMIT;
3295 elog(FATAL, "EndTransactionBlock: unexpected state %s",
3296 BlockStateAsString(s->blockState));
3299 if (s->blockState == TBLOCK_INPROGRESS)
3300 s->blockState = TBLOCK_END;
3302 elog(FATAL, "EndTransactionBlock: unexpected state %s",
3303 BlockStateAsString(s->blockState));
3308 * Here we are inside an aborted subtransaction. Treat the COMMIT
3309 * as ROLLBACK: set up to abort everything and exit the main
3312 case TBLOCK_SUBABORT:
3313 while (s->parent != NULL)
3315 if (s->blockState == TBLOCK_SUBINPROGRESS)
3316 s->blockState = TBLOCK_SUBABORT_PENDING;
3317 else if (s->blockState == TBLOCK_SUBABORT)
3318 s->blockState = TBLOCK_SUBABORT_END;
3320 elog(FATAL, "EndTransactionBlock: unexpected state %s",
3321 BlockStateAsString(s->blockState));
3324 if (s->blockState == TBLOCK_INPROGRESS)
3325 s->blockState = TBLOCK_ABORT_PENDING;
3326 else if (s->blockState == TBLOCK_ABORT)
3327 s->blockState = TBLOCK_ABORT_END;
3329 elog(FATAL, "EndTransactionBlock: unexpected state %s",
3330 BlockStateAsString(s->blockState));
3334 * The user issued COMMIT when not inside a transaction. Issue a
3335 * WARNING, staying in TBLOCK_STARTED state. The upcoming call to
3336 * CommitTransactionCommand() will then close the transaction and
3337 * put us back into the default state.
3339 case TBLOCK_STARTED:
3341 (errcode(ERRCODE_NO_ACTIVE_SQL_TRANSACTION),
3342 errmsg("there is no transaction in progress")));
3346 /* These cases are invalid. */
3347 case TBLOCK_DEFAULT:
3349 case TBLOCK_SUBBEGIN:
3351 case TBLOCK_SUBRELEASE:
3352 case TBLOCK_SUBCOMMIT:
3353 case TBLOCK_ABORT_END:
3354 case TBLOCK_SUBABORT_END:
3355 case TBLOCK_ABORT_PENDING:
3356 case TBLOCK_SUBABORT_PENDING:
3357 case TBLOCK_SUBRESTART:
3358 case TBLOCK_SUBABORT_RESTART:
3359 case TBLOCK_PREPARE:
3360 elog(FATAL, "EndTransactionBlock: unexpected state %s",
3361 BlockStateAsString(s->blockState));
3369 * UserAbortTransactionBlock
3370 * This executes a ROLLBACK command.
3372 * As above, we don't actually do anything here except change blockState.
3375 UserAbortTransactionBlock(void)
3377 TransactionState s = CurrentTransactionState;
3379 switch (s->blockState)
3382 * We are inside a transaction block and we got a ROLLBACK command
3383 * from the user, so tell CommitTransactionCommand to abort and
3384 * exit the transaction block.
3386 case TBLOCK_INPROGRESS:
3387 s->blockState = TBLOCK_ABORT_PENDING;
3391 * We are inside a failed transaction block and we got a ROLLBACK
3392 * command from the user. Abort processing is already done, so
3393 * CommitTransactionCommand just has to cleanup and go back to
3397 s->blockState = TBLOCK_ABORT_END;
3401 * We are inside a subtransaction. Mark everything up to top
3402 * level as exitable.
3404 case TBLOCK_SUBINPROGRESS:
3405 case TBLOCK_SUBABORT:
3406 while (s->parent != NULL)
3408 if (s->blockState == TBLOCK_SUBINPROGRESS)
3409 s->blockState = TBLOCK_SUBABORT_PENDING;
3410 else if (s->blockState == TBLOCK_SUBABORT)
3411 s->blockState = TBLOCK_SUBABORT_END;
3413 elog(FATAL, "UserAbortTransactionBlock: unexpected state %s",
3414 BlockStateAsString(s->blockState));
3417 if (s->blockState == TBLOCK_INPROGRESS)
3418 s->blockState = TBLOCK_ABORT_PENDING;
3419 else if (s->blockState == TBLOCK_ABORT)
3420 s->blockState = TBLOCK_ABORT_END;
3422 elog(FATAL, "UserAbortTransactionBlock: unexpected state %s",
3423 BlockStateAsString(s->blockState));
3427 * The user issued ABORT when not inside a transaction. Issue a
3428 * NOTICE and go to abort state. The upcoming call to
3429 * CommitTransactionCommand() will then put us back into the
3432 case TBLOCK_STARTED:
3434 (errcode(ERRCODE_NO_ACTIVE_SQL_TRANSACTION),
3435 errmsg("there is no transaction in progress")));
3436 s->blockState = TBLOCK_ABORT_PENDING;
3439 /* These cases are invalid. */
3440 case TBLOCK_DEFAULT:
3442 case TBLOCK_SUBBEGIN:
3444 case TBLOCK_SUBRELEASE:
3445 case TBLOCK_SUBCOMMIT:
3446 case TBLOCK_ABORT_END:
3447 case TBLOCK_SUBABORT_END:
3448 case TBLOCK_ABORT_PENDING:
3449 case TBLOCK_SUBABORT_PENDING:
3450 case TBLOCK_SUBRESTART:
3451 case TBLOCK_SUBABORT_RESTART:
3452 case TBLOCK_PREPARE:
3453 elog(FATAL, "UserAbortTransactionBlock: unexpected state %s",
3454 BlockStateAsString(s->blockState));
3461 * This executes a SAVEPOINT command.
3464 DefineSavepoint(char *name)
3466 TransactionState s = CurrentTransactionState;
3468 switch (s->blockState)
3470 case TBLOCK_INPROGRESS:
3471 case TBLOCK_SUBINPROGRESS:
3472 /* Normal subtransaction start */
3474 s = CurrentTransactionState; /* changed by push */
3477 * Savepoint names, like the TransactionState block itself, live
3478 * in TopTransactionContext.
3481 s->name = MemoryContextStrdup(TopTransactionContext, name);
3484 /* These cases are invalid. */
3485 case TBLOCK_DEFAULT:
3486 case TBLOCK_STARTED:
3488 case TBLOCK_SUBBEGIN:
3490 case TBLOCK_SUBRELEASE:
3491 case TBLOCK_SUBCOMMIT:
3493 case TBLOCK_SUBABORT:
3494 case TBLOCK_ABORT_END:
3495 case TBLOCK_SUBABORT_END:
3496 case TBLOCK_ABORT_PENDING:
3497 case TBLOCK_SUBABORT_PENDING:
3498 case TBLOCK_SUBRESTART:
3499 case TBLOCK_SUBABORT_RESTART:
3500 case TBLOCK_PREPARE:
3501 elog(FATAL, "DefineSavepoint: unexpected state %s",
3502 BlockStateAsString(s->blockState));
3509 * This executes a RELEASE command.
3511 * As above, we don't actually do anything here except change blockState.
3514 ReleaseSavepoint(List *options)
3516 TransactionState s = CurrentTransactionState;
3517 TransactionState target,
3522 switch (s->blockState)
3525 * We can't rollback to a savepoint if there is no savepoint
3528 case TBLOCK_INPROGRESS:
3530 (errcode(ERRCODE_S_E_INVALID_SPECIFICATION),
3531 errmsg("no such savepoint")));
3535 * We are in a non-aborted subtransaction. This is the only valid
3538 case TBLOCK_SUBINPROGRESS:
3541 /* These cases are invalid. */
3542 case TBLOCK_DEFAULT:
3543 case TBLOCK_STARTED:
3545 case TBLOCK_SUBBEGIN:
3547 case TBLOCK_SUBRELEASE:
3548 case TBLOCK_SUBCOMMIT:
3550 case TBLOCK_SUBABORT:
3551 case TBLOCK_ABORT_END:
3552 case TBLOCK_SUBABORT_END:
3553 case TBLOCK_ABORT_PENDING:
3554 case TBLOCK_SUBABORT_PENDING:
3555 case TBLOCK_SUBRESTART:
3556 case TBLOCK_SUBABORT_RESTART:
3557 case TBLOCK_PREPARE:
3558 elog(FATAL, "ReleaseSavepoint: unexpected state %s",
3559 BlockStateAsString(s->blockState));
3563 foreach(cell, options)
3565 DefElem *elem = lfirst(cell);
3567 if (strcmp(elem->defname, "savepoint_name") == 0)
3568 name = strVal(elem->arg);
3571 Assert(PointerIsValid(name));
3573 for (target = s; PointerIsValid(target); target = target->parent)
3575 if (PointerIsValid(target->name) && strcmp(target->name, name) == 0)
3579 if (!PointerIsValid(target))
3581 (errcode(ERRCODE_S_E_INVALID_SPECIFICATION),
3582 errmsg("no such savepoint")));
3584 /* disallow crossing savepoint level boundaries */
3585 if (target->savepointLevel != s->savepointLevel)
3587 (errcode(ERRCODE_S_E_INVALID_SPECIFICATION),
3588 errmsg("no such savepoint")));
3591 * Mark "commit pending" all subtransactions up to the target
3592 * subtransaction. The actual commits will happen when control gets to
3593 * CommitTransactionCommand.
3595 xact = CurrentTransactionState;
3598 Assert(xact->blockState == TBLOCK_SUBINPROGRESS);
3599 xact->blockState = TBLOCK_SUBRELEASE;
3602 xact = xact->parent;
3603 Assert(PointerIsValid(xact));
3608 * RollbackToSavepoint
3609 * This executes a ROLLBACK TO <savepoint> command.
3611 * As above, we don't actually do anything here except change blockState.
3614 RollbackToSavepoint(List *options)
3616 TransactionState s = CurrentTransactionState;
3617 TransactionState target,
3622 switch (s->blockState)
3625 * We can't rollback to a savepoint if there is no savepoint
3628 case TBLOCK_INPROGRESS:
3631 (errcode(ERRCODE_S_E_INVALID_SPECIFICATION),
3632 errmsg("no such savepoint")));
3636 * There is at least one savepoint, so proceed.
3638 case TBLOCK_SUBINPROGRESS:
3639 case TBLOCK_SUBABORT:
3642 /* These cases are invalid. */
3643 case TBLOCK_DEFAULT:
3644 case TBLOCK_STARTED:
3646 case TBLOCK_SUBBEGIN:
3648 case TBLOCK_SUBRELEASE:
3649 case TBLOCK_SUBCOMMIT:
3650 case TBLOCK_ABORT_END:
3651 case TBLOCK_SUBABORT_END:
3652 case TBLOCK_ABORT_PENDING:
3653 case TBLOCK_SUBABORT_PENDING:
3654 case TBLOCK_SUBRESTART:
3655 case TBLOCK_SUBABORT_RESTART:
3656 case TBLOCK_PREPARE:
3657 elog(FATAL, "RollbackToSavepoint: unexpected state %s",
3658 BlockStateAsString(s->blockState));
3662 foreach(cell, options)
3664 DefElem *elem = lfirst(cell);
3666 if (strcmp(elem->defname, "savepoint_name") == 0)
3667 name = strVal(elem->arg);
3670 Assert(PointerIsValid(name));
3672 for (target = s; PointerIsValid(target); target = target->parent)
3674 if (PointerIsValid(target->name) && strcmp(target->name, name) == 0)
3678 if (!PointerIsValid(target))
3680 (errcode(ERRCODE_S_E_INVALID_SPECIFICATION),
3681 errmsg("no such savepoint")));
3683 /* disallow crossing savepoint level boundaries */
3684 if (target->savepointLevel != s->savepointLevel)
3686 (errcode(ERRCODE_S_E_INVALID_SPECIFICATION),
3687 errmsg("no such savepoint")));
3690 * Mark "abort pending" all subtransactions up to the target
3691 * subtransaction. The actual aborts will happen when control gets to
3692 * CommitTransactionCommand.
3694 xact = CurrentTransactionState;
3699 if (xact->blockState == TBLOCK_SUBINPROGRESS)
3700 xact->blockState = TBLOCK_SUBABORT_PENDING;
3701 else if (xact->blockState == TBLOCK_SUBABORT)
3702 xact->blockState = TBLOCK_SUBABORT_END;
3704 elog(FATAL, "RollbackToSavepoint: unexpected state %s",
3705 BlockStateAsString(xact->blockState));
3706 xact = xact->parent;
3707 Assert(PointerIsValid(xact));
3710 /* And mark the target as "restart pending" */
3711 if (xact->blockState == TBLOCK_SUBINPROGRESS)
3712 xact->blockState = TBLOCK_SUBRESTART;
3713 else if (xact->blockState == TBLOCK_SUBABORT)
3714 xact->blockState = TBLOCK_SUBABORT_RESTART;
3716 elog(FATAL, "RollbackToSavepoint: unexpected state %s",
3717 BlockStateAsString(xact->blockState));
3721 * BeginInternalSubTransaction
3722 * This is the same as DefineSavepoint except it allows TBLOCK_STARTED,
3723 * TBLOCK_END, and TBLOCK_PREPARE states, and therefore it can safely be
3724 * used in functions that might be called when not inside a BEGIN block
3725 * or when running deferred triggers at COMMIT/PREPARE time. Also, it
3726 * automatically does CommitTransactionCommand/StartTransactionCommand
3727 * instead of expecting the caller to do it.
3730 BeginInternalSubTransaction(char *name)
3732 TransactionState s = CurrentTransactionState;
3734 switch (s->blockState)
3736 case TBLOCK_STARTED:
3737 case TBLOCK_INPROGRESS:
3739 case TBLOCK_PREPARE:
3740 case TBLOCK_SUBINPROGRESS:
3741 /* Normal subtransaction start */
3743 s = CurrentTransactionState; /* changed by push */
3746 * Savepoint names, like the TransactionState block itself, live
3747 * in TopTransactionContext.
3750 s->name = MemoryContextStrdup(TopTransactionContext, name);
3753 /* These cases are invalid. */
3754 case TBLOCK_DEFAULT:
3756 case TBLOCK_SUBBEGIN:
3757 case TBLOCK_SUBRELEASE:
3758 case TBLOCK_SUBCOMMIT:
3760 case TBLOCK_SUBABORT:
3761 case TBLOCK_ABORT_END:
3762 case TBLOCK_SUBABORT_END:
3763 case TBLOCK_ABORT_PENDING:
3764 case TBLOCK_SUBABORT_PENDING:
3765 case TBLOCK_SUBRESTART:
3766 case TBLOCK_SUBABORT_RESTART:
3767 elog(FATAL, "BeginInternalSubTransaction: unexpected state %s",
3768 BlockStateAsString(s->blockState));
3772 CommitTransactionCommand();
3773 StartTransactionCommand();
3777 * ReleaseCurrentSubTransaction
3779 * RELEASE (ie, commit) the innermost subtransaction, regardless of its
3780 * savepoint name (if any).
3781 * NB: do NOT use CommitTransactionCommand/StartTransactionCommand with this.
3784 ReleaseCurrentSubTransaction(void)
3786 TransactionState s = CurrentTransactionState;
3788 if (s->blockState != TBLOCK_SUBINPROGRESS)
3789 elog(ERROR, "ReleaseCurrentSubTransaction: unexpected state %s",
3790 BlockStateAsString(s->blockState));
3791 Assert(s->state == TRANS_INPROGRESS);
3792 MemoryContextSwitchTo(CurTransactionContext);
3793 CommitSubTransaction();
3794 s = CurrentTransactionState; /* changed by pop */
3795 Assert(s->state == TRANS_INPROGRESS);
3799 * RollbackAndReleaseCurrentSubTransaction
3801 * ROLLBACK and RELEASE (ie, abort) the innermost subtransaction, regardless
3802 * of its savepoint name (if any).
3803 * NB: do NOT use CommitTransactionCommand/StartTransactionCommand with this.
3806 RollbackAndReleaseCurrentSubTransaction(void)
3808 TransactionState s = CurrentTransactionState;
3810 switch (s->blockState)
3812 /* Must be in a subtransaction */
3813 case TBLOCK_SUBINPROGRESS:
3814 case TBLOCK_SUBABORT:
3817 /* These cases are invalid. */
3818 case TBLOCK_DEFAULT:
3819 case TBLOCK_STARTED:
3821 case TBLOCK_SUBBEGIN:
3822 case TBLOCK_INPROGRESS:
3824 case TBLOCK_SUBRELEASE:
3825 case TBLOCK_SUBCOMMIT:
3827 case TBLOCK_ABORT_END:
3828 case TBLOCK_SUBABORT_END:
3829 case TBLOCK_ABORT_PENDING:
3830 case TBLOCK_SUBABORT_PENDING:
3831 case TBLOCK_SUBRESTART:
3832 case TBLOCK_SUBABORT_RESTART:
3833 case TBLOCK_PREPARE:
3834 elog(FATAL, "RollbackAndReleaseCurrentSubTransaction: unexpected state %s",
3835 BlockStateAsString(s->blockState));
3840 * Abort the current subtransaction, if needed.
3842 if (s->blockState == TBLOCK_SUBINPROGRESS)
3843 AbortSubTransaction();
3845 /* And clean it up, too */
3846 CleanupSubTransaction();
3848 s = CurrentTransactionState; /* changed by pop */
3849 AssertState(s->blockState == TBLOCK_SUBINPROGRESS ||
3850 s->blockState == TBLOCK_INPROGRESS ||
3851 s->blockState == TBLOCK_STARTED);
3855 * AbortOutOfAnyTransaction
3857 * This routine is provided for error recovery purposes. It aborts any
3858 * active transaction or transaction block, leaving the system in a known
3862 AbortOutOfAnyTransaction(void)
3864 TransactionState s = CurrentTransactionState;
3867 * Get out of any transaction or nested transaction
3871 switch (s->blockState)
3873 case TBLOCK_DEFAULT:
3874 if (s->state == TRANS_DEFAULT)
3876 /* Not in a transaction, do nothing */
3881 * We can get here after an error during transaction start
3882 * (state will be TRANS_START). Need to clean up the
3883 * incompletely started transaction. First, adjust the
3884 * low-level state to suppress warning message from
3887 if (s->state == TRANS_START)
3888 s->state = TRANS_INPROGRESS;
3890 CleanupTransaction();
3893 case TBLOCK_STARTED:
3895 case TBLOCK_INPROGRESS:
3897 case TBLOCK_ABORT_PENDING:
3898 case TBLOCK_PREPARE:
3899 /* In a transaction, so clean up */
3901 CleanupTransaction();
3902 s->blockState = TBLOCK_DEFAULT;
3905 case TBLOCK_ABORT_END:
3906 /* AbortTransaction already done, still need Cleanup */
3907 CleanupTransaction();
3908 s->blockState = TBLOCK_DEFAULT;
3912 * In a subtransaction, so clean it up and abort parent too
3914 case TBLOCK_SUBBEGIN:
3915 case TBLOCK_SUBINPROGRESS:
3916 case TBLOCK_SUBRELEASE:
3917 case TBLOCK_SUBCOMMIT:
3918 case TBLOCK_SUBABORT_PENDING:
3919 case TBLOCK_SUBRESTART:
3920 AbortSubTransaction();
3921 CleanupSubTransaction();
3922 s = CurrentTransactionState; /* changed by pop */
3925 case TBLOCK_SUBABORT:
3926 case TBLOCK_SUBABORT_END:
3927 case TBLOCK_SUBABORT_RESTART:
3928 /* As above, but AbortSubTransaction already done */
3929 CleanupSubTransaction();
3930 s = CurrentTransactionState; /* changed by pop */
3933 } while (s->blockState != TBLOCK_DEFAULT);
3935 /* Should be out of all subxacts now */
3936 Assert(s->parent == NULL);
3940 * IsTransactionBlock --- are we within a transaction block?
3943 IsTransactionBlock(void)
3945 TransactionState s = CurrentTransactionState;
3947 if (s->blockState == TBLOCK_DEFAULT || s->blockState == TBLOCK_STARTED)
3954 * IsTransactionOrTransactionBlock --- are we within either a transaction
3955 * or a transaction block? (The backend is only really "idle" when this
3958 * This should match up with IsTransactionBlock and IsTransactionState.
3961 IsTransactionOrTransactionBlock(void)
3963 TransactionState s = CurrentTransactionState;
3965 if (s->blockState == TBLOCK_DEFAULT)
3972 * TransactionBlockStatusCode - return status code to send in ReadyForQuery
3975 TransactionBlockStatusCode(void)
3977 TransactionState s = CurrentTransactionState;
3979 switch (s->blockState)
3981 case TBLOCK_DEFAULT:
3982 case TBLOCK_STARTED:
3983 return 'I'; /* idle --- not in transaction */
3985 case TBLOCK_SUBBEGIN:
3986 case TBLOCK_INPROGRESS:
3987 case TBLOCK_SUBINPROGRESS:
3989 case TBLOCK_SUBRELEASE:
3990 case TBLOCK_SUBCOMMIT:
3991 case TBLOCK_PREPARE:
3992 return 'T'; /* in transaction */
3994 case TBLOCK_SUBABORT:
3995 case TBLOCK_ABORT_END:
3996 case TBLOCK_SUBABORT_END:
3997 case TBLOCK_ABORT_PENDING:
3998 case TBLOCK_SUBABORT_PENDING:
3999 case TBLOCK_SUBRESTART:
4000 case TBLOCK_SUBABORT_RESTART:
4001 return 'E'; /* in failed transaction */
4004 /* should never get here */
4005 elog(FATAL, "invalid transaction block state: %s",
4006 BlockStateAsString(s->blockState));
4007 return 0; /* keep compiler quiet */
4014 IsSubTransaction(void)
4016 TransactionState s = CurrentTransactionState;
4018 if (s->nestingLevel >= 2)
4025 * StartSubTransaction
4027 * If you're wondering why this is separate from PushTransaction: it's because
4028 * we can't conveniently do this stuff right inside DefineSavepoint. The
4029 * SAVEPOINT utility command will be executed inside a Portal, and if we
4030 * muck with CurrentMemoryContext or CurrentResourceOwner then exit from
4031 * the Portal will undo those settings. So we make DefineSavepoint just
4032 * push a dummy transaction block, and when control returns to the main
4033 * idle loop, CommitTransactionCommand will be called, and we'll come here
4034 * to finish starting the subtransaction.
4037 StartSubTransaction(void)
4039 TransactionState s = CurrentTransactionState;
4041 if (s->state != TRANS_DEFAULT)
4042 elog(WARNING, "StartSubTransaction while in %s state",
4043 TransStateAsString(s->state));
4045 s->state = TRANS_START;
4048 * Initialize subsystems for new subtransaction
4050 * must initialize resource-management stuff first
4052 AtSubStart_Memory();
4053 AtSubStart_ResourceOwner();
4055 AtSubStart_Notify();
4056 AfterTriggerBeginSubXact();
4058 s->state = TRANS_INPROGRESS;
4061 * Call start-of-subxact callbacks
4063 CallSubXactCallbacks(SUBXACT_EVENT_START_SUB, s->subTransactionId,
4064 s->parent->subTransactionId);
4066 ShowTransactionState("StartSubTransaction");
4070 * CommitSubTransaction
4072 * The caller has to make sure to always reassign CurrentTransactionState
4073 * if it has a local pointer to it after calling this function.
4076 CommitSubTransaction(void)
4078 TransactionState s = CurrentTransactionState;
4080 ShowTransactionState("CommitSubTransaction");
4082 if (s->state != TRANS_INPROGRESS)
4083 elog(WARNING, "CommitSubTransaction while in %s state",
4084 TransStateAsString(s->state));
4086 /* Pre-commit processing goes here */
4088 CallSubXactCallbacks(SUBXACT_EVENT_PRE_COMMIT_SUB, s->subTransactionId,
4089 s->parent->subTransactionId);
4091 /* Do the actual "commit", such as it is */
4092 s->state = TRANS_COMMIT;
4094 /* Must CCI to ensure commands of subtransaction are seen as done */
4095 CommandCounterIncrement();
4098 * Prior to 8.4 we marked subcommit in clog at this point. We now only
4099 * perform that step, if required, as part of the atomic update of the
4100 * whole transaction tree at top level commit or abort.
4103 /* Post-commit cleanup */
4104 if (TransactionIdIsValid(s->transactionId))
4105 AtSubCommit_childXids();
4106 AfterTriggerEndSubXact(true);
4107 AtSubCommit_Portals(s->subTransactionId,
4108 s->parent->subTransactionId,
4109 s->parent->curTransactionOwner);
4110 AtEOSubXact_LargeObject(true, s->subTransactionId,
4111 s->parent->subTransactionId);
4112 AtSubCommit_Notify();
4114 CallSubXactCallbacks(SUBXACT_EVENT_COMMIT_SUB, s->subTransactionId,
4115 s->parent->subTransactionId);
4117 ResourceOwnerRelease(s->curTransactionOwner,
4118 RESOURCE_RELEASE_BEFORE_LOCKS,
4120 AtEOSubXact_RelationCache(true, s->subTransactionId,
4121 s->parent->subTransactionId);
4122 AtEOSubXact_Inval(true);
4126 * The only lock we actually release here is the subtransaction XID lock.
4128 CurrentResourceOwner = s->curTransactionOwner;
4129 if (TransactionIdIsValid(s->transactionId))
4130 XactLockTableDelete(s->transactionId);
4133 * Other locks should get transferred to their parent resource owner.
4135 ResourceOwnerRelease(s->curTransactionOwner,
4136 RESOURCE_RELEASE_LOCKS,
4138 ResourceOwnerRelease(s->curTransactionOwner,
4139 RESOURCE_RELEASE_AFTER_LOCKS,
4142 AtEOXact_GUC(true, s->gucNestLevel);
4143 AtEOSubXact_SPI(true, s->subTransactionId);
4144 AtEOSubXact_on_commit_actions(true, s->subTransactionId,
4145 s->parent->subTransactionId);
4146 AtEOSubXact_Namespace(true, s->subTransactionId,
4147 s->parent->subTransactionId);
4148 AtEOSubXact_Files(true, s->subTransactionId,
4149 s->parent->subTransactionId);
4150 AtEOSubXact_HashTables(true, s->nestingLevel);
4151 AtEOSubXact_PgStat(true, s->nestingLevel);
4152 AtSubCommit_Snapshot(s->nestingLevel);
4155 * We need to restore the upper transaction's read-only state, in case the
4156 * upper is read-write while the child is read-only; GUC will incorrectly
4157 * think it should leave the child state in place.
4159 XactReadOnly = s->prevXactReadOnly;
4161 CurrentResourceOwner = s->parent->curTransactionOwner;
4162 CurTransactionResourceOwner = s->parent->curTransactionOwner;
4163 ResourceOwnerDelete(s->curTransactionOwner);
4164 s->curTransactionOwner = NULL;
4166 AtSubCommit_Memory();
4168 s->state = TRANS_DEFAULT;
4174 * AbortSubTransaction
4177 AbortSubTransaction(void)
4179 TransactionState s = CurrentTransactionState;
4181 /* Prevent cancel/die interrupt while cleaning up */
4184 /* Make sure we have a valid memory context and resource owner */
4185 AtSubAbort_Memory();
4186 AtSubAbort_ResourceOwner();
4189 * Release any LW locks we might be holding as quickly as possible.
4190 * (Regular locks, however, must be held till we finish aborting.)
4191 * Releasing LW locks is critical since we might try to grab them again
4192 * while cleaning up!
4194 * FIXME This may be incorrect --- Are there some locks we should keep?
4195 * Buffer locks, for example? I don't think so but I'm not sure.
4205 * check the current transaction state
4207 ShowTransactionState("AbortSubTransaction");
4209 if (s->state != TRANS_INPROGRESS)
4210 elog(WARNING, "AbortSubTransaction while in %s state",
4211 TransStateAsString(s->state));
4213 s->state = TRANS_ABORT;
4216 * Reset user ID which might have been changed transiently. (See notes in
4217 * AbortTransaction.)
4219 SetUserIdAndSecContext(s->prevUser, s->prevSecContext);
4222 * We can skip all this stuff if the subxact failed before creating a
4225 if (s->curTransactionOwner)
4227 AfterTriggerEndSubXact(false);
4228 AtSubAbort_Portals(s->subTransactionId,
4229 s->parent->subTransactionId,
4230 s->parent->curTransactionOwner);
4231 AtEOSubXact_LargeObject(false, s->subTransactionId,
4232 s->parent->subTransactionId);
4233 AtSubAbort_Notify();
4235 /* Advertise the fact that we aborted in pg_clog. */
4236 (void) RecordTransactionAbort(true);
4238 /* Post-abort cleanup */
4239 if (TransactionIdIsValid(s->transactionId))
4240 AtSubAbort_childXids();
4242 CallSubXactCallbacks(SUBXACT_EVENT_ABORT_SUB, s->subTransactionId,
4243 s->parent->subTransactionId);
4245 ResourceOwnerRelease(s->curTransactionOwner,
4246 RESOURCE_RELEASE_BEFORE_LOCKS,
4248 AtEOSubXact_RelationCache(false, s->subTransactionId,
4249 s->parent->subTransactionId);
4250 AtEOSubXact_Inval(false);
4251 ResourceOwnerRelease(s->curTransactionOwner,
4252 RESOURCE_RELEASE_LOCKS,
4254 ResourceOwnerRelease(s->curTransactionOwner,
4255 RESOURCE_RELEASE_AFTER_LOCKS,
4259 AtEOXact_GUC(false, s->gucNestLevel);
4260 AtEOSubXact_SPI(false, s->subTransactionId);
4261 AtEOSubXact_on_commit_actions(false, s->subTransactionId,
4262 s->parent->subTransactionId);
4263 AtEOSubXact_Namespace(false, s->subTransactionId,
4264 s->parent->subTransactionId);
4265 AtEOSubXact_Files(false, s->subTransactionId,
4266 s->parent->subTransactionId);
4267 AtEOSubXact_HashTables(false, s->nestingLevel);
4268 AtEOSubXact_PgStat(false, s->nestingLevel);
4269 AtSubAbort_Snapshot(s->nestingLevel);
4273 * Restore the upper transaction's read-only state, too. This should be
4274 * redundant with GUC's cleanup but we may as well do it for consistency
4275 * with the commit case.
4277 XactReadOnly = s->prevXactReadOnly;
4279 RESUME_INTERRUPTS();
4283 * CleanupSubTransaction
4285 * The caller has to make sure to always reassign CurrentTransactionState
4286 * if it has a local pointer to it after calling this function.
4289 CleanupSubTransaction(void)
4291 TransactionState s = CurrentTransactionState;
4293 ShowTransactionState("CleanupSubTransaction");
4295 if (s->state != TRANS_ABORT)
4296 elog(WARNING, "CleanupSubTransaction while in %s state",
4297 TransStateAsString(s->state));
4299 AtSubCleanup_Portals(s->subTransactionId);
4301 CurrentResourceOwner = s->parent->curTransactionOwner;
4302 CurTransactionResourceOwner = s->parent->curTransactionOwner;
4303 if (s->curTransactionOwner)
4304 ResourceOwnerDelete(s->curTransactionOwner);
4305 s->curTransactionOwner = NULL;
4307 AtSubCleanup_Memory();
4309 s->state = TRANS_DEFAULT;
4316 * Create transaction state stack entry for a subtransaction
4318 * The caller has to make sure to always reassign CurrentTransactionState
4319 * if it has a local pointer to it after calling this function.
4322 PushTransaction(void)
4324 TransactionState p = CurrentTransactionState;
4328 * We keep subtransaction state nodes in TopTransactionContext.
4330 s = (TransactionState)
4331 MemoryContextAllocZero(TopTransactionContext,
4332 sizeof(TransactionStateData));
4335 * Assign a subtransaction ID, watching out for counter wraparound.
4337 currentSubTransactionId += 1;
4338 if (currentSubTransactionId == InvalidSubTransactionId)
4340 currentSubTransactionId -= 1;
4343 (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
4344 errmsg("cannot have more than 2^32-1 subtransactions in a transaction")));
4348 * We can now stack a minimally valid subtransaction without fear of
4351 s->transactionId = InvalidTransactionId; /* until assigned */
4352 s->subTransactionId = currentSubTransactionId;
4354 s->nestingLevel = p->nestingLevel + 1;
4355 s->gucNestLevel = NewGUCNestLevel();
4356 s->savepointLevel = p->savepointLevel;
4357 s->state = TRANS_DEFAULT;
4358 s->blockState = TBLOCK_SUBBEGIN;
4359 GetUserIdAndSecContext(&s->prevUser, &s->prevSecContext);
4360 s->prevXactReadOnly = XactReadOnly;
4362 CurrentTransactionState = s;
4365 * AbortSubTransaction and CleanupSubTransaction have to be able to cope
4366 * with the subtransaction from here on out; in particular they should not
4367 * assume that it necessarily has a transaction context, resource owner,
4374 * Pop back to parent transaction state
4376 * The caller has to make sure to always reassign CurrentTransactionState
4377 * if it has a local pointer to it after calling this function.
4380 PopTransaction(void)
4382 TransactionState s = CurrentTransactionState;
4384 if (s->state != TRANS_DEFAULT)
4385 elog(WARNING, "PopTransaction while in %s state",
4386 TransStateAsString(s->state));
4388 if (s->parent == NULL)
4389 elog(FATAL, "PopTransaction with no parent");
4391 CurrentTransactionState = s->parent;
4393 /* Let's just make sure CurTransactionContext is good */
4394 CurTransactionContext = s->parent->curTransactionContext;
4395 MemoryContextSwitchTo(CurTransactionContext);
4397 /* Ditto for ResourceOwner links */
4398 CurTransactionResourceOwner = s->parent->curTransactionOwner;
4399 CurrentResourceOwner = s->parent->curTransactionOwner;
4401 /* Free the old child structure */
4408 * ShowTransactionState
4412 ShowTransactionState(const char *str)
4414 /* skip work if message will definitely not be printed */
4415 if (log_min_messages <= DEBUG3 || client_min_messages <= DEBUG3)
4417 elog(DEBUG3, "%s", str);
4418 ShowTransactionStateRec(CurrentTransactionState);
4423 * ShowTransactionStateRec
4424 * Recursive subroutine for ShowTransactionState
4427 ShowTransactionStateRec(TransactionState s)
4431 initStringInfo(&buf);
4433 if (s->nChildXids > 0)
4437 appendStringInfo(&buf, "%u", s->childXids[0]);
4438 for (i = 1; i < s->nChildXids; i++)
4439 appendStringInfo(&buf, " %u", s->childXids[i]);
4443 ShowTransactionStateRec(s->parent);
4445 /* use ereport to suppress computation if msg will not be printed */
4447 (errmsg_internal("name: %s; blockState: %13s; state: %7s, xid/subid/cid: %u/%u/%u%s, nestlvl: %d, children: %s",
4448 PointerIsValid(s->name) ? s->name : "unnamed",
4449 BlockStateAsString(s->blockState),
4450 TransStateAsString(s->state),
4451 (unsigned int) s->transactionId,
4452 (unsigned int) s->subTransactionId,
4453 (unsigned int) currentCommandId,
4454 currentCommandIdUsed ? " (used)" : "",
4455 s->nestingLevel, buf.data)));
4461 * BlockStateAsString
4465 BlockStateAsString(TBlockState blockState)
4469 case TBLOCK_DEFAULT:
4471 case TBLOCK_STARTED:
4475 case TBLOCK_INPROGRESS:
4476 return "INPROGRESS";
4481 case TBLOCK_ABORT_END:
4483 case TBLOCK_ABORT_PENDING:
4484 return "ABORT PEND";
4485 case TBLOCK_PREPARE:
4487 case TBLOCK_SUBBEGIN:
4489 case TBLOCK_SUBINPROGRESS:
4490 return "SUB INPROGRS";
4491 case TBLOCK_SUBRELEASE:
4492 return "SUB RELEASE";
4493 case TBLOCK_SUBCOMMIT:
4494 return "SUB COMMIT";
4495 case TBLOCK_SUBABORT:
4497 case TBLOCK_SUBABORT_END:
4498 return "SUB ABORT END";
4499 case TBLOCK_SUBABORT_PENDING:
4500 return "SUB ABRT PEND";
4501 case TBLOCK_SUBRESTART:
4502 return "SUB RESTART";
4503 case TBLOCK_SUBABORT_RESTART:
4504 return "SUB AB RESTRT";
4506 return "UNRECOGNIZED";
4510 * TransStateAsString
4514 TransStateAsString(TransState state)
4522 case TRANS_INPROGRESS:
4531 return "UNRECOGNIZED";
4535 * xactGetCommittedChildren
4537 * Gets the list of committed children of the current transaction. The return
4538 * value is the number of child transactions. *ptr is set to point to an
4539 * array of TransactionIds. The array is allocated in TopTransactionContext;
4540 * the caller should *not* pfree() it (this is a change from pre-8.4 code!).
4541 * If there are no subxacts, *ptr is set to NULL.
4544 xactGetCommittedChildren(TransactionId **ptr)
4546 TransactionState s = CurrentTransactionState;
4548 if (s->nChildXids == 0)
4551 *ptr = s->childXids;
4553 return s->nChildXids;
4557 * XLOG support routines
4561 * Before 9.0 this was a fairly short function, but now it performs many
4562 * actions for which the order of execution is critical.
4565 xact_redo_commit_internal(TransactionId xid, XLogRecPtr lsn,
4566 TransactionId *sub_xids, int nsubxacts,
4567 SharedInvalidationMessage *inval_msgs, int nmsgs,
4568 RelFileNode *xnodes, int nrels,
4572 TransactionId max_xid;
4575 max_xid = TransactionIdLatest(xid, nsubxacts, sub_xids);
4578 * Make sure nextXid is beyond any XID mentioned in the record.
4580 * We don't expect anyone else to modify nextXid, hence we don't need to
4581 * hold a lock while checking this. We still acquire the lock to modify
4584 if (TransactionIdFollowsOrEquals(max_xid,
4585 ShmemVariableCache->nextXid))
4587 LWLockAcquire(XidGenLock, LW_EXCLUSIVE);
4588 ShmemVariableCache->nextXid = max_xid;
4589 TransactionIdAdvance(ShmemVariableCache->nextXid);
4590 LWLockRelease(XidGenLock);
4593 if (standbyState == STANDBY_DISABLED)
4596 * Mark the transaction committed in pg_clog.
4598 TransactionIdCommitTree(xid, nsubxacts, sub_xids);
4603 * If a transaction completion record arrives that has as-yet
4604 * unobserved subtransactions then this will not have been fully
4605 * handled by the call to RecordKnownAssignedTransactionIds() in the
4606 * main recovery loop in xlog.c. So we need to do bookkeeping again to
4607 * cover that case. This is confusing and it is easy to think this
4608 * call is irrelevant, which has happened three times in development
4609 * already. Leave it in.
4611 RecordKnownAssignedTransactionIds(max_xid);
4614 * Mark the transaction committed in pg_clog. We use async commit
4615 * protocol during recovery to provide information on database
4616 * consistency for when users try to set hint bits. It is important
4617 * that we do not set hint bits until the minRecoveryPoint is past
4618 * this commit record. This ensures that if we crash we don't see hint
4619 * bits set on changes made by transactions that haven't yet
4620 * recovered. It's unlikely but it's good to be safe.
4622 TransactionIdAsyncCommitTree(xid, nsubxacts, sub_xids, lsn);
4625 * We must mark clog before we update the ProcArray.
4627 ExpireTreeKnownAssignedTransactionIds(xid, nsubxacts, sub_xids, max_xid);
4630 * Send any cache invalidations attached to the commit. We must
4631 * maintain the same order of invalidation then release locks as
4632 * occurs in CommitTransaction().
4634 ProcessCommittedInvalidationMessages(inval_msgs, nmsgs,
4635 XactCompletionRelcacheInitFileInval(xinfo),
4639 * Release locks, if any. We do this for both two phase and normal one
4640 * phase transactions. In effect we are ignoring the prepare phase and
4641 * just going straight to lock release. At commit we release all locks
4642 * via their top-level xid only, so no need to provide subxact list,
4643 * which will save time when replaying commits.
4645 StandbyReleaseLockTree(xid, 0, NULL);
4648 /* Make sure files supposed to be dropped are dropped */
4652 * First update minimum recovery point to cover this WAL record. Once
4653 * a relation is deleted, there's no going back. The buffer manager
4654 * enforces the WAL-first rule for normal updates to relation files,
4655 * so that the minimum recovery point is always updated before the
4656 * corresponding change in the data file is flushed to disk, but we
4657 * have to do the same here since we're bypassing the buffer manager.
4659 * Doing this before deleting the files means that if a deletion fails
4660 * for some reason, you cannot start up the system even after restart,
4661 * until you fix the underlying situation so that the deletion will
4662 * succeed. Alternatively, we could update the minimum recovery point
4663 * after deletion, but that would leave a small window where the
4664 * WAL-first rule would be violated.
4668 for (i = 0; i < nrels; i++)
4670 SMgrRelation srel = smgropen(xnodes[i], InvalidBackendId);
4673 for (fork = 0; fork <= MAX_FORKNUM; fork++)
4674 XLogDropRelation(xnodes[i], fork);
4675 smgrdounlink(srel, true);
4681 * We issue an XLogFlush() for the same reason we emit ForceSyncCommit()
4682 * in normal operation. For example, in CREATE DATABASE, we copy all files
4683 * from the template database, and then commit the transaction. If we
4684 * crash after all the files have been copied but before the commit, you
4685 * have files in the data directory without an entry in pg_database. To
4686 * minimize the window for that, we use ForceSyncCommit() to rush the
4687 * commit record to disk as quick as possible. We have the same window
4688 * during recovery, and forcing an XLogFlush() (which updates
4689 * minRecoveryPoint during recovery) helps to reduce that problem window,
4690 * for any user that requested ForceSyncCommit().
4692 if (XactCompletionForceSyncCommit(xinfo))
4698 * Utility function to call xact_redo_commit_internal after breaking down xlrec
4701 xact_redo_commit(xl_xact_commit *xlrec,
4702 TransactionId xid, XLogRecPtr lsn)
4704 TransactionId *subxacts;
4705 SharedInvalidationMessage *inval_msgs;
4707 /* subxid array follows relfilenodes */
4708 subxacts = (TransactionId *) &(xlrec->xnodes[xlrec->nrels]);
4709 /* invalidation messages array follows subxids */
4710 inval_msgs = (SharedInvalidationMessage *) &(subxacts[xlrec->nsubxacts]);
4712 xact_redo_commit_internal(xid, lsn, subxacts, xlrec->nsubxacts,
4713 inval_msgs, xlrec->nmsgs,
4714 xlrec->xnodes, xlrec->nrels,
4721 * Utility function to call xact_redo_commit_internal for compact form of message.
4724 xact_redo_commit_compact(xl_xact_commit_compact *xlrec,
4725 TransactionId xid, XLogRecPtr lsn)
4727 xact_redo_commit_internal(xid, lsn, xlrec->subxacts, xlrec->nsubxacts,
4728 NULL, 0, /* inval msgs */
4729 NULL, 0, /* relfilenodes */
4730 InvalidOid, /* dbId */
4731 InvalidOid, /* tsId */
4736 * Be careful with the order of execution, as with xact_redo_commit().
4737 * The two functions are similar but differ in key places.
4739 * Note also that an abort can be for a subtransaction and its children,
4740 * not just for a top level abort. That means we have to consider
4741 * topxid != xid, whereas in commit we would find topxid == xid always
4742 * because subtransaction commit is never WAL logged.
4745 xact_redo_abort(xl_xact_abort *xlrec, TransactionId xid)
4747 TransactionId *sub_xids;
4748 TransactionId max_xid;
4751 sub_xids = (TransactionId *) &(xlrec->xnodes[xlrec->nrels]);
4752 max_xid = TransactionIdLatest(xid, xlrec->nsubxacts, sub_xids);
4755 * Make sure nextXid is beyond any XID mentioned in the record.
4757 * We don't expect anyone else to modify nextXid, hence we don't need to
4758 * hold a lock while checking this. We still acquire the lock to modify
4761 if (TransactionIdFollowsOrEquals(max_xid,
4762 ShmemVariableCache->nextXid))
4764 LWLockAcquire(XidGenLock, LW_EXCLUSIVE);
4765 ShmemVariableCache->nextXid = max_xid;
4766 TransactionIdAdvance(ShmemVariableCache->nextXid);
4767 LWLockRelease(XidGenLock);
4770 if (standbyState == STANDBY_DISABLED)
4772 /* Mark the transaction aborted in pg_clog, no need for async stuff */
4773 TransactionIdAbortTree(xid, xlrec->nsubxacts, sub_xids);
4778 * If a transaction completion record arrives that has as-yet
4779 * unobserved subtransactions then this will not have been fully
4780 * handled by the call to RecordKnownAssignedTransactionIds() in the
4781 * main recovery loop in xlog.c. So we need to do bookkeeping again to
4782 * cover that case. This is confusing and it is easy to think this
4783 * call is irrelevant, which has happened three times in development
4784 * already. Leave it in.
4786 RecordKnownAssignedTransactionIds(max_xid);
4788 /* Mark the transaction aborted in pg_clog, no need for async stuff */
4789 TransactionIdAbortTree(xid, xlrec->nsubxacts, sub_xids);
4792 * We must update the ProcArray after we have marked clog.
4794 ExpireTreeKnownAssignedTransactionIds(xid, xlrec->nsubxacts, sub_xids, max_xid);
4797 * There are no flat files that need updating, nor invalidation
4798 * messages to send or undo.
4802 * Release locks, if any. There are no invalidations to send.
4804 StandbyReleaseLockTree(xid, xlrec->nsubxacts, sub_xids);
4807 /* Make sure files supposed to be dropped are dropped */
4808 for (i = 0; i < xlrec->nrels; i++)
4810 SMgrRelation srel = smgropen(xlrec->xnodes[i], InvalidBackendId);
4813 for (fork = 0; fork <= MAX_FORKNUM; fork++)
4814 XLogDropRelation(xlrec->xnodes[i], fork);
4815 smgrdounlink(srel, true);
4821 xact_redo(XLogRecPtr lsn, XLogRecord *record)
4823 uint8 info = record->xl_info & ~XLR_INFO_MASK;
4825 /* Backup blocks are not used in xact records */
4826 Assert(!(record->xl_info & XLR_BKP_BLOCK_MASK));
4828 if (info == XLOG_XACT_COMMIT_COMPACT)
4830 xl_xact_commit_compact *xlrec = (xl_xact_commit_compact *) XLogRecGetData(record);
4832 xact_redo_commit_compact(xlrec, record->xl_xid, lsn);
4834 else if (info == XLOG_XACT_COMMIT)
4836 xl_xact_commit *xlrec = (xl_xact_commit *) XLogRecGetData(record);
4838 xact_redo_commit(xlrec, record->xl_xid, lsn);
4840 else if (info == XLOG_XACT_ABORT)
4842 xl_xact_abort *xlrec = (xl_xact_abort *) XLogRecGetData(record);
4844 xact_redo_abort(xlrec, record->xl_xid);
4846 else if (info == XLOG_XACT_PREPARE)
4848 /* the record contents are exactly the 2PC file */
4849 RecreateTwoPhaseFile(record->xl_xid,
4850 XLogRecGetData(record), record->xl_len);
4852 else if (info == XLOG_XACT_COMMIT_PREPARED)
4854 xl_xact_commit_prepared *xlrec = (xl_xact_commit_prepared *) XLogRecGetData(record);
4856 xact_redo_commit(&xlrec->crec, xlrec->xid, lsn);
4857 RemoveTwoPhaseFile(xlrec->xid, false);
4859 else if (info == XLOG_XACT_ABORT_PREPARED)
4861 xl_xact_abort_prepared *xlrec = (xl_xact_abort_prepared *) XLogRecGetData(record);
4863 xact_redo_abort(&xlrec->arec, xlrec->xid);
4864 RemoveTwoPhaseFile(xlrec->xid, false);
4866 else if (info == XLOG_XACT_ASSIGNMENT)
4868 xl_xact_assignment *xlrec = (xl_xact_assignment *) XLogRecGetData(record);
4870 if (standbyState >= STANDBY_INITIALIZED)
4871 ProcArrayApplyXidAssignment(xlrec->xtop,
4872 xlrec->nsubxacts, xlrec->xsub);
4875 elog(PANIC, "xact_redo: unknown op code %u", info);