1 /*-------------------------------------------------------------------------
4 * top level transaction system support routines
6 * See src/backend/access/transam/README for more information.
8 * Portions Copyright (c) 1996-2012, 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/lmgr.h"
42 #include "storage/predicate.h"
43 #include "storage/proc.h"
44 #include "storage/procarray.h"
45 #include "storage/sinvaladt.h"
46 #include "storage/smgr.h"
47 #include "utils/combocid.h"
48 #include "utils/guc.h"
49 #include "utils/inval.h"
50 #include "utils/memutils.h"
51 #include "utils/relmapper.h"
52 #include "utils/snapmgr.h"
53 #include "utils/timestamp.h"
58 * User-tweakable parameters
60 int DefaultXactIsoLevel = XACT_READ_COMMITTED;
63 bool DefaultXactReadOnly = false;
66 bool DefaultXactDeferrable = false;
69 int synchronous_commit = SYNCHRONOUS_COMMIT_ON;
72 * MyXactAccessedTempRel is set when a temporary relation is accessed.
73 * We don't allow PREPARE TRANSACTION in that case. (This is global
74 * so that it can be set from heapam.c.)
76 bool MyXactAccessedTempRel = false;
80 * transaction states - transaction state from server perspective
82 typedef enum TransState
84 TRANS_DEFAULT, /* idle */
85 TRANS_START, /* transaction starting */
86 TRANS_INPROGRESS, /* inside a valid transaction */
87 TRANS_COMMIT, /* commit in progress */
88 TRANS_ABORT, /* abort in progress */
89 TRANS_PREPARE /* prepare in progress */
93 * transaction block states - transaction state of client queries
95 * Note: the subtransaction states are used only for non-topmost
96 * transactions; the others appear only in the topmost transaction.
98 typedef enum TBlockState
100 /* not-in-transaction-block states */
101 TBLOCK_DEFAULT, /* idle */
102 TBLOCK_STARTED, /* running single-query transaction */
104 /* transaction block states */
105 TBLOCK_BEGIN, /* starting transaction block */
106 TBLOCK_INPROGRESS, /* live transaction */
107 TBLOCK_END, /* COMMIT received */
108 TBLOCK_ABORT, /* failed xact, awaiting ROLLBACK */
109 TBLOCK_ABORT_END, /* failed xact, ROLLBACK received */
110 TBLOCK_ABORT_PENDING, /* live xact, ROLLBACK received */
111 TBLOCK_PREPARE, /* live xact, PREPARE received */
113 /* subtransaction states */
114 TBLOCK_SUBBEGIN, /* starting a subtransaction */
115 TBLOCK_SUBINPROGRESS, /* live subtransaction */
116 TBLOCK_SUBRELEASE, /* RELEASE received */
117 TBLOCK_SUBCOMMIT, /* COMMIT received while TBLOCK_SUBINPROGRESS */
118 TBLOCK_SUBABORT, /* failed subxact, awaiting ROLLBACK */
119 TBLOCK_SUBABORT_END, /* failed subxact, ROLLBACK received */
120 TBLOCK_SUBABORT_PENDING, /* live subxact, ROLLBACK received */
121 TBLOCK_SUBRESTART, /* live subxact, ROLLBACK TO received */
122 TBLOCK_SUBABORT_RESTART /* failed subxact, ROLLBACK TO received */
126 * transaction state structure
128 typedef struct TransactionStateData
130 TransactionId transactionId; /* my XID, or Invalid if none */
131 SubTransactionId subTransactionId; /* my subxact ID */
132 char *name; /* savepoint name, if any */
133 int savepointLevel; /* savepoint level */
134 TransState state; /* low-level state */
135 TBlockState blockState; /* high-level state */
136 int nestingLevel; /* transaction nesting depth */
137 int gucNestLevel; /* GUC context nesting depth */
138 MemoryContext curTransactionContext; /* my xact-lifetime context */
139 ResourceOwner curTransactionOwner; /* my query resources */
140 TransactionId *childXids; /* subcommitted child XIDs, in XID order */
141 int nChildXids; /* # of subcommitted child XIDs */
142 int maxChildXids; /* allocated size of childXids[] */
143 Oid prevUser; /* previous CurrentUserId setting */
144 int prevSecContext; /* previous SecurityRestrictionContext */
145 bool prevXactReadOnly; /* entry-time xact r/o state */
146 bool startedInRecovery; /* did we start in recovery? */
147 struct TransactionStateData *parent; /* back link to parent */
148 } TransactionStateData;
150 typedef TransactionStateData *TransactionState;
153 * CurrentTransactionState always points to the current transaction state
154 * block. It will point to TopTransactionStateData when not in a
155 * transaction at all, or when in a top-level transaction.
157 static TransactionStateData TopTransactionStateData = {
158 0, /* transaction id */
159 0, /* subtransaction id */
160 NULL, /* savepoint name */
161 0, /* savepoint level */
162 TRANS_DEFAULT, /* transaction state */
163 TBLOCK_DEFAULT, /* transaction block state from the client
165 0, /* transaction nesting depth */
166 0, /* GUC context nesting depth */
167 NULL, /* cur transaction context */
168 NULL, /* cur transaction resource owner */
169 NULL, /* subcommitted child Xids */
170 0, /* # of subcommitted child Xids */
171 0, /* allocated size of childXids[] */
172 InvalidOid, /* previous CurrentUserId setting */
173 0, /* previous SecurityRestrictionContext */
174 false, /* entry-time xact r/o state */
175 false, /* startedInRecovery */
176 NULL /* link to parent state block */
180 * unreportedXids holds XIDs of all subtransactions that have not yet been
181 * reported in a XLOG_XACT_ASSIGNMENT record.
183 static int nUnreportedXids;
184 static TransactionId unreportedXids[PGPROC_MAX_CACHED_SUBXIDS];
186 static TransactionState CurrentTransactionState = &TopTransactionStateData;
189 * The subtransaction ID and command ID assignment counters are global
190 * to a whole transaction, so we do not keep them in the state stack.
192 static SubTransactionId currentSubTransactionId;
193 static CommandId currentCommandId;
194 static bool currentCommandIdUsed;
197 * xactStartTimestamp is the value of transaction_timestamp().
198 * stmtStartTimestamp is the value of statement_timestamp().
199 * xactStopTimestamp is the time at which we log a commit or abort WAL record.
200 * These do not change as we enter and exit subtransactions, so we don't
201 * keep them inside the TransactionState stack.
203 static TimestampTz xactStartTimestamp;
204 static TimestampTz stmtStartTimestamp;
205 static TimestampTz xactStopTimestamp;
208 * GID to be used for preparing the current transaction. This is also
209 * global to a whole transaction, so we don't keep it in the state stack.
211 static char *prepareGID;
214 * Some commands want to force synchronous commit.
216 static bool forceSyncCommit = false;
219 * Private context for transaction-abort work --- we reserve space for this
220 * at startup to ensure that AbortTransaction and AbortSubTransaction can work
221 * when we've run out of memory.
223 static MemoryContext TransactionAbortContext = NULL;
226 * List of add-on start- and end-of-xact callbacks
228 typedef struct XactCallbackItem
230 struct XactCallbackItem *next;
231 XactCallback callback;
235 static XactCallbackItem *Xact_callbacks = NULL;
238 * List of add-on start- and end-of-subxact callbacks
240 typedef struct SubXactCallbackItem
242 struct SubXactCallbackItem *next;
243 SubXactCallback callback;
245 } SubXactCallbackItem;
247 static SubXactCallbackItem *SubXact_callbacks = NULL;
250 /* local function prototypes */
251 static void AssignTransactionId(TransactionState s);
252 static void AbortTransaction(void);
253 static void AtAbort_Memory(void);
254 static void AtCleanup_Memory(void);
255 static void AtAbort_ResourceOwner(void);
256 static void AtCCI_LocalCache(void);
257 static void AtCommit_Memory(void);
258 static void AtStart_Cache(void);
259 static void AtStart_Memory(void);
260 static void AtStart_ResourceOwner(void);
261 static void CallXactCallbacks(XactEvent event);
262 static void CallSubXactCallbacks(SubXactEvent event,
263 SubTransactionId mySubid,
264 SubTransactionId parentSubid);
265 static void CleanupTransaction(void);
266 static void CommitTransaction(void);
267 static TransactionId RecordTransactionAbort(bool isSubXact);
268 static void StartTransaction(void);
270 static void StartSubTransaction(void);
271 static void CommitSubTransaction(void);
272 static void AbortSubTransaction(void);
273 static void CleanupSubTransaction(void);
274 static void PushTransaction(void);
275 static void PopTransaction(void);
277 static void AtSubAbort_Memory(void);
278 static void AtSubCleanup_Memory(void);
279 static void AtSubAbort_ResourceOwner(void);
280 static void AtSubCommit_Memory(void);
281 static void AtSubStart_Memory(void);
282 static void AtSubStart_ResourceOwner(void);
284 static void ShowTransactionState(const char *str);
285 static void ShowTransactionStateRec(TransactionState state);
286 static const char *BlockStateAsString(TBlockState blockState);
287 static const char *TransStateAsString(TransState state);
290 /* ----------------------------------------------------------------
291 * transaction state accessors
292 * ----------------------------------------------------------------
298 * This returns true if we are inside a valid transaction; that is,
299 * it is safe to initiate database access, take heavyweight locks, etc.
302 IsTransactionState(void)
304 TransactionState s = CurrentTransactionState;
307 * TRANS_DEFAULT and TRANS_ABORT are obviously unsafe states. However, we
308 * also reject the startup/shutdown states TRANS_START, TRANS_COMMIT,
309 * TRANS_PREPARE since it might be too soon or too late within those
310 * transition states to do anything interesting. Hence, the only "valid"
311 * state is TRANS_INPROGRESS.
313 return (s->state == TRANS_INPROGRESS);
317 * IsAbortedTransactionBlockState
319 * This returns true if we are within an aborted transaction block.
322 IsAbortedTransactionBlockState(void)
324 TransactionState s = CurrentTransactionState;
326 if (s->blockState == TBLOCK_ABORT ||
327 s->blockState == TBLOCK_SUBABORT)
335 * GetTopTransactionId
337 * This will return the XID of the main transaction, assigning one if
338 * it's not yet set. Be careful to call this only inside a valid xact.
341 GetTopTransactionId(void)
343 if (!TransactionIdIsValid(TopTransactionStateData.transactionId))
344 AssignTransactionId(&TopTransactionStateData);
345 return TopTransactionStateData.transactionId;
349 * GetTopTransactionIdIfAny
351 * This will return the XID of the main transaction, if one is assigned.
352 * It will return InvalidTransactionId if we are not currently inside a
353 * transaction, or inside a transaction that hasn't yet been assigned an XID.
356 GetTopTransactionIdIfAny(void)
358 return TopTransactionStateData.transactionId;
362 * GetCurrentTransactionId
364 * This will return the XID of the current transaction (main or sub
365 * transaction), assigning one if it's not yet set. Be careful to call this
366 * only inside a valid xact.
369 GetCurrentTransactionId(void)
371 TransactionState s = CurrentTransactionState;
373 if (!TransactionIdIsValid(s->transactionId))
374 AssignTransactionId(s);
375 return s->transactionId;
379 * GetCurrentTransactionIdIfAny
381 * This will return the XID of the current sub xact, if one is assigned.
382 * It will return InvalidTransactionId if we are not currently inside a
383 * transaction, or inside a transaction that hasn't been assigned an XID yet.
386 GetCurrentTransactionIdIfAny(void)
388 return CurrentTransactionState->transactionId;
392 * GetStableLatestTransactionId
394 * Get the transaction's XID if it has one, else read the next-to-be-assigned
395 * XID. Once we have a value, return that same value for the remainder of the
396 * current transaction. This is meant to provide the reference point for the
397 * age(xid) function, but might be useful for other maintenance tasks as well.
400 GetStableLatestTransactionId(void)
402 static LocalTransactionId lxid = InvalidLocalTransactionId;
403 static TransactionId stablexid = InvalidTransactionId;
405 if (lxid != MyProc->lxid)
408 stablexid = GetTopTransactionIdIfAny();
409 if (!TransactionIdIsValid(stablexid))
410 stablexid = ReadNewTransactionId();
413 Assert(TransactionIdIsValid(stablexid));
419 * AssignTransactionId
421 * Assigns a new permanent XID to the given TransactionState.
422 * We do not assign XIDs to transactions until/unless this is called.
423 * Also, any parent TransactionStates that don't yet have XIDs are assigned
424 * one; this maintains the invariant that a child transaction has an XID
425 * following its parent's.
428 AssignTransactionId(TransactionState s)
430 bool isSubXact = (s->parent != NULL);
431 ResourceOwner currentOwner;
433 /* Assert that caller didn't screw up */
434 Assert(!TransactionIdIsValid(s->transactionId));
435 Assert(s->state == TRANS_INPROGRESS);
438 * Ensure parent(s) have XIDs, so that a child always has an XID later
439 * than its parent. Musn't recurse here, or we might get a stack overflow
440 * if we're at the bottom of a huge stack of subtransactions none of which
443 if (isSubXact && !TransactionIdIsValid(s->parent->transactionId))
445 TransactionState p = s->parent;
446 TransactionState *parents;
447 size_t parentOffset = 0;
449 parents = palloc(sizeof(TransactionState) * s->nestingLevel);
450 while (p != NULL && !TransactionIdIsValid(p->transactionId))
452 parents[parentOffset++] = p;
457 * This is technically a recursive call, but the recursion will never
458 * be more than one layer deep.
460 while (parentOffset != 0)
461 AssignTransactionId(parents[--parentOffset]);
467 * Generate a new Xid and record it in PG_PROC and pg_subtrans.
469 * NB: we must make the subtrans entry BEFORE the Xid appears anywhere in
470 * shared storage other than PG_PROC; because if there's no room for it in
471 * PG_PROC, the subtrans entry is needed to ensure that other backends see
472 * the Xid as "running". See GetNewTransactionId.
474 s->transactionId = GetNewTransactionId(isSubXact);
477 SubTransSetParent(s->transactionId, s->parent->transactionId, false);
480 * If it's a top-level transaction, the predicate locking system needs to
481 * be told about it too.
484 RegisterPredicateLockingXid(s->transactionId);
487 * Acquire lock on the transaction XID. (We assume this cannot block.) We
488 * have to ensure that the lock is assigned to the transaction's own
491 currentOwner = CurrentResourceOwner;
494 CurrentResourceOwner = s->curTransactionOwner;
495 XactLockTableInsert(s->transactionId);
499 /* Ensure CurrentResourceOwner is restored on error */
500 CurrentResourceOwner = currentOwner;
504 CurrentResourceOwner = currentOwner;
507 * Every PGPROC_MAX_CACHED_SUBXIDS assigned transaction ids within each
508 * top-level transaction we issue a WAL record for the assignment. We
509 * include the top-level xid and all the subxids that have not yet been
510 * reported using XLOG_XACT_ASSIGNMENT records.
512 * This is required to limit the amount of shared memory required in a hot
513 * standby server to keep track of in-progress XIDs. See notes for
514 * RecordKnownAssignedTransactionIds().
516 * We don't keep track of the immediate parent of each subxid, only the
517 * top-level transaction that each subxact belongs to. This is correct in
518 * recovery only because aborted subtransactions are separately WAL
521 if (isSubXact && XLogStandbyInfoActive())
523 unreportedXids[nUnreportedXids] = s->transactionId;
527 * ensure this test matches similar one in
528 * RecoverPreparedTransactions()
530 if (nUnreportedXids >= PGPROC_MAX_CACHED_SUBXIDS)
532 XLogRecData rdata[2];
533 xl_xact_assignment xlrec;
536 * xtop is always set by now because we recurse up transaction
537 * stack to the highest unassigned xid and then come back down
539 xlrec.xtop = GetTopTransactionId();
540 Assert(TransactionIdIsValid(xlrec.xtop));
541 xlrec.nsubxacts = nUnreportedXids;
543 rdata[0].data = (char *) &xlrec;
544 rdata[0].len = MinSizeOfXactAssignment;
545 rdata[0].buffer = InvalidBuffer;
546 rdata[0].next = &rdata[1];
548 rdata[1].data = (char *) unreportedXids;
549 rdata[1].len = PGPROC_MAX_CACHED_SUBXIDS * sizeof(TransactionId);
550 rdata[1].buffer = InvalidBuffer;
551 rdata[1].next = NULL;
553 (void) XLogInsert(RM_XACT_ID, XLOG_XACT_ASSIGNMENT, rdata);
561 * GetCurrentSubTransactionId
564 GetCurrentSubTransactionId(void)
566 TransactionState s = CurrentTransactionState;
568 return s->subTransactionId;
573 * GetCurrentCommandId
575 * "used" must be TRUE if the caller intends to use the command ID to mark
576 * inserted/updated/deleted tuples. FALSE means the ID is being fetched
577 * for read-only purposes (ie, as a snapshot validity cutoff). See
578 * CommandCounterIncrement() for discussion.
581 GetCurrentCommandId(bool used)
583 /* this is global to a transaction, not subtransaction-local */
585 currentCommandIdUsed = true;
586 return currentCommandId;
590 * GetCurrentTransactionStartTimestamp
593 GetCurrentTransactionStartTimestamp(void)
595 return xactStartTimestamp;
599 * GetCurrentStatementStartTimestamp
602 GetCurrentStatementStartTimestamp(void)
604 return stmtStartTimestamp;
608 * GetCurrentTransactionStopTimestamp
610 * We return current time if the transaction stop time hasn't been set
611 * (which can happen if we decide we don't need to log an XLOG record).
614 GetCurrentTransactionStopTimestamp(void)
616 if (xactStopTimestamp != 0)
617 return xactStopTimestamp;
618 return GetCurrentTimestamp();
622 * SetCurrentStatementStartTimestamp
625 SetCurrentStatementStartTimestamp(void)
627 stmtStartTimestamp = GetCurrentTimestamp();
631 * SetCurrentTransactionStopTimestamp
634 SetCurrentTransactionStopTimestamp(void)
636 xactStopTimestamp = GetCurrentTimestamp();
640 * GetCurrentTransactionNestLevel
642 * Note: this will return zero when not inside any transaction, one when
643 * inside a top-level transaction, etc.
646 GetCurrentTransactionNestLevel(void)
648 TransactionState s = CurrentTransactionState;
650 return s->nestingLevel;
655 * TransactionIdIsCurrentTransactionId
658 TransactionIdIsCurrentTransactionId(TransactionId xid)
663 * We always say that BootstrapTransactionId is "not my transaction ID"
664 * even when it is (ie, during bootstrap). Along with the fact that
665 * transam.c always treats BootstrapTransactionId as already committed,
666 * this causes the tqual.c routines to see all tuples as committed, which
667 * is what we need during bootstrap. (Bootstrap mode only inserts tuples,
668 * it never updates or deletes them, so all tuples can be presumed good
671 * Likewise, InvalidTransactionId and FrozenTransactionId are certainly
672 * not my transaction ID, so we can just return "false" immediately for
673 * any non-normal XID.
675 if (!TransactionIdIsNormal(xid))
679 * We will return true for the Xid of the current subtransaction, any of
680 * its subcommitted children, any of its parents, or any of their
681 * previously subcommitted children. However, a transaction being aborted
682 * is no longer "current", even though it may still have an entry on the
685 for (s = CurrentTransactionState; s != NULL; s = s->parent)
690 if (s->state == TRANS_ABORT)
692 if (!TransactionIdIsValid(s->transactionId))
693 continue; /* it can't have any child XIDs either */
694 if (TransactionIdEquals(xid, s->transactionId))
696 /* As the childXids array is ordered, we can use binary search */
698 high = s->nChildXids - 1;
704 middle = low + (high - low) / 2;
705 probe = s->childXids[middle];
706 if (TransactionIdEquals(probe, xid))
708 else if (TransactionIdPrecedes(probe, xid))
719 * TransactionStartedDuringRecovery
721 * Returns true if the current transaction started while recovery was still
722 * in progress. Recovery might have ended since so RecoveryInProgress() might
723 * return false already.
726 TransactionStartedDuringRecovery(void)
728 return CurrentTransactionState->startedInRecovery;
732 * CommandCounterIncrement
735 CommandCounterIncrement(void)
738 * If the current value of the command counter hasn't been "used" to mark
739 * tuples, we need not increment it, since there's no need to distinguish
740 * a read-only command from others. This helps postpone command counter
741 * overflow, and keeps no-op CommandCounterIncrement operations cheap.
743 if (currentCommandIdUsed)
745 currentCommandId += 1;
746 if (currentCommandId == FirstCommandId) /* check for overflow */
748 currentCommandId -= 1;
750 (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
751 errmsg("cannot have more than 2^32-1 commands in a transaction")));
753 currentCommandIdUsed = false;
755 /* Propagate new command ID into static snapshots */
756 SnapshotSetCommandId(currentCommandId);
759 * Make any catalog changes done by the just-completed command visible
760 * in the local syscache. We obviously don't need to do this after a
761 * read-only command. (But see hacks in inval.c to make real sure we
762 * don't think a command that queued inval messages was read-only.)
771 * Interface routine to allow commands to force a synchronous commit of the
772 * current top-level transaction
775 ForceSyncCommit(void)
777 forceSyncCommit = true;
781 /* ----------------------------------------------------------------
782 * StartTransaction stuff
783 * ----------------------------------------------------------------
792 AcceptInvalidationMessages();
801 TransactionState s = CurrentTransactionState;
804 * If this is the first time through, create a private context for
805 * AbortTransaction to work in. By reserving some space now, we can
806 * insulate AbortTransaction from out-of-memory scenarios. Like
807 * ErrorContext, we set it up with slow growth rate and a nonzero minimum
808 * size, so that space will be reserved immediately.
810 if (TransactionAbortContext == NULL)
811 TransactionAbortContext =
812 AllocSetContextCreate(TopMemoryContext,
813 "TransactionAbortContext",
819 * We shouldn't have a transaction context already.
821 Assert(TopTransactionContext == NULL);
824 * Create a toplevel context for the transaction.
826 TopTransactionContext =
827 AllocSetContextCreate(TopMemoryContext,
828 "TopTransactionContext",
829 ALLOCSET_DEFAULT_MINSIZE,
830 ALLOCSET_DEFAULT_INITSIZE,
831 ALLOCSET_DEFAULT_MAXSIZE);
834 * In a top-level transaction, CurTransactionContext is the same as
835 * TopTransactionContext.
837 CurTransactionContext = TopTransactionContext;
838 s->curTransactionContext = CurTransactionContext;
840 /* Make the CurTransactionContext active. */
841 MemoryContextSwitchTo(CurTransactionContext);
845 * AtStart_ResourceOwner
848 AtStart_ResourceOwner(void)
850 TransactionState s = CurrentTransactionState;
853 * We shouldn't have a transaction resource owner already.
855 Assert(TopTransactionResourceOwner == NULL);
858 * Create a toplevel resource owner for the transaction.
860 s->curTransactionOwner = ResourceOwnerCreate(NULL, "TopTransaction");
862 TopTransactionResourceOwner = s->curTransactionOwner;
863 CurTransactionResourceOwner = s->curTransactionOwner;
864 CurrentResourceOwner = s->curTransactionOwner;
867 /* ----------------------------------------------------------------
868 * StartSubTransaction stuff
869 * ----------------------------------------------------------------
876 AtSubStart_Memory(void)
878 TransactionState s = CurrentTransactionState;
880 Assert(CurTransactionContext != NULL);
883 * Create a CurTransactionContext, which will be used to hold data that
884 * survives subtransaction commit but disappears on subtransaction abort.
885 * We make it a child of the immediate parent's CurTransactionContext.
887 CurTransactionContext = AllocSetContextCreate(CurTransactionContext,
888 "CurTransactionContext",
889 ALLOCSET_DEFAULT_MINSIZE,
890 ALLOCSET_DEFAULT_INITSIZE,
891 ALLOCSET_DEFAULT_MAXSIZE);
892 s->curTransactionContext = CurTransactionContext;
894 /* Make the CurTransactionContext active. */
895 MemoryContextSwitchTo(CurTransactionContext);
899 * AtSubStart_ResourceOwner
902 AtSubStart_ResourceOwner(void)
904 TransactionState s = CurrentTransactionState;
906 Assert(s->parent != NULL);
909 * Create a resource owner for the subtransaction. We make it a child of
910 * the immediate parent's resource owner.
912 s->curTransactionOwner =
913 ResourceOwnerCreate(s->parent->curTransactionOwner,
916 CurTransactionResourceOwner = s->curTransactionOwner;
917 CurrentResourceOwner = s->curTransactionOwner;
920 /* ----------------------------------------------------------------
921 * CommitTransaction stuff
922 * ----------------------------------------------------------------
926 * RecordTransactionCommit
928 * Returns latest XID among xact and its children, or InvalidTransactionId
929 * if the xact has no XID. (We compute that here just because it's easier.)
932 RecordTransactionCommit(void)
934 TransactionId xid = GetTopTransactionIdIfAny();
935 bool markXidCommitted = TransactionIdIsValid(xid);
936 TransactionId latestXid = InvalidTransactionId;
940 TransactionId *children;
942 SharedInvalidationMessage *invalMessages = NULL;
943 bool RelcacheInitFileInval = false;
946 /* Get data needed for commit record */
947 nrels = smgrGetPendingDeletes(true, &rels);
948 nchildren = xactGetCommittedChildren(&children);
949 if (XLogStandbyInfoActive())
950 nmsgs = xactGetCommittedInvalidationMessages(&invalMessages,
951 &RelcacheInitFileInval);
952 wrote_xlog = (XactLastRecEnd != 0);
955 * If we haven't been assigned an XID yet, we neither can, nor do we want
956 * to write a COMMIT record.
958 if (!markXidCommitted)
961 * We expect that every smgrscheduleunlink is followed by a catalog
962 * update, and hence XID assignment, so we shouldn't get here with any
963 * pending deletes. Use a real test not just an Assert to check this,
964 * since it's a bit fragile.
967 elog(ERROR, "cannot commit a transaction that deleted files but has no xid");
969 /* Can't have child XIDs either; AssignTransactionId enforces this */
970 Assert(nchildren == 0);
973 * If we didn't create XLOG entries, we're done here; otherwise we
974 * should flush those entries the same as a commit record. (An
975 * example of a possible record that wouldn't cause an XID to be
976 * assigned is a sequence advance record due to nextval() --- we want
977 * to flush that to disk before reporting commit.)
985 * Begin commit critical section and insert the commit XLOG record.
987 /* Tell bufmgr and smgr to prepare for commit */
991 * Mark ourselves as within our "commit critical section". This
992 * forces any concurrent checkpoint to wait until we've updated
993 * pg_clog. Without this, it is possible for the checkpoint to set
994 * REDO after the XLOG record but fail to flush the pg_clog update to
995 * disk, leading to loss of the transaction commit if the system
996 * crashes a little later.
998 * Note: we could, but don't bother to, set this flag in
999 * RecordTransactionAbort. That's because loss of a transaction abort
1000 * is noncritical; the presumption would be that it aborted, anyway.
1002 * It's safe to change the inCommit flag of our own backend without
1003 * holding the ProcArrayLock, since we're the only one modifying it.
1004 * This makes checkpoint's determination of which xacts are inCommit a
1005 * bit fuzzy, but it doesn't matter.
1007 START_CRIT_SECTION();
1008 MyPgXact->inCommit = true;
1010 SetCurrentTransactionStopTimestamp();
1013 * Do we need the long commit record? If not, use the compact format.
1015 if (nrels > 0 || nmsgs > 0 || RelcacheInitFileInval || forceSyncCommit)
1017 XLogRecData rdata[4];
1019 xl_xact_commit xlrec;
1022 * Set flags required for recovery processing of commits.
1025 if (RelcacheInitFileInval)
1026 xlrec.xinfo |= XACT_COMPLETION_UPDATE_RELCACHE_FILE;
1027 if (forceSyncCommit)
1028 xlrec.xinfo |= XACT_COMPLETION_FORCE_SYNC_COMMIT;
1030 xlrec.dbId = MyDatabaseId;
1031 xlrec.tsId = MyDatabaseTableSpace;
1033 xlrec.xact_time = xactStopTimestamp;
1034 xlrec.nrels = nrels;
1035 xlrec.nsubxacts = nchildren;
1036 xlrec.nmsgs = nmsgs;
1037 rdata[0].data = (char *) (&xlrec);
1038 rdata[0].len = MinSizeOfXactCommit;
1039 rdata[0].buffer = InvalidBuffer;
1040 /* dump rels to delete */
1043 rdata[0].next = &(rdata[1]);
1044 rdata[1].data = (char *) rels;
1045 rdata[1].len = nrels * sizeof(RelFileNode);
1046 rdata[1].buffer = InvalidBuffer;
1049 /* dump committed child Xids */
1052 rdata[lastrdata].next = &(rdata[2]);
1053 rdata[2].data = (char *) children;
1054 rdata[2].len = nchildren * sizeof(TransactionId);
1055 rdata[2].buffer = InvalidBuffer;
1058 /* dump shared cache invalidation messages */
1061 rdata[lastrdata].next = &(rdata[3]);
1062 rdata[3].data = (char *) invalMessages;
1063 rdata[3].len = nmsgs * sizeof(SharedInvalidationMessage);
1064 rdata[3].buffer = InvalidBuffer;
1067 rdata[lastrdata].next = NULL;
1069 (void) XLogInsert(RM_XACT_ID, XLOG_XACT_COMMIT, rdata);
1073 XLogRecData rdata[2];
1075 xl_xact_commit_compact xlrec;
1077 xlrec.xact_time = xactStopTimestamp;
1078 xlrec.nsubxacts = nchildren;
1079 rdata[0].data = (char *) (&xlrec);
1080 rdata[0].len = MinSizeOfXactCommitCompact;
1081 rdata[0].buffer = InvalidBuffer;
1082 /* dump committed child Xids */
1085 rdata[0].next = &(rdata[1]);
1086 rdata[1].data = (char *) children;
1087 rdata[1].len = nchildren * sizeof(TransactionId);
1088 rdata[1].buffer = InvalidBuffer;
1091 rdata[lastrdata].next = NULL;
1093 (void) XLogInsert(RM_XACT_ID, XLOG_XACT_COMMIT_COMPACT, rdata);
1098 * Check if we want to commit asynchronously. We can allow the XLOG flush
1099 * to happen asynchronously if synchronous_commit=off, or if the current
1100 * transaction has not performed any WAL-logged operation. The latter
1101 * case can arise if the current transaction wrote only to temporary
1102 * and/or unlogged tables. In case of a crash, the loss of such a
1103 * transaction will be irrelevant since temp tables will be lost anyway,
1104 * and unlogged tables will be truncated. (Given the foregoing, you might
1105 * think that it would be unnecessary to emit the XLOG record at all in
1106 * this case, but we don't currently try to do that. It would certainly
1107 * cause problems at least in Hot Standby mode, where the
1108 * KnownAssignedXids machinery requires tracking every XID assignment. It
1109 * might be OK to skip it only when wal_level < hot_standby, but for now
1112 * However, if we're doing cleanup of any non-temp rels or committing any
1113 * command that wanted to force sync commit, then we must flush XLOG
1114 * immediately. (We must not allow asynchronous commit if there are any
1115 * non-temp tables to be deleted, because we might delete the files before
1116 * the COMMIT record is flushed to disk. We do allow asynchronous commit
1117 * if all to-be-deleted tables are temporary though, since they are lost
1118 * anyway if we crash.)
1120 if ((wrote_xlog && synchronous_commit > SYNCHRONOUS_COMMIT_OFF) ||
1121 forceSyncCommit || nrels > 0)
1123 XLogFlush(XactLastRecEnd);
1126 * Now we may update the CLOG, if we wrote a COMMIT record above
1128 if (markXidCommitted)
1129 TransactionIdCommitTree(xid, nchildren, children);
1134 * Asynchronous commit case:
1136 * This enables possible committed transaction loss in the case of a
1137 * postmaster crash because WAL buffers are left unwritten. Ideally we
1138 * could issue the WAL write without the fsync, but some
1139 * wal_sync_methods do not allow separate write/fsync.
1141 * Report the latest async commit LSN, so that the WAL writer knows to
1142 * flush this commit.
1144 XLogSetAsyncXactLSN(XactLastRecEnd);
1147 * We must not immediately update the CLOG, since we didn't flush the
1148 * XLOG. Instead, we store the LSN up to which the XLOG must be
1149 * flushed before the CLOG may be updated.
1151 if (markXidCommitted)
1152 TransactionIdAsyncCommitTree(xid, nchildren, children, XactLastRecEnd);
1156 * If we entered a commit critical section, leave it now, and let
1157 * checkpoints proceed.
1159 if (markXidCommitted)
1161 MyPgXact->inCommit = false;
1165 /* Compute latestXid while we have the child XIDs handy */
1166 latestXid = TransactionIdLatest(xid, nchildren, children);
1169 * Wait for synchronous replication, if required.
1171 * Note that at this stage we have marked clog, but still show as running
1172 * in the procarray and continue to hold locks.
1175 SyncRepWaitForLSN(XactLastRecEnd);
1177 /* Reset XactLastRecEnd until the next transaction writes something */
1181 /* Clean up local data */
1193 AtCCI_LocalCache(void)
1196 * Make any pending relation map changes visible. We must do this before
1197 * processing local sinval messages, so that the map changes will get
1198 * reflected into the relcache when relcache invals are processed.
1200 AtCCI_RelationMap();
1203 * Make catalog changes visible to me for the next command.
1205 CommandEndInvalidationMessages();
1212 AtCommit_Memory(void)
1215 * Now that we're "out" of a transaction, have the system allocate things
1216 * in the top memory context instead of per-transaction contexts.
1218 MemoryContextSwitchTo(TopMemoryContext);
1221 * Release all transaction-local memory.
1223 Assert(TopTransactionContext != NULL);
1224 MemoryContextDelete(TopTransactionContext);
1225 TopTransactionContext = NULL;
1226 CurTransactionContext = NULL;
1227 CurrentTransactionState->curTransactionContext = NULL;
1230 /* ----------------------------------------------------------------
1231 * CommitSubTransaction stuff
1232 * ----------------------------------------------------------------
1236 * AtSubCommit_Memory
1239 AtSubCommit_Memory(void)
1241 TransactionState s = CurrentTransactionState;
1243 Assert(s->parent != NULL);
1245 /* Return to parent transaction level's memory context. */
1246 CurTransactionContext = s->parent->curTransactionContext;
1247 MemoryContextSwitchTo(CurTransactionContext);
1250 * Ordinarily we cannot throw away the child's CurTransactionContext,
1251 * since the data it contains will be needed at upper commit. However, if
1252 * there isn't actually anything in it, we can throw it away. This avoids
1253 * a small memory leak in the common case of "trivial" subxacts.
1255 if (MemoryContextIsEmpty(s->curTransactionContext))
1257 MemoryContextDelete(s->curTransactionContext);
1258 s->curTransactionContext = NULL;
1263 * AtSubCommit_childXids
1265 * Pass my own XID and my child XIDs up to my parent as committed children.
1268 AtSubCommit_childXids(void)
1270 TransactionState s = CurrentTransactionState;
1273 Assert(s->parent != NULL);
1276 * The parent childXids array will need to hold my XID and all my
1277 * childXids, in addition to the XIDs already there.
1279 new_nChildXids = s->parent->nChildXids + s->nChildXids + 1;
1281 /* Allocate or enlarge the parent array if necessary */
1282 if (s->parent->maxChildXids < new_nChildXids)
1284 int new_maxChildXids;
1285 TransactionId *new_childXids;
1288 * Make it 2x what's needed right now, to avoid having to enlarge it
1289 * repeatedly. But we can't go above MaxAllocSize. (The latter limit
1290 * is what ensures that we don't need to worry about integer overflow
1291 * here or in the calculation of new_nChildXids.)
1293 new_maxChildXids = Min(new_nChildXids * 2,
1294 (int) (MaxAllocSize / sizeof(TransactionId)));
1296 if (new_maxChildXids < new_nChildXids)
1298 (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
1299 errmsg("maximum number of committed subtransactions (%d) exceeded",
1300 (int) (MaxAllocSize / sizeof(TransactionId)))));
1303 * We keep the child-XID arrays in TopTransactionContext; this avoids
1304 * setting up child-transaction contexts for what might be just a few
1305 * bytes of grandchild XIDs.
1307 if (s->parent->childXids == NULL)
1309 MemoryContextAlloc(TopTransactionContext,
1310 new_maxChildXids * sizeof(TransactionId));
1312 new_childXids = repalloc(s->parent->childXids,
1313 new_maxChildXids * sizeof(TransactionId));
1315 s->parent->childXids = new_childXids;
1316 s->parent->maxChildXids = new_maxChildXids;
1320 * Copy all my XIDs to parent's array.
1322 * Note: We rely on the fact that the XID of a child always follows that
1323 * of its parent. By copying the XID of this subtransaction before the
1324 * XIDs of its children, we ensure that the array stays ordered. Likewise,
1325 * all XIDs already in the array belong to subtransactions started and
1326 * subcommitted before us, so their XIDs must precede ours.
1328 s->parent->childXids[s->parent->nChildXids] = s->transactionId;
1330 if (s->nChildXids > 0)
1331 memcpy(&s->parent->childXids[s->parent->nChildXids + 1],
1333 s->nChildXids * sizeof(TransactionId));
1335 s->parent->nChildXids = new_nChildXids;
1337 /* Release child's array to avoid leakage */
1338 if (s->childXids != NULL)
1339 pfree(s->childXids);
1340 /* We must reset these to avoid double-free if fail later in commit */
1341 s->childXids = NULL;
1343 s->maxChildXids = 0;
1346 /* ----------------------------------------------------------------
1347 * AbortTransaction stuff
1348 * ----------------------------------------------------------------
1352 * RecordTransactionAbort
1354 * Returns latest XID among xact and its children, or InvalidTransactionId
1355 * if the xact has no XID. (We compute that here just because it's easier.)
1357 static TransactionId
1358 RecordTransactionAbort(bool isSubXact)
1360 TransactionId xid = GetCurrentTransactionIdIfAny();
1361 TransactionId latestXid;
1365 TransactionId *children;
1366 XLogRecData rdata[3];
1368 xl_xact_abort xlrec;
1371 * If we haven't been assigned an XID, nobody will care whether we aborted
1372 * or not. Hence, we're done in that case. It does not matter if we have
1373 * rels to delete (note that this routine is not responsible for actually
1374 * deleting 'em). We cannot have any child XIDs, either.
1376 if (!TransactionIdIsValid(xid))
1378 /* Reset XactLastRecEnd until the next transaction writes something */
1381 return InvalidTransactionId;
1385 * We have a valid XID, so we should write an ABORT record for it.
1387 * We do not flush XLOG to disk here, since the default assumption after a
1388 * crash would be that we aborted, anyway. For the same reason, we don't
1389 * need to worry about interlocking against checkpoint start.
1393 * Check that we haven't aborted halfway through RecordTransactionCommit.
1395 if (TransactionIdDidCommit(xid))
1396 elog(PANIC, "cannot abort transaction %u, it was already committed",
1399 /* Fetch the data we need for the abort record */
1400 nrels = smgrGetPendingDeletes(false, &rels);
1401 nchildren = xactGetCommittedChildren(&children);
1403 /* XXX do we really need a critical section here? */
1404 START_CRIT_SECTION();
1406 /* Write the ABORT record */
1408 xlrec.xact_time = GetCurrentTimestamp();
1411 SetCurrentTransactionStopTimestamp();
1412 xlrec.xact_time = xactStopTimestamp;
1414 xlrec.nrels = nrels;
1415 xlrec.nsubxacts = nchildren;
1416 rdata[0].data = (char *) (&xlrec);
1417 rdata[0].len = MinSizeOfXactAbort;
1418 rdata[0].buffer = InvalidBuffer;
1419 /* dump rels to delete */
1422 rdata[0].next = &(rdata[1]);
1423 rdata[1].data = (char *) rels;
1424 rdata[1].len = nrels * sizeof(RelFileNode);
1425 rdata[1].buffer = InvalidBuffer;
1428 /* dump committed child Xids */
1431 rdata[lastrdata].next = &(rdata[2]);
1432 rdata[2].data = (char *) children;
1433 rdata[2].len = nchildren * sizeof(TransactionId);
1434 rdata[2].buffer = InvalidBuffer;
1437 rdata[lastrdata].next = NULL;
1439 (void) XLogInsert(RM_XACT_ID, XLOG_XACT_ABORT, rdata);
1442 * Report the latest async abort LSN, so that the WAL writer knows to
1443 * flush this abort. There's nothing to be gained by delaying this, since
1444 * WALWriter may as well do this when it can. This is important with
1445 * streaming replication because if we don't flush WAL regularly we will
1446 * find that large aborts leave us with a long backlog for when commits
1447 * occur after the abort, increasing our window of data loss should
1448 * problems occur at that point.
1451 XLogSetAsyncXactLSN(XactLastRecEnd);
1454 * Mark the transaction aborted in clog. This is not absolutely necessary
1455 * but we may as well do it while we are here; also, in the subxact case
1456 * it is helpful because XactLockTableWait makes use of it to avoid
1457 * waiting for already-aborted subtransactions. It is OK to do it without
1458 * having flushed the ABORT record to disk, because in event of a crash
1459 * we'd be assumed to have aborted anyway.
1461 TransactionIdAbortTree(xid, nchildren, children);
1465 /* Compute latestXid while we have the child XIDs handy */
1466 latestXid = TransactionIdLatest(xid, nchildren, children);
1469 * If we're aborting a subtransaction, we can immediately remove failed
1470 * XIDs from PGPROC's cache of running child XIDs. We do that here for
1471 * subxacts, because we already have the child XID array at hand. For
1472 * main xacts, the equivalent happens just after this function returns.
1475 XidCacheRemoveRunningXids(xid, nchildren, children, latestXid);
1477 /* Reset XactLastRecEnd until the next transaction writes something */
1481 /* And clean up local data */
1492 AtAbort_Memory(void)
1495 * Switch into TransactionAbortContext, which should have some free space
1496 * even if nothing else does. We'll work in this context until we've
1497 * finished cleaning up.
1499 * It is barely possible to get here when we've not been able to create
1500 * TransactionAbortContext yet; if so use TopMemoryContext.
1502 if (TransactionAbortContext != NULL)
1503 MemoryContextSwitchTo(TransactionAbortContext);
1505 MemoryContextSwitchTo(TopMemoryContext);
1512 AtSubAbort_Memory(void)
1514 Assert(TransactionAbortContext != NULL);
1516 MemoryContextSwitchTo(TransactionAbortContext);
1521 * AtAbort_ResourceOwner
1524 AtAbort_ResourceOwner(void)
1527 * Make sure we have a valid ResourceOwner, if possible (else it will be
1528 * NULL, which is OK)
1530 CurrentResourceOwner = TopTransactionResourceOwner;
1534 * AtSubAbort_ResourceOwner
1537 AtSubAbort_ResourceOwner(void)
1539 TransactionState s = CurrentTransactionState;
1541 /* Make sure we have a valid ResourceOwner */
1542 CurrentResourceOwner = s->curTransactionOwner;
1547 * AtSubAbort_childXids
1550 AtSubAbort_childXids(void)
1552 TransactionState s = CurrentTransactionState;
1555 * We keep the child-XID arrays in TopTransactionContext (see
1556 * AtSubCommit_childXids). This means we'd better free the array
1557 * explicitly at abort to avoid leakage.
1559 if (s->childXids != NULL)
1560 pfree(s->childXids);
1561 s->childXids = NULL;
1563 s->maxChildXids = 0;
1566 * We could prune the unreportedXids array here. But we don't bother. That
1567 * would potentially reduce number of XLOG_XACT_ASSIGNMENT records but it
1568 * would likely introduce more CPU time into the more common paths, so we
1569 * choose not to do that.
1573 /* ----------------------------------------------------------------
1574 * CleanupTransaction stuff
1575 * ----------------------------------------------------------------
1582 AtCleanup_Memory(void)
1584 Assert(CurrentTransactionState->parent == NULL);
1587 * Now that we're "out" of a transaction, have the system allocate things
1588 * in the top memory context instead of per-transaction contexts.
1590 MemoryContextSwitchTo(TopMemoryContext);
1593 * Clear the special abort context for next time.
1595 if (TransactionAbortContext != NULL)
1596 MemoryContextResetAndDeleteChildren(TransactionAbortContext);
1599 * Release all transaction-local memory.
1601 if (TopTransactionContext != NULL)
1602 MemoryContextDelete(TopTransactionContext);
1603 TopTransactionContext = NULL;
1604 CurTransactionContext = NULL;
1605 CurrentTransactionState->curTransactionContext = NULL;
1609 /* ----------------------------------------------------------------
1610 * CleanupSubTransaction stuff
1611 * ----------------------------------------------------------------
1615 * AtSubCleanup_Memory
1618 AtSubCleanup_Memory(void)
1620 TransactionState s = CurrentTransactionState;
1622 Assert(s->parent != NULL);
1624 /* Make sure we're not in an about-to-be-deleted context */
1625 MemoryContextSwitchTo(s->parent->curTransactionContext);
1626 CurTransactionContext = s->parent->curTransactionContext;
1629 * Clear the special abort context for next time.
1631 if (TransactionAbortContext != NULL)
1632 MemoryContextResetAndDeleteChildren(TransactionAbortContext);
1635 * Delete the subxact local memory contexts. Its CurTransactionContext can
1636 * go too (note this also kills CurTransactionContexts from any children
1639 if (s->curTransactionContext)
1640 MemoryContextDelete(s->curTransactionContext);
1641 s->curTransactionContext = NULL;
1644 /* ----------------------------------------------------------------
1645 * interface routines
1646 * ----------------------------------------------------------------
1653 StartTransaction(void)
1656 VirtualTransactionId vxid;
1659 * Let's just make sure the state stack is empty
1661 s = &TopTransactionStateData;
1662 CurrentTransactionState = s;
1665 * check the current transaction state
1667 if (s->state != TRANS_DEFAULT)
1668 elog(WARNING, "StartTransaction while in %s state",
1669 TransStateAsString(s->state));
1672 * set the current transaction state information appropriately during
1675 s->state = TRANS_START;
1676 s->transactionId = InvalidTransactionId; /* until assigned */
1679 * Make sure we've reset xact state variables
1681 * If recovery is still in progress, mark this transaction as read-only.
1682 * We have lower level defences in XLogInsert and elsewhere to stop us
1683 * from modifying data during recovery, but this gives the normal
1684 * indication to the user that the transaction is read-only.
1686 if (RecoveryInProgress())
1688 s->startedInRecovery = true;
1689 XactReadOnly = true;
1693 s->startedInRecovery = false;
1694 XactReadOnly = DefaultXactReadOnly;
1696 XactDeferrable = DefaultXactDeferrable;
1697 XactIsoLevel = DefaultXactIsoLevel;
1698 forceSyncCommit = false;
1699 MyXactAccessedTempRel = false;
1702 * reinitialize within-transaction counters
1704 s->subTransactionId = TopSubTransactionId;
1705 currentSubTransactionId = TopSubTransactionId;
1706 currentCommandId = FirstCommandId;
1707 currentCommandIdUsed = false;
1710 * initialize reported xid accounting
1712 nUnreportedXids = 0;
1715 * must initialize resource-management stuff first
1718 AtStart_ResourceOwner();
1721 * Assign a new LocalTransactionId, and combine it with the backendId to
1722 * form a virtual transaction id.
1724 vxid.backendId = MyBackendId;
1725 vxid.localTransactionId = GetNextLocalTransactionId();
1728 * Lock the virtual transaction id before we announce it in the proc array
1730 VirtualXactLockTableInsert(vxid);
1733 * Advertise it in the proc array. We assume assignment of
1734 * LocalTransactionID is atomic, and the backendId should be set already.
1736 Assert(MyProc->backendId == vxid.backendId);
1737 MyProc->lxid = vxid.localTransactionId;
1739 TRACE_POSTGRESQL_TRANSACTION_START(vxid.localTransactionId);
1742 * set transaction_timestamp() (a/k/a now()). We want this to be the same
1743 * as the first command's statement_timestamp(), so don't do a fresh
1744 * GetCurrentTimestamp() call (which'd be expensive anyway). Also, mark
1745 * xactStopTimestamp as unset.
1747 xactStartTimestamp = stmtStartTimestamp;
1748 xactStopTimestamp = 0;
1749 pgstat_report_xact_timestamp(xactStartTimestamp);
1752 * initialize current transaction state fields
1754 * note: prevXactReadOnly is not used at the outermost level
1756 s->nestingLevel = 1;
1757 s->gucNestLevel = 1;
1758 s->childXids = NULL;
1760 s->maxChildXids = 0;
1761 GetUserIdAndSecContext(&s->prevUser, &s->prevSecContext);
1762 /* SecurityRestrictionContext should never be set outside a transaction */
1763 Assert(s->prevSecContext == 0);
1766 * initialize other subsystems for new transaction
1771 AfterTriggerBeginXact();
1774 * done with start processing, set current transaction state to "in
1777 s->state = TRANS_INPROGRESS;
1779 ShowTransactionState("StartTransaction");
1786 * NB: if you change this routine, better look at PrepareTransaction too!
1789 CommitTransaction(void)
1791 TransactionState s = CurrentTransactionState;
1792 TransactionId latestXid;
1794 ShowTransactionState("CommitTransaction");
1797 * check the current transaction state
1799 if (s->state != TRANS_INPROGRESS)
1800 elog(WARNING, "CommitTransaction while in %s state",
1801 TransStateAsString(s->state));
1802 Assert(s->parent == NULL);
1805 * Do pre-commit processing that involves calling user-defined code, such
1806 * as triggers. Since closing cursors could queue trigger actions,
1807 * triggers could open cursors, etc, we have to keep looping until there's
1808 * nothing left to do.
1813 * Fire all currently pending deferred triggers.
1815 AfterTriggerFireDeferred();
1818 * Close open portals (converting holdable ones into static portals).
1819 * If there weren't any, we are done ... otherwise loop back to check
1820 * if they queued deferred triggers. Lather, rinse, repeat.
1822 if (!PreCommit_Portals(false))
1827 * The remaining actions cannot call any user-defined code, so it's safe
1828 * to start shutting down within-transaction services. But note that most
1829 * of this stuff could still throw an error, which would switch us into
1830 * the transaction-abort path.
1833 /* Shut down the deferred-trigger manager */
1834 AfterTriggerEndXact(true);
1837 * Let ON COMMIT management do its thing (must happen after closing
1838 * cursors, to avoid dangling-reference problems)
1840 PreCommit_on_commit_actions();
1842 /* close large objects before lower-level cleanup */
1843 AtEOXact_LargeObject(true);
1846 * Mark serializable transaction as complete for predicate locking
1847 * purposes. This should be done as late as we can put it and still allow
1848 * errors to be raised for failure patterns found at commit.
1850 PreCommit_CheckForSerializationFailure();
1853 * Insert notifications sent by NOTIFY commands into the queue. This
1854 * should be late in the pre-commit sequence to minimize time spent
1855 * holding the notify-insertion lock.
1859 /* Prevent cancel/die interrupt while cleaning up */
1862 /* Commit updates to the relation map --- do this as late as possible */
1863 AtEOXact_RelationMap(true);
1866 * set the current transaction state information appropriately during
1869 s->state = TRANS_COMMIT;
1872 * Here is where we really truly commit.
1874 latestXid = RecordTransactionCommit();
1876 TRACE_POSTGRESQL_TRANSACTION_COMMIT(MyProc->lxid);
1879 * Let others know about no transaction in progress by me. Note that this
1880 * must be done _before_ releasing locks we hold and _after_
1881 * RecordTransactionCommit.
1883 ProcArrayEndTransaction(MyProc, latestXid);
1886 * This is all post-commit cleanup. Note that if an error is raised here,
1887 * it's too late to abort the transaction. This should be just
1888 * noncritical resource releasing.
1890 * The ordering of operations is not entirely random. The idea is:
1891 * release resources visible to other backends (eg, files, buffer pins);
1892 * then release locks; then release backend-local resources. We want to
1893 * release locks at the point where any backend waiting for us will see
1894 * our transaction as being fully cleaned up.
1896 * Resources that can be associated with individual queries are handled by
1897 * the ResourceOwner mechanism. The other calls here are for backend-wide
1901 CallXactCallbacks(XACT_EVENT_COMMIT);
1903 ResourceOwnerRelease(TopTransactionResourceOwner,
1904 RESOURCE_RELEASE_BEFORE_LOCKS,
1907 /* Check we've released all buffer pins */
1908 AtEOXact_Buffers(true);
1910 /* Clean up the relation cache */
1911 AtEOXact_RelationCache(true);
1914 * Make catalog changes visible to all backends. This has to happen after
1915 * relcache references are dropped (see comments for
1916 * AtEOXact_RelationCache), but before locks are released (if anyone is
1917 * waiting for lock on a relation we've modified, we want them to know
1918 * about the catalog change before they start using the relation).
1920 AtEOXact_Inval(true);
1922 AtEOXact_MultiXact();
1924 ResourceOwnerRelease(TopTransactionResourceOwner,
1925 RESOURCE_RELEASE_LOCKS,
1927 ResourceOwnerRelease(TopTransactionResourceOwner,
1928 RESOURCE_RELEASE_AFTER_LOCKS,
1932 * Likewise, dropping of files deleted during the transaction is best done
1933 * after releasing relcache and buffer pins. (This is not strictly
1934 * necessary during commit, since such pins should have been released
1935 * already, but this ordering is definitely critical during abort.) Since
1936 * this may take many seconds, also delay until after releasing locks.
1937 * Other backends will observe the attendant catalog changes and not
1938 * attempt to access affected files.
1940 smgrDoPendingDeletes(true);
1942 /* Check we've released all catcache entries */
1943 AtEOXact_CatCache(true);
1946 AtEOXact_GUC(true, 1);
1948 AtEOXact_on_commit_actions(true);
1949 AtEOXact_Namespace(true);
1950 /* smgrcommit already done */
1952 AtEOXact_ComboCid();
1953 AtEOXact_HashTables(true);
1954 AtEOXact_PgStat(true);
1955 AtEOXact_Snapshot(true);
1956 pgstat_report_xact_timestamp(0);
1958 CurrentResourceOwner = NULL;
1959 ResourceOwnerDelete(TopTransactionResourceOwner);
1960 s->curTransactionOwner = NULL;
1961 CurTransactionResourceOwner = NULL;
1962 TopTransactionResourceOwner = NULL;
1966 s->transactionId = InvalidTransactionId;
1967 s->subTransactionId = InvalidSubTransactionId;
1968 s->nestingLevel = 0;
1969 s->gucNestLevel = 0;
1970 s->childXids = NULL;
1972 s->maxChildXids = 0;
1975 * done with commit processing, set current transaction state back to
1978 s->state = TRANS_DEFAULT;
1980 RESUME_INTERRUPTS();
1985 * PrepareTransaction
1987 * NB: if you change this routine, better look at CommitTransaction too!
1990 PrepareTransaction(void)
1992 TransactionState s = CurrentTransactionState;
1993 TransactionId xid = GetCurrentTransactionId();
1994 GlobalTransaction gxact;
1995 TimestampTz prepared_at;
1997 ShowTransactionState("PrepareTransaction");
2000 * check the current transaction state
2002 if (s->state != TRANS_INPROGRESS)
2003 elog(WARNING, "PrepareTransaction while in %s state",
2004 TransStateAsString(s->state));
2005 Assert(s->parent == NULL);
2008 * Do pre-commit processing that involves calling user-defined code, such
2009 * as triggers. Since closing cursors could queue trigger actions,
2010 * triggers could open cursors, etc, we have to keep looping until there's
2011 * nothing left to do.
2016 * Fire all currently pending deferred triggers.
2018 AfterTriggerFireDeferred();
2021 * Close open portals (converting holdable ones into static portals).
2022 * If there weren't any, we are done ... otherwise loop back to check
2023 * if they queued deferred triggers. Lather, rinse, repeat.
2025 if (!PreCommit_Portals(true))
2030 * The remaining actions cannot call any user-defined code, so it's safe
2031 * to start shutting down within-transaction services. But note that most
2032 * of this stuff could still throw an error, which would switch us into
2033 * the transaction-abort path.
2036 /* Shut down the deferred-trigger manager */
2037 AfterTriggerEndXact(true);
2040 * Let ON COMMIT management do its thing (must happen after closing
2041 * cursors, to avoid dangling-reference problems)
2043 PreCommit_on_commit_actions();
2045 /* close large objects before lower-level cleanup */
2046 AtEOXact_LargeObject(true);
2049 * Mark serializable transaction as complete for predicate locking
2050 * purposes. This should be done as late as we can put it and still allow
2051 * errors to be raised for failure patterns found at commit.
2053 PreCommit_CheckForSerializationFailure();
2055 /* NOTIFY will be handled below */
2058 * Don't allow PREPARE TRANSACTION if we've accessed a temporary table in
2059 * this transaction. Having the prepared xact hold locks on another
2060 * backend's temp table seems a bad idea --- for instance it would prevent
2061 * the backend from exiting. There are other problems too, such as how to
2062 * clean up the source backend's local buffers and ON COMMIT state if the
2063 * prepared xact includes a DROP of a temp table.
2065 * We must check this after executing any ON COMMIT actions, because they
2066 * might still access a temp relation.
2068 * XXX In principle this could be relaxed to allow some useful special
2069 * cases, such as a temp table created and dropped all within the
2070 * transaction. That seems to require much more bookkeeping though.
2072 if (MyXactAccessedTempRel)
2074 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2075 errmsg("cannot PREPARE a transaction that has operated on temporary tables")));
2078 * Likewise, don't allow PREPARE after pg_export_snapshot. This could be
2079 * supported if we added cleanup logic to twophase.c, but for now it
2080 * doesn't seem worth the trouble.
2082 if (XactHasExportedSnapshots())
2084 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2085 errmsg("cannot PREPARE a transaction that has exported snapshots")));
2087 /* Prevent cancel/die interrupt while cleaning up */
2091 * set the current transaction state information appropriately during
2092 * prepare processing
2094 s->state = TRANS_PREPARE;
2096 prepared_at = GetCurrentTimestamp();
2098 /* Tell bufmgr and smgr to prepare for commit */
2102 * Reserve the GID for this transaction. This could fail if the requested
2103 * GID is invalid or already in use.
2105 gxact = MarkAsPreparing(xid, prepareGID, prepared_at,
2106 GetUserId(), MyDatabaseId);
2110 * Collect data for the 2PC state file. Note that in general, no actual
2111 * state change should happen in the called modules during this step,
2112 * since it's still possible to fail before commit, and in that case we
2113 * want transaction abort to be able to clean up. (In particular, the
2114 * AtPrepare routines may error out if they find cases they cannot
2115 * handle.) State cleanup should happen in the PostPrepare routines
2116 * below. However, some modules can go ahead and clear state here because
2117 * they wouldn't do anything with it during abort anyway.
2119 * Note: because the 2PC state file records will be replayed in the same
2120 * order they are made, the order of these calls has to match the order in
2121 * which we want things to happen during COMMIT PREPARED or ROLLBACK
2122 * PREPARED; in particular, pay attention to whether things should happen
2123 * before or after releasing the transaction's locks.
2125 StartPrepare(gxact);
2129 AtPrepare_PredicateLocks();
2131 AtPrepare_MultiXact();
2132 AtPrepare_RelationMap();
2135 * Here is where we really truly prepare.
2137 * We have to record transaction prepares even if we didn't make any
2138 * updates, because the transaction manager might get confused if we lose
2139 * a global transaction.
2144 * Now we clean up backend-internal state and release internal resources.
2147 /* Reset XactLastRecEnd until the next transaction writes something */
2151 * Let others know about no transaction in progress by me. This has to be
2152 * done *after* the prepared transaction has been marked valid, else
2153 * someone may think it is unlocked and recyclable.
2155 ProcArrayClearTransaction(MyProc);
2158 * This is all post-transaction cleanup. Note that if an error is raised
2159 * here, it's too late to abort the transaction. This should be just
2160 * noncritical resource releasing. See notes in CommitTransaction.
2163 CallXactCallbacks(XACT_EVENT_PREPARE);
2165 ResourceOwnerRelease(TopTransactionResourceOwner,
2166 RESOURCE_RELEASE_BEFORE_LOCKS,
2169 /* Check we've released all buffer pins */
2170 AtEOXact_Buffers(true);
2172 /* Clean up the relation cache */
2173 AtEOXact_RelationCache(true);
2175 /* notify doesn't need a postprepare call */
2177 PostPrepare_PgStat();
2179 PostPrepare_Inval();
2183 PostPrepare_MultiXact(xid);
2185 PostPrepare_Locks(xid);
2186 PostPrepare_PredicateLocks(xid);
2188 ResourceOwnerRelease(TopTransactionResourceOwner,
2189 RESOURCE_RELEASE_LOCKS,
2191 ResourceOwnerRelease(TopTransactionResourceOwner,
2192 RESOURCE_RELEASE_AFTER_LOCKS,
2195 /* Check we've released all catcache entries */
2196 AtEOXact_CatCache(true);
2198 /* PREPARE acts the same as COMMIT as far as GUC is concerned */
2199 AtEOXact_GUC(true, 1);
2201 AtEOXact_on_commit_actions(true);
2202 AtEOXact_Namespace(true);
2203 /* smgrcommit already done */
2205 AtEOXact_ComboCid();
2206 AtEOXact_HashTables(true);
2207 /* don't call AtEOXact_PgStat here */
2208 AtEOXact_Snapshot(true);
2210 CurrentResourceOwner = NULL;
2211 ResourceOwnerDelete(TopTransactionResourceOwner);
2212 s->curTransactionOwner = NULL;
2213 CurTransactionResourceOwner = NULL;
2214 TopTransactionResourceOwner = NULL;
2218 s->transactionId = InvalidTransactionId;
2219 s->subTransactionId = InvalidSubTransactionId;
2220 s->nestingLevel = 0;
2221 s->gucNestLevel = 0;
2222 s->childXids = NULL;
2224 s->maxChildXids = 0;
2227 * done with 1st phase commit processing, set current transaction state
2230 s->state = TRANS_DEFAULT;
2232 RESUME_INTERRUPTS();
2240 AbortTransaction(void)
2242 TransactionState s = CurrentTransactionState;
2243 TransactionId latestXid;
2245 /* Prevent cancel/die interrupt while cleaning up */
2248 /* Make sure we have a valid memory context and resource owner */
2250 AtAbort_ResourceOwner();
2253 * Release any LW locks we might be holding as quickly as possible.
2254 * (Regular locks, however, must be held till we finish aborting.)
2255 * Releasing LW locks is critical since we might try to grab them again
2256 * while cleaning up!
2260 /* Clean up buffer I/O and buffer context locks, too */
2265 * Also clean up any open wait for lock, since the lock manager will choke
2266 * if we try to wait for another lock before doing this.
2271 * check the current transaction state
2273 if (s->state != TRANS_INPROGRESS && s->state != TRANS_PREPARE)
2274 elog(WARNING, "AbortTransaction while in %s state",
2275 TransStateAsString(s->state));
2276 Assert(s->parent == NULL);
2279 * set the current transaction state information appropriately during the
2282 s->state = TRANS_ABORT;
2285 * Reset user ID which might have been changed transiently. We need this
2286 * to clean up in case control escaped out of a SECURITY DEFINER function
2287 * or other local change of CurrentUserId; therefore, the prior value of
2288 * SecurityRestrictionContext also needs to be restored.
2290 * (Note: it is not necessary to restore session authorization or role
2291 * settings here because those can only be changed via GUC, and GUC will
2292 * take care of rolling them back if need be.)
2294 SetUserIdAndSecContext(s->prevUser, s->prevSecContext);
2297 * do abort processing
2299 AfterTriggerEndXact(false); /* 'false' means it's abort */
2301 AtEOXact_LargeObject(false);
2303 AtEOXact_RelationMap(false);
2306 * Advertise the fact that we aborted in pg_clog (assuming that we got as
2307 * far as assigning an XID to advertise).
2309 latestXid = RecordTransactionAbort(false);
2311 TRACE_POSTGRESQL_TRANSACTION_ABORT(MyProc->lxid);
2314 * Let others know about no transaction in progress by me. Note that this
2315 * must be done _before_ releasing locks we hold and _after_
2316 * RecordTransactionAbort.
2318 ProcArrayEndTransaction(MyProc, latestXid);
2321 * Post-abort cleanup. See notes in CommitTransaction() concerning
2322 * ordering. We can skip all of it if the transaction failed before
2323 * creating a resource owner.
2325 if (TopTransactionResourceOwner != NULL)
2327 CallXactCallbacks(XACT_EVENT_ABORT);
2329 ResourceOwnerRelease(TopTransactionResourceOwner,
2330 RESOURCE_RELEASE_BEFORE_LOCKS,
2332 AtEOXact_Buffers(false);
2333 AtEOXact_RelationCache(false);
2334 AtEOXact_Inval(false);
2335 AtEOXact_MultiXact();
2336 ResourceOwnerRelease(TopTransactionResourceOwner,
2337 RESOURCE_RELEASE_LOCKS,
2339 ResourceOwnerRelease(TopTransactionResourceOwner,
2340 RESOURCE_RELEASE_AFTER_LOCKS,
2342 smgrDoPendingDeletes(false);
2343 AtEOXact_CatCache(false);
2345 AtEOXact_GUC(false, 1);
2346 AtEOXact_SPI(false);
2347 AtEOXact_on_commit_actions(false);
2348 AtEOXact_Namespace(false);
2350 AtEOXact_ComboCid();
2351 AtEOXact_HashTables(false);
2352 AtEOXact_PgStat(false);
2353 pgstat_report_xact_timestamp(0);
2357 * State remains TRANS_ABORT until CleanupTransaction().
2359 RESUME_INTERRUPTS();
2363 * CleanupTransaction
2366 CleanupTransaction(void)
2368 TransactionState s = CurrentTransactionState;
2371 * State should still be TRANS_ABORT from AbortTransaction().
2373 if (s->state != TRANS_ABORT)
2374 elog(FATAL, "CleanupTransaction: unexpected state %s",
2375 TransStateAsString(s->state));
2378 * do abort cleanup processing
2380 AtCleanup_Portals(); /* now safe to release portal memory */
2381 AtEOXact_Snapshot(false); /* and release the transaction's snapshots */
2383 CurrentResourceOwner = NULL; /* and resource owner */
2384 if (TopTransactionResourceOwner)
2385 ResourceOwnerDelete(TopTransactionResourceOwner);
2386 s->curTransactionOwner = NULL;
2387 CurTransactionResourceOwner = NULL;
2388 TopTransactionResourceOwner = NULL;
2390 AtCleanup_Memory(); /* and transaction memory */
2392 s->transactionId = InvalidTransactionId;
2393 s->subTransactionId = InvalidSubTransactionId;
2394 s->nestingLevel = 0;
2395 s->gucNestLevel = 0;
2396 s->childXids = NULL;
2398 s->maxChildXids = 0;
2401 * done with abort processing, set current transaction state back to
2404 s->state = TRANS_DEFAULT;
2408 * StartTransactionCommand
2411 StartTransactionCommand(void)
2413 TransactionState s = CurrentTransactionState;
2415 switch (s->blockState)
2418 * if we aren't in a transaction block, we just do our usual start
2421 case TBLOCK_DEFAULT:
2423 s->blockState = TBLOCK_STARTED;
2427 * We are somewhere in a transaction block or subtransaction and
2428 * about to start a new command. For now we do nothing, but
2429 * someday we may do command-local resource initialization. (Note
2430 * that any needed CommandCounterIncrement was done by the
2431 * previous CommitTransactionCommand.)
2433 case TBLOCK_INPROGRESS:
2434 case TBLOCK_SUBINPROGRESS:
2438 * Here we are in a failed transaction block (one of the commands
2439 * caused an abort) so we do nothing but remain in the abort
2440 * state. Eventually we will get a ROLLBACK command which will
2441 * get us out of this state. (It is up to other code to ensure
2442 * that no commands other than ROLLBACK will be processed in these
2446 case TBLOCK_SUBABORT:
2449 /* These cases are invalid. */
2450 case TBLOCK_STARTED:
2452 case TBLOCK_SUBBEGIN:
2454 case TBLOCK_SUBRELEASE:
2455 case TBLOCK_SUBCOMMIT:
2456 case TBLOCK_ABORT_END:
2457 case TBLOCK_SUBABORT_END:
2458 case TBLOCK_ABORT_PENDING:
2459 case TBLOCK_SUBABORT_PENDING:
2460 case TBLOCK_SUBRESTART:
2461 case TBLOCK_SUBABORT_RESTART:
2462 case TBLOCK_PREPARE:
2463 elog(ERROR, "StartTransactionCommand: unexpected state %s",
2464 BlockStateAsString(s->blockState));
2469 * We must switch to CurTransactionContext before returning. This is
2470 * already done if we called StartTransaction, otherwise not.
2472 Assert(CurTransactionContext != NULL);
2473 MemoryContextSwitchTo(CurTransactionContext);
2477 * CommitTransactionCommand
2480 CommitTransactionCommand(void)
2482 TransactionState s = CurrentTransactionState;
2484 switch (s->blockState)
2487 * This shouldn't happen, because it means the previous
2488 * StartTransactionCommand didn't set the STARTED state
2491 case TBLOCK_DEFAULT:
2492 elog(FATAL, "CommitTransactionCommand: unexpected state %s",
2493 BlockStateAsString(s->blockState));
2497 * If we aren't in a transaction block, just do our usual
2498 * transaction commit, and return to the idle state.
2500 case TBLOCK_STARTED:
2501 CommitTransaction();
2502 s->blockState = TBLOCK_DEFAULT;
2506 * We are completing a "BEGIN TRANSACTION" command, so we change
2507 * to the "transaction block in progress" state and return. (We
2508 * assume the BEGIN did nothing to the database, so we need no
2509 * CommandCounterIncrement.)
2512 s->blockState = TBLOCK_INPROGRESS;
2516 * This is the case when we have finished executing a command
2517 * someplace within a transaction block. We increment the command
2518 * counter and return.
2520 case TBLOCK_INPROGRESS:
2521 case TBLOCK_SUBINPROGRESS:
2522 CommandCounterIncrement();
2526 * We are completing a "COMMIT" command. Do it and return to the
2530 CommitTransaction();
2531 s->blockState = TBLOCK_DEFAULT;
2535 * Here we are in the middle of a transaction block but one of the
2536 * commands caused an abort so we do nothing but remain in the
2537 * abort state. Eventually we will get a ROLLBACK comand.
2540 case TBLOCK_SUBABORT:
2544 * Here we were in an aborted transaction block and we just got
2545 * the ROLLBACK command from the user, so clean up the
2546 * already-aborted transaction and return to the idle state.
2548 case TBLOCK_ABORT_END:
2549 CleanupTransaction();
2550 s->blockState = TBLOCK_DEFAULT;
2554 * Here we were in a perfectly good transaction block but the user
2555 * told us to ROLLBACK anyway. We have to abort the transaction
2556 * and then clean up.
2558 case TBLOCK_ABORT_PENDING:
2560 CleanupTransaction();
2561 s->blockState = TBLOCK_DEFAULT;
2565 * We are completing a "PREPARE TRANSACTION" command. Do it and
2566 * return to the idle state.
2568 case TBLOCK_PREPARE:
2569 PrepareTransaction();
2570 s->blockState = TBLOCK_DEFAULT;
2574 * We were just issued a SAVEPOINT inside a transaction block.
2575 * Start a subtransaction. (DefineSavepoint already did
2576 * PushTransaction, so as to have someplace to put the SUBBEGIN
2579 case TBLOCK_SUBBEGIN:
2580 StartSubTransaction();
2581 s->blockState = TBLOCK_SUBINPROGRESS;
2585 * We were issued a RELEASE command, so we end the current
2586 * subtransaction and return to the parent transaction. The parent
2587 * might be ended too, so repeat till we find an INPROGRESS
2588 * transaction or subtransaction.
2590 case TBLOCK_SUBRELEASE:
2593 CommitSubTransaction();
2594 s = CurrentTransactionState; /* changed by pop */
2595 } while (s->blockState == TBLOCK_SUBRELEASE);
2597 Assert(s->blockState == TBLOCK_INPROGRESS ||
2598 s->blockState == TBLOCK_SUBINPROGRESS);
2602 * We were issued a COMMIT, so we end the current subtransaction
2603 * hierarchy and perform final commit. We do this by rolling up
2604 * any subtransactions into their parent, which leads to O(N^2)
2605 * operations with respect to resource owners - this isn't that
2606 * bad until we approach a thousands of savepoints but is
2607 * necessary for correctness should after triggers create new
2610 case TBLOCK_SUBCOMMIT:
2613 CommitSubTransaction();
2614 s = CurrentTransactionState; /* changed by pop */
2615 } while (s->blockState == TBLOCK_SUBCOMMIT);
2616 /* If we had a COMMIT command, finish off the main xact too */
2617 if (s->blockState == TBLOCK_END)
2619 Assert(s->parent == NULL);
2620 CommitTransaction();
2621 s->blockState = TBLOCK_DEFAULT;
2623 else if (s->blockState == TBLOCK_PREPARE)
2625 Assert(s->parent == NULL);
2626 PrepareTransaction();
2627 s->blockState = TBLOCK_DEFAULT;
2630 elog(ERROR, "CommitTransactionCommand: unexpected state %s",
2631 BlockStateAsString(s->blockState));
2635 * The current already-failed subtransaction is ending due to a
2636 * ROLLBACK or ROLLBACK TO command, so pop it and recursively
2637 * examine the parent (which could be in any of several states).
2639 case TBLOCK_SUBABORT_END:
2640 CleanupSubTransaction();
2641 CommitTransactionCommand();
2645 * As above, but it's not dead yet, so abort first.
2647 case TBLOCK_SUBABORT_PENDING:
2648 AbortSubTransaction();
2649 CleanupSubTransaction();
2650 CommitTransactionCommand();
2654 * The current subtransaction is the target of a ROLLBACK TO
2655 * command. Abort and pop it, then start a new subtransaction
2656 * with the same name.
2658 case TBLOCK_SUBRESTART:
2663 /* save name and keep Cleanup from freeing it */
2666 savepointLevel = s->savepointLevel;
2668 AbortSubTransaction();
2669 CleanupSubTransaction();
2671 DefineSavepoint(NULL);
2672 s = CurrentTransactionState; /* changed by push */
2674 s->savepointLevel = savepointLevel;
2676 /* This is the same as TBLOCK_SUBBEGIN case */
2677 AssertState(s->blockState == TBLOCK_SUBBEGIN);
2678 StartSubTransaction();
2679 s->blockState = TBLOCK_SUBINPROGRESS;
2684 * Same as above, but the subtransaction had already failed, so we
2685 * don't need AbortSubTransaction.
2687 case TBLOCK_SUBABORT_RESTART:
2692 /* save name and keep Cleanup from freeing it */
2695 savepointLevel = s->savepointLevel;
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;
2714 * AbortCurrentTransaction
2717 AbortCurrentTransaction(void)
2719 TransactionState s = CurrentTransactionState;
2721 switch (s->blockState)
2723 case TBLOCK_DEFAULT:
2724 if (s->state == TRANS_DEFAULT)
2726 /* we are idle, so nothing to do */
2731 * We can get here after an error during transaction start
2732 * (state will be TRANS_START). Need to clean up the
2733 * incompletely started transaction. First, adjust the
2734 * low-level state to suppress warning message from
2737 if (s->state == TRANS_START)
2738 s->state = TRANS_INPROGRESS;
2740 CleanupTransaction();
2745 * if we aren't in a transaction block, we just do the basic abort
2746 * & cleanup transaction.
2748 case TBLOCK_STARTED:
2750 CleanupTransaction();
2751 s->blockState = TBLOCK_DEFAULT;
2755 * If we are in TBLOCK_BEGIN it means something screwed up right
2756 * after reading "BEGIN TRANSACTION". We assume that the user
2757 * will interpret the error as meaning the BEGIN failed to get him
2758 * into a transaction block, so we should abort and return to idle
2763 CleanupTransaction();
2764 s->blockState = TBLOCK_DEFAULT;
2768 * We are somewhere in a transaction block and we've gotten a
2769 * failure, so we abort the transaction and set up the persistent
2770 * ABORT state. We will stay in ABORT until we get a ROLLBACK.
2772 case TBLOCK_INPROGRESS:
2774 s->blockState = TBLOCK_ABORT;
2775 /* CleanupTransaction happens when we exit TBLOCK_ABORT_END */
2779 * Here, we failed while trying to COMMIT. Clean up the
2780 * transaction and return to idle state (we do not want to stay in
2785 CleanupTransaction();
2786 s->blockState = TBLOCK_DEFAULT;
2790 * Here, we are already in an aborted transaction state and are
2791 * waiting for a ROLLBACK, but for some reason we failed again! So
2792 * we just remain in the abort state.
2795 case TBLOCK_SUBABORT:
2799 * We are in a failed transaction and we got the ROLLBACK command.
2800 * We have already aborted, we just need to cleanup and go to idle
2803 case TBLOCK_ABORT_END:
2804 CleanupTransaction();
2805 s->blockState = TBLOCK_DEFAULT;
2809 * We are in a live transaction and we got a ROLLBACK command.
2810 * Abort, cleanup, go to idle state.
2812 case TBLOCK_ABORT_PENDING:
2814 CleanupTransaction();
2815 s->blockState = TBLOCK_DEFAULT;
2819 * Here, we failed while trying to PREPARE. Clean up the
2820 * transaction and return to idle state (we do not want to stay in
2823 case TBLOCK_PREPARE:
2825 CleanupTransaction();
2826 s->blockState = TBLOCK_DEFAULT;
2830 * We got an error inside a subtransaction. Abort just the
2831 * subtransaction, and go to the persistent SUBABORT state until
2834 case TBLOCK_SUBINPROGRESS:
2835 AbortSubTransaction();
2836 s->blockState = TBLOCK_SUBABORT;
2840 * If we failed while trying to create a subtransaction, clean up
2841 * the broken subtransaction and abort the parent. The same
2842 * applies if we get a failure while ending a subtransaction.
2844 case TBLOCK_SUBBEGIN:
2845 case TBLOCK_SUBRELEASE:
2846 case TBLOCK_SUBCOMMIT:
2847 case TBLOCK_SUBABORT_PENDING:
2848 case TBLOCK_SUBRESTART:
2849 AbortSubTransaction();
2850 CleanupSubTransaction();
2851 AbortCurrentTransaction();
2855 * Same as above, except the Abort() was already done.
2857 case TBLOCK_SUBABORT_END:
2858 case TBLOCK_SUBABORT_RESTART:
2859 CleanupSubTransaction();
2860 AbortCurrentTransaction();
2866 * PreventTransactionChain
2868 * This routine is to be called by statements that must not run inside
2869 * a transaction block, typically because they have non-rollback-able
2870 * side effects or do internal commits.
2872 * If we have already started a transaction block, issue an error; also issue
2873 * an error if we appear to be running inside a user-defined function (which
2874 * could issue more commands and possibly cause a failure after the statement
2875 * completes). Subtransactions are verboten too.
2877 * isTopLevel: passed down from ProcessUtility to determine whether we are
2878 * inside a function or multi-query querystring. (We will always fail if
2879 * this is false, but it's convenient to centralize the check here instead of
2880 * making callers do it.)
2881 * stmtType: statement type name, for error messages.
2884 PreventTransactionChain(bool isTopLevel, const char *stmtType)
2887 * xact block already started?
2889 if (IsTransactionBlock())
2891 (errcode(ERRCODE_ACTIVE_SQL_TRANSACTION),
2892 /* translator: %s represents an SQL statement name */
2893 errmsg("%s cannot run inside a transaction block",
2899 if (IsSubTransaction())
2901 (errcode(ERRCODE_ACTIVE_SQL_TRANSACTION),
2902 /* translator: %s represents an SQL statement name */
2903 errmsg("%s cannot run inside a subtransaction",
2907 * inside a function call?
2911 (errcode(ERRCODE_ACTIVE_SQL_TRANSACTION),
2912 /* translator: %s represents an SQL statement name */
2913 errmsg("%s cannot be executed from a function or multi-command string",
2916 /* If we got past IsTransactionBlock test, should be in default state */
2917 if (CurrentTransactionState->blockState != TBLOCK_DEFAULT &&
2918 CurrentTransactionState->blockState != TBLOCK_STARTED)
2919 elog(FATAL, "cannot prevent transaction chain");
2924 * RequireTransactionChain
2926 * This routine is to be called by statements that must run inside
2927 * a transaction block, because they have no effects that persist past
2928 * transaction end (and so calling them outside a transaction block
2929 * is presumably an error). DECLARE CURSOR is an example.
2931 * If we appear to be running inside a user-defined function, we do not
2932 * issue an error, since the function could issue more commands that make
2933 * use of the current statement's results. Likewise subtransactions.
2934 * Thus this is an inverse for PreventTransactionChain.
2936 * isTopLevel: passed down from ProcessUtility to determine whether we are
2937 * inside a function.
2938 * stmtType: statement type name, for error messages.
2941 RequireTransactionChain(bool isTopLevel, const char *stmtType)
2944 * xact block already started?
2946 if (IsTransactionBlock())
2952 if (IsSubTransaction())
2956 * inside a function call?
2962 (errcode(ERRCODE_NO_ACTIVE_SQL_TRANSACTION),
2963 /* translator: %s represents an SQL statement name */
2964 errmsg("%s can only be used in transaction blocks",
2969 * IsInTransactionChain
2971 * This routine is for statements that need to behave differently inside
2972 * a transaction block than when running as single commands. ANALYZE is
2973 * currently the only example.
2975 * isTopLevel: passed down from ProcessUtility to determine whether we are
2976 * inside a function.
2979 IsInTransactionChain(bool isTopLevel)
2982 * Return true on same conditions that would make PreventTransactionChain
2985 if (IsTransactionBlock())
2988 if (IsSubTransaction())
2994 if (CurrentTransactionState->blockState != TBLOCK_DEFAULT &&
2995 CurrentTransactionState->blockState != TBLOCK_STARTED)
3003 * Register or deregister callback functions for start- and end-of-xact
3006 * These functions are intended for use by dynamically loaded modules.
3007 * For built-in modules we generally just hardwire the appropriate calls
3008 * (mainly because it's easier to control the order that way, where needed).
3010 * At transaction end, the callback occurs post-commit or post-abort, so the
3011 * callback functions can only do noncritical cleanup.
3014 RegisterXactCallback(XactCallback callback, void *arg)
3016 XactCallbackItem *item;
3018 item = (XactCallbackItem *)
3019 MemoryContextAlloc(TopMemoryContext, sizeof(XactCallbackItem));
3020 item->callback = callback;
3022 item->next = Xact_callbacks;
3023 Xact_callbacks = item;
3027 UnregisterXactCallback(XactCallback callback, void *arg)
3029 XactCallbackItem *item;
3030 XactCallbackItem *prev;
3033 for (item = Xact_callbacks; item; prev = item, item = item->next)
3035 if (item->callback == callback && item->arg == arg)
3038 prev->next = item->next;
3040 Xact_callbacks = item->next;
3048 CallXactCallbacks(XactEvent event)
3050 XactCallbackItem *item;
3052 for (item = Xact_callbacks; item; item = item->next)
3053 (*item->callback) (event, item->arg);
3058 * Register or deregister callback functions for start- and end-of-subxact
3061 * Pretty much same as above, but for subtransaction events.
3063 * At subtransaction end, the callback occurs post-subcommit or post-subabort,
3064 * so the callback functions can only do noncritical cleanup. At
3065 * subtransaction start, the callback is called when the subtransaction has
3066 * finished initializing.
3069 RegisterSubXactCallback(SubXactCallback callback, void *arg)
3071 SubXactCallbackItem *item;
3073 item = (SubXactCallbackItem *)
3074 MemoryContextAlloc(TopMemoryContext, sizeof(SubXactCallbackItem));
3075 item->callback = callback;
3077 item->next = SubXact_callbacks;
3078 SubXact_callbacks = item;
3082 UnregisterSubXactCallback(SubXactCallback callback, void *arg)
3084 SubXactCallbackItem *item;
3085 SubXactCallbackItem *prev;
3088 for (item = SubXact_callbacks; item; prev = item, item = item->next)
3090 if (item->callback == callback && item->arg == arg)
3093 prev->next = item->next;
3095 SubXact_callbacks = item->next;
3103 CallSubXactCallbacks(SubXactEvent event,
3104 SubTransactionId mySubid,
3105 SubTransactionId parentSubid)
3107 SubXactCallbackItem *item;
3109 for (item = SubXact_callbacks; item; item = item->next)
3110 (*item->callback) (event, mySubid, parentSubid, item->arg);
3114 /* ----------------------------------------------------------------
3115 * transaction block support
3116 * ----------------------------------------------------------------
3120 * BeginTransactionBlock
3121 * This executes a BEGIN command.
3124 BeginTransactionBlock(void)
3126 TransactionState s = CurrentTransactionState;
3128 switch (s->blockState)
3131 * We are not inside a transaction block, so allow one to begin.
3133 case TBLOCK_STARTED:
3134 s->blockState = TBLOCK_BEGIN;
3138 * Already a transaction block in progress.
3140 case TBLOCK_INPROGRESS:
3141 case TBLOCK_SUBINPROGRESS:
3143 case TBLOCK_SUBABORT:
3145 (errcode(ERRCODE_ACTIVE_SQL_TRANSACTION),
3146 errmsg("there is already a transaction in progress")));
3149 /* These cases are invalid. */
3150 case TBLOCK_DEFAULT:
3152 case TBLOCK_SUBBEGIN:
3154 case TBLOCK_SUBRELEASE:
3155 case TBLOCK_SUBCOMMIT:
3156 case TBLOCK_ABORT_END:
3157 case TBLOCK_SUBABORT_END:
3158 case TBLOCK_ABORT_PENDING:
3159 case TBLOCK_SUBABORT_PENDING:
3160 case TBLOCK_SUBRESTART:
3161 case TBLOCK_SUBABORT_RESTART:
3162 case TBLOCK_PREPARE:
3163 elog(FATAL, "BeginTransactionBlock: unexpected state %s",
3164 BlockStateAsString(s->blockState));
3170 * PrepareTransactionBlock
3171 * This executes a PREPARE command.
3173 * Since PREPARE may actually do a ROLLBACK, the result indicates what
3174 * happened: TRUE for PREPARE, FALSE for ROLLBACK.
3176 * Note that we don't actually do anything here except change blockState.
3177 * The real work will be done in the upcoming PrepareTransaction().
3178 * We do it this way because it's not convenient to change memory context,
3179 * resource owner, etc while executing inside a Portal.
3182 PrepareTransactionBlock(char *gid)
3187 /* Set up to commit the current transaction */
3188 result = EndTransactionBlock();
3190 /* If successful, change outer tblock state to PREPARE */
3193 s = CurrentTransactionState;
3195 while (s->parent != NULL)
3198 if (s->blockState == TBLOCK_END)
3200 /* Save GID where PrepareTransaction can find it again */
3201 prepareGID = MemoryContextStrdup(TopTransactionContext, gid);
3203 s->blockState = TBLOCK_PREPARE;
3208 * ignore case where we are not in a transaction;
3209 * EndTransactionBlock already issued a warning.
3211 Assert(s->blockState == TBLOCK_STARTED);
3212 /* Don't send back a PREPARE result tag... */
3221 * EndTransactionBlock
3222 * This executes a COMMIT command.
3224 * Since COMMIT may actually do a ROLLBACK, the result indicates what
3225 * happened: TRUE for COMMIT, FALSE for ROLLBACK.
3227 * Note that we don't actually do anything here except change blockState.
3228 * The real work will be done in the upcoming CommitTransactionCommand().
3229 * We do it this way because it's not convenient to change memory context,
3230 * resource owner, etc while executing inside a Portal.
3233 EndTransactionBlock(void)
3235 TransactionState s = CurrentTransactionState;
3236 bool result = false;
3238 switch (s->blockState)
3241 * We are in a transaction block, so tell CommitTransactionCommand
3244 case TBLOCK_INPROGRESS:
3245 s->blockState = TBLOCK_END;
3250 * We are in a failed transaction block. Tell
3251 * CommitTransactionCommand it's time to exit the block.
3254 s->blockState = TBLOCK_ABORT_END;
3258 * We are in a live subtransaction block. Set up to subcommit all
3259 * open subtransactions and then commit the main transaction.
3261 case TBLOCK_SUBINPROGRESS:
3262 while (s->parent != NULL)
3264 if (s->blockState == TBLOCK_SUBINPROGRESS)
3265 s->blockState = TBLOCK_SUBCOMMIT;
3267 elog(FATAL, "EndTransactionBlock: unexpected state %s",
3268 BlockStateAsString(s->blockState));
3271 if (s->blockState == TBLOCK_INPROGRESS)
3272 s->blockState = TBLOCK_END;
3274 elog(FATAL, "EndTransactionBlock: unexpected state %s",
3275 BlockStateAsString(s->blockState));
3280 * Here we are inside an aborted subtransaction. Treat the COMMIT
3281 * as ROLLBACK: set up to abort everything and exit the main
3284 case TBLOCK_SUBABORT:
3285 while (s->parent != NULL)
3287 if (s->blockState == TBLOCK_SUBINPROGRESS)
3288 s->blockState = TBLOCK_SUBABORT_PENDING;
3289 else if (s->blockState == TBLOCK_SUBABORT)
3290 s->blockState = TBLOCK_SUBABORT_END;
3292 elog(FATAL, "EndTransactionBlock: unexpected state %s",
3293 BlockStateAsString(s->blockState));
3296 if (s->blockState == TBLOCK_INPROGRESS)
3297 s->blockState = TBLOCK_ABORT_PENDING;
3298 else if (s->blockState == TBLOCK_ABORT)
3299 s->blockState = TBLOCK_ABORT_END;
3301 elog(FATAL, "EndTransactionBlock: unexpected state %s",
3302 BlockStateAsString(s->blockState));
3306 * The user issued COMMIT when not inside a transaction. Issue a
3307 * WARNING, staying in TBLOCK_STARTED state. The upcoming call to
3308 * CommitTransactionCommand() will then close the transaction and
3309 * put us back into the default state.
3311 case TBLOCK_STARTED:
3313 (errcode(ERRCODE_NO_ACTIVE_SQL_TRANSACTION),
3314 errmsg("there is no transaction in progress")));
3318 /* These cases are invalid. */
3319 case TBLOCK_DEFAULT:
3321 case TBLOCK_SUBBEGIN:
3323 case TBLOCK_SUBRELEASE:
3324 case TBLOCK_SUBCOMMIT:
3325 case TBLOCK_ABORT_END:
3326 case TBLOCK_SUBABORT_END:
3327 case TBLOCK_ABORT_PENDING:
3328 case TBLOCK_SUBABORT_PENDING:
3329 case TBLOCK_SUBRESTART:
3330 case TBLOCK_SUBABORT_RESTART:
3331 case TBLOCK_PREPARE:
3332 elog(FATAL, "EndTransactionBlock: unexpected state %s",
3333 BlockStateAsString(s->blockState));
3341 * UserAbortTransactionBlock
3342 * This executes a ROLLBACK command.
3344 * As above, we don't actually do anything here except change blockState.
3347 UserAbortTransactionBlock(void)
3349 TransactionState s = CurrentTransactionState;
3351 switch (s->blockState)
3354 * We are inside a transaction block and we got a ROLLBACK command
3355 * from the user, so tell CommitTransactionCommand to abort and
3356 * exit the transaction block.
3358 case TBLOCK_INPROGRESS:
3359 s->blockState = TBLOCK_ABORT_PENDING;
3363 * We are inside a failed transaction block and we got a ROLLBACK
3364 * command from the user. Abort processing is already done, so
3365 * CommitTransactionCommand just has to cleanup and go back to
3369 s->blockState = TBLOCK_ABORT_END;
3373 * We are inside a subtransaction. Mark everything up to top
3374 * level as exitable.
3376 case TBLOCK_SUBINPROGRESS:
3377 case TBLOCK_SUBABORT:
3378 while (s->parent != NULL)
3380 if (s->blockState == TBLOCK_SUBINPROGRESS)
3381 s->blockState = TBLOCK_SUBABORT_PENDING;
3382 else if (s->blockState == TBLOCK_SUBABORT)
3383 s->blockState = TBLOCK_SUBABORT_END;
3385 elog(FATAL, "UserAbortTransactionBlock: unexpected state %s",
3386 BlockStateAsString(s->blockState));
3389 if (s->blockState == TBLOCK_INPROGRESS)
3390 s->blockState = TBLOCK_ABORT_PENDING;
3391 else if (s->blockState == TBLOCK_ABORT)
3392 s->blockState = TBLOCK_ABORT_END;
3394 elog(FATAL, "UserAbortTransactionBlock: unexpected state %s",
3395 BlockStateAsString(s->blockState));
3399 * The user issued ABORT when not inside a transaction. Issue a
3400 * WARNING and go to abort state. The upcoming call to
3401 * CommitTransactionCommand() will then put us back into the
3404 case TBLOCK_STARTED:
3406 (errcode(ERRCODE_NO_ACTIVE_SQL_TRANSACTION),
3407 errmsg("there is no transaction in progress")));
3408 s->blockState = TBLOCK_ABORT_PENDING;
3411 /* These cases are invalid. */
3412 case TBLOCK_DEFAULT:
3414 case TBLOCK_SUBBEGIN:
3416 case TBLOCK_SUBRELEASE:
3417 case TBLOCK_SUBCOMMIT:
3418 case TBLOCK_ABORT_END:
3419 case TBLOCK_SUBABORT_END:
3420 case TBLOCK_ABORT_PENDING:
3421 case TBLOCK_SUBABORT_PENDING:
3422 case TBLOCK_SUBRESTART:
3423 case TBLOCK_SUBABORT_RESTART:
3424 case TBLOCK_PREPARE:
3425 elog(FATAL, "UserAbortTransactionBlock: unexpected state %s",
3426 BlockStateAsString(s->blockState));
3433 * This executes a SAVEPOINT command.
3436 DefineSavepoint(char *name)
3438 TransactionState s = CurrentTransactionState;
3440 switch (s->blockState)
3442 case TBLOCK_INPROGRESS:
3443 case TBLOCK_SUBINPROGRESS:
3444 /* Normal subtransaction start */
3446 s = CurrentTransactionState; /* changed by push */
3449 * Savepoint names, like the TransactionState block itself, live
3450 * in TopTransactionContext.
3453 s->name = MemoryContextStrdup(TopTransactionContext, name);
3456 /* These cases are invalid. */
3457 case TBLOCK_DEFAULT:
3458 case TBLOCK_STARTED:
3460 case TBLOCK_SUBBEGIN:
3462 case TBLOCK_SUBRELEASE:
3463 case TBLOCK_SUBCOMMIT:
3465 case TBLOCK_SUBABORT:
3466 case TBLOCK_ABORT_END:
3467 case TBLOCK_SUBABORT_END:
3468 case TBLOCK_ABORT_PENDING:
3469 case TBLOCK_SUBABORT_PENDING:
3470 case TBLOCK_SUBRESTART:
3471 case TBLOCK_SUBABORT_RESTART:
3472 case TBLOCK_PREPARE:
3473 elog(FATAL, "DefineSavepoint: unexpected state %s",
3474 BlockStateAsString(s->blockState));
3481 * This executes a RELEASE command.
3483 * As above, we don't actually do anything here except change blockState.
3486 ReleaseSavepoint(List *options)
3488 TransactionState s = CurrentTransactionState;
3489 TransactionState target,
3494 switch (s->blockState)
3497 * We can't rollback to a savepoint if there is no savepoint
3500 case TBLOCK_INPROGRESS:
3502 (errcode(ERRCODE_S_E_INVALID_SPECIFICATION),
3503 errmsg("no such savepoint")));
3507 * We are in a non-aborted subtransaction. This is the only valid
3510 case TBLOCK_SUBINPROGRESS:
3513 /* These cases are invalid. */
3514 case TBLOCK_DEFAULT:
3515 case TBLOCK_STARTED:
3517 case TBLOCK_SUBBEGIN:
3519 case TBLOCK_SUBRELEASE:
3520 case TBLOCK_SUBCOMMIT:
3522 case TBLOCK_SUBABORT:
3523 case TBLOCK_ABORT_END:
3524 case TBLOCK_SUBABORT_END:
3525 case TBLOCK_ABORT_PENDING:
3526 case TBLOCK_SUBABORT_PENDING:
3527 case TBLOCK_SUBRESTART:
3528 case TBLOCK_SUBABORT_RESTART:
3529 case TBLOCK_PREPARE:
3530 elog(FATAL, "ReleaseSavepoint: unexpected state %s",
3531 BlockStateAsString(s->blockState));
3535 foreach(cell, options)
3537 DefElem *elem = lfirst(cell);
3539 if (strcmp(elem->defname, "savepoint_name") == 0)
3540 name = strVal(elem->arg);
3543 Assert(PointerIsValid(name));
3545 for (target = s; PointerIsValid(target); target = target->parent)
3547 if (PointerIsValid(target->name) && strcmp(target->name, name) == 0)
3551 if (!PointerIsValid(target))
3553 (errcode(ERRCODE_S_E_INVALID_SPECIFICATION),
3554 errmsg("no such savepoint")));
3556 /* disallow crossing savepoint level boundaries */
3557 if (target->savepointLevel != s->savepointLevel)
3559 (errcode(ERRCODE_S_E_INVALID_SPECIFICATION),
3560 errmsg("no such savepoint")));
3563 * Mark "commit pending" all subtransactions up to the target
3564 * subtransaction. The actual commits will happen when control gets to
3565 * CommitTransactionCommand.
3567 xact = CurrentTransactionState;
3570 Assert(xact->blockState == TBLOCK_SUBINPROGRESS);
3571 xact->blockState = TBLOCK_SUBRELEASE;
3574 xact = xact->parent;
3575 Assert(PointerIsValid(xact));
3580 * RollbackToSavepoint
3581 * This executes a ROLLBACK TO <savepoint> command.
3583 * As above, we don't actually do anything here except change blockState.
3586 RollbackToSavepoint(List *options)
3588 TransactionState s = CurrentTransactionState;
3589 TransactionState target,
3594 switch (s->blockState)
3597 * We can't rollback to a savepoint if there is no savepoint
3600 case TBLOCK_INPROGRESS:
3603 (errcode(ERRCODE_S_E_INVALID_SPECIFICATION),
3604 errmsg("no such savepoint")));
3608 * There is at least one savepoint, so proceed.
3610 case TBLOCK_SUBINPROGRESS:
3611 case TBLOCK_SUBABORT:
3614 /* These cases are invalid. */
3615 case TBLOCK_DEFAULT:
3616 case TBLOCK_STARTED:
3618 case TBLOCK_SUBBEGIN:
3620 case TBLOCK_SUBRELEASE:
3621 case TBLOCK_SUBCOMMIT:
3622 case TBLOCK_ABORT_END:
3623 case TBLOCK_SUBABORT_END:
3624 case TBLOCK_ABORT_PENDING:
3625 case TBLOCK_SUBABORT_PENDING:
3626 case TBLOCK_SUBRESTART:
3627 case TBLOCK_SUBABORT_RESTART:
3628 case TBLOCK_PREPARE:
3629 elog(FATAL, "RollbackToSavepoint: unexpected state %s",
3630 BlockStateAsString(s->blockState));
3634 foreach(cell, options)
3636 DefElem *elem = lfirst(cell);
3638 if (strcmp(elem->defname, "savepoint_name") == 0)
3639 name = strVal(elem->arg);
3642 Assert(PointerIsValid(name));
3644 for (target = s; PointerIsValid(target); target = target->parent)
3646 if (PointerIsValid(target->name) && strcmp(target->name, name) == 0)
3650 if (!PointerIsValid(target))
3652 (errcode(ERRCODE_S_E_INVALID_SPECIFICATION),
3653 errmsg("no such savepoint")));
3655 /* disallow crossing savepoint level boundaries */
3656 if (target->savepointLevel != s->savepointLevel)
3658 (errcode(ERRCODE_S_E_INVALID_SPECIFICATION),
3659 errmsg("no such savepoint")));
3662 * Mark "abort pending" all subtransactions up to the target
3663 * subtransaction. The actual aborts will happen when control gets to
3664 * CommitTransactionCommand.
3666 xact = CurrentTransactionState;
3671 if (xact->blockState == TBLOCK_SUBINPROGRESS)
3672 xact->blockState = TBLOCK_SUBABORT_PENDING;
3673 else if (xact->blockState == TBLOCK_SUBABORT)
3674 xact->blockState = TBLOCK_SUBABORT_END;
3676 elog(FATAL, "RollbackToSavepoint: unexpected state %s",
3677 BlockStateAsString(xact->blockState));
3678 xact = xact->parent;
3679 Assert(PointerIsValid(xact));
3682 /* And mark the target as "restart pending" */
3683 if (xact->blockState == TBLOCK_SUBINPROGRESS)
3684 xact->blockState = TBLOCK_SUBRESTART;
3685 else if (xact->blockState == TBLOCK_SUBABORT)
3686 xact->blockState = TBLOCK_SUBABORT_RESTART;
3688 elog(FATAL, "RollbackToSavepoint: unexpected state %s",
3689 BlockStateAsString(xact->blockState));
3693 * BeginInternalSubTransaction
3694 * This is the same as DefineSavepoint except it allows TBLOCK_STARTED,
3695 * TBLOCK_END, and TBLOCK_PREPARE states, and therefore it can safely be
3696 * used in functions that might be called when not inside a BEGIN block
3697 * or when running deferred triggers at COMMIT/PREPARE time. Also, it
3698 * automatically does CommitTransactionCommand/StartTransactionCommand
3699 * instead of expecting the caller to do it.
3702 BeginInternalSubTransaction(char *name)
3704 TransactionState s = CurrentTransactionState;
3706 switch (s->blockState)
3708 case TBLOCK_STARTED:
3709 case TBLOCK_INPROGRESS:
3711 case TBLOCK_PREPARE:
3712 case TBLOCK_SUBINPROGRESS:
3713 /* Normal subtransaction start */
3715 s = CurrentTransactionState; /* changed by push */
3718 * Savepoint names, like the TransactionState block itself, live
3719 * in TopTransactionContext.
3722 s->name = MemoryContextStrdup(TopTransactionContext, name);
3725 /* These cases are invalid. */
3726 case TBLOCK_DEFAULT:
3728 case TBLOCK_SUBBEGIN:
3729 case TBLOCK_SUBRELEASE:
3730 case TBLOCK_SUBCOMMIT:
3732 case TBLOCK_SUBABORT:
3733 case TBLOCK_ABORT_END:
3734 case TBLOCK_SUBABORT_END:
3735 case TBLOCK_ABORT_PENDING:
3736 case TBLOCK_SUBABORT_PENDING:
3737 case TBLOCK_SUBRESTART:
3738 case TBLOCK_SUBABORT_RESTART:
3739 elog(FATAL, "BeginInternalSubTransaction: unexpected state %s",
3740 BlockStateAsString(s->blockState));
3744 CommitTransactionCommand();
3745 StartTransactionCommand();
3749 * ReleaseCurrentSubTransaction
3751 * RELEASE (ie, commit) the innermost subtransaction, regardless of its
3752 * savepoint name (if any).
3753 * NB: do NOT use CommitTransactionCommand/StartTransactionCommand with this.
3756 ReleaseCurrentSubTransaction(void)
3758 TransactionState s = CurrentTransactionState;
3760 if (s->blockState != TBLOCK_SUBINPROGRESS)
3761 elog(ERROR, "ReleaseCurrentSubTransaction: unexpected state %s",
3762 BlockStateAsString(s->blockState));
3763 Assert(s->state == TRANS_INPROGRESS);
3764 MemoryContextSwitchTo(CurTransactionContext);
3765 CommitSubTransaction();
3766 s = CurrentTransactionState; /* changed by pop */
3767 Assert(s->state == TRANS_INPROGRESS);
3771 * RollbackAndReleaseCurrentSubTransaction
3773 * ROLLBACK and RELEASE (ie, abort) the innermost subtransaction, regardless
3774 * of its savepoint name (if any).
3775 * NB: do NOT use CommitTransactionCommand/StartTransactionCommand with this.
3778 RollbackAndReleaseCurrentSubTransaction(void)
3780 TransactionState s = CurrentTransactionState;
3782 switch (s->blockState)
3784 /* Must be in a subtransaction */
3785 case TBLOCK_SUBINPROGRESS:
3786 case TBLOCK_SUBABORT:
3789 /* These cases are invalid. */
3790 case TBLOCK_DEFAULT:
3791 case TBLOCK_STARTED:
3793 case TBLOCK_SUBBEGIN:
3794 case TBLOCK_INPROGRESS:
3796 case TBLOCK_SUBRELEASE:
3797 case TBLOCK_SUBCOMMIT:
3799 case TBLOCK_ABORT_END:
3800 case TBLOCK_SUBABORT_END:
3801 case TBLOCK_ABORT_PENDING:
3802 case TBLOCK_SUBABORT_PENDING:
3803 case TBLOCK_SUBRESTART:
3804 case TBLOCK_SUBABORT_RESTART:
3805 case TBLOCK_PREPARE:
3806 elog(FATAL, "RollbackAndReleaseCurrentSubTransaction: unexpected state %s",
3807 BlockStateAsString(s->blockState));
3812 * Abort the current subtransaction, if needed.
3814 if (s->blockState == TBLOCK_SUBINPROGRESS)
3815 AbortSubTransaction();
3817 /* And clean it up, too */
3818 CleanupSubTransaction();
3820 s = CurrentTransactionState; /* changed by pop */
3821 AssertState(s->blockState == TBLOCK_SUBINPROGRESS ||
3822 s->blockState == TBLOCK_INPROGRESS ||
3823 s->blockState == TBLOCK_STARTED);
3827 * AbortOutOfAnyTransaction
3829 * This routine is provided for error recovery purposes. It aborts any
3830 * active transaction or transaction block, leaving the system in a known
3834 AbortOutOfAnyTransaction(void)
3836 TransactionState s = CurrentTransactionState;
3839 * Get out of any transaction or nested transaction
3843 switch (s->blockState)
3845 case TBLOCK_DEFAULT:
3846 if (s->state == TRANS_DEFAULT)
3848 /* Not in a transaction, do nothing */
3853 * We can get here after an error during transaction start
3854 * (state will be TRANS_START). Need to clean up the
3855 * incompletely started transaction. First, adjust the
3856 * low-level state to suppress warning message from
3859 if (s->state == TRANS_START)
3860 s->state = TRANS_INPROGRESS;
3862 CleanupTransaction();
3865 case TBLOCK_STARTED:
3867 case TBLOCK_INPROGRESS:
3869 case TBLOCK_ABORT_PENDING:
3870 case TBLOCK_PREPARE:
3871 /* In a transaction, so clean up */
3873 CleanupTransaction();
3874 s->blockState = TBLOCK_DEFAULT;
3877 case TBLOCK_ABORT_END:
3878 /* AbortTransaction already done, still need Cleanup */
3879 CleanupTransaction();
3880 s->blockState = TBLOCK_DEFAULT;
3884 * In a subtransaction, so clean it up and abort parent too
3886 case TBLOCK_SUBBEGIN:
3887 case TBLOCK_SUBINPROGRESS:
3888 case TBLOCK_SUBRELEASE:
3889 case TBLOCK_SUBCOMMIT:
3890 case TBLOCK_SUBABORT_PENDING:
3891 case TBLOCK_SUBRESTART:
3892 AbortSubTransaction();
3893 CleanupSubTransaction();
3894 s = CurrentTransactionState; /* changed by pop */
3897 case TBLOCK_SUBABORT:
3898 case TBLOCK_SUBABORT_END:
3899 case TBLOCK_SUBABORT_RESTART:
3900 /* As above, but AbortSubTransaction already done */
3901 CleanupSubTransaction();
3902 s = CurrentTransactionState; /* changed by pop */
3905 } while (s->blockState != TBLOCK_DEFAULT);
3907 /* Should be out of all subxacts now */
3908 Assert(s->parent == NULL);
3912 * IsTransactionBlock --- are we within a transaction block?
3915 IsTransactionBlock(void)
3917 TransactionState s = CurrentTransactionState;
3919 if (s->blockState == TBLOCK_DEFAULT || s->blockState == TBLOCK_STARTED)
3926 * IsTransactionOrTransactionBlock --- are we within either a transaction
3927 * or a transaction block? (The backend is only really "idle" when this
3930 * This should match up with IsTransactionBlock and IsTransactionState.
3933 IsTransactionOrTransactionBlock(void)
3935 TransactionState s = CurrentTransactionState;
3937 if (s->blockState == TBLOCK_DEFAULT)
3944 * TransactionBlockStatusCode - return status code to send in ReadyForQuery
3947 TransactionBlockStatusCode(void)
3949 TransactionState s = CurrentTransactionState;
3951 switch (s->blockState)
3953 case TBLOCK_DEFAULT:
3954 case TBLOCK_STARTED:
3955 return 'I'; /* idle --- not in transaction */
3957 case TBLOCK_SUBBEGIN:
3958 case TBLOCK_INPROGRESS:
3959 case TBLOCK_SUBINPROGRESS:
3961 case TBLOCK_SUBRELEASE:
3962 case TBLOCK_SUBCOMMIT:
3963 case TBLOCK_PREPARE:
3964 return 'T'; /* in transaction */
3966 case TBLOCK_SUBABORT:
3967 case TBLOCK_ABORT_END:
3968 case TBLOCK_SUBABORT_END:
3969 case TBLOCK_ABORT_PENDING:
3970 case TBLOCK_SUBABORT_PENDING:
3971 case TBLOCK_SUBRESTART:
3972 case TBLOCK_SUBABORT_RESTART:
3973 return 'E'; /* in failed transaction */
3976 /* should never get here */
3977 elog(FATAL, "invalid transaction block state: %s",
3978 BlockStateAsString(s->blockState));
3979 return 0; /* keep compiler quiet */
3986 IsSubTransaction(void)
3988 TransactionState s = CurrentTransactionState;
3990 if (s->nestingLevel >= 2)
3997 * StartSubTransaction
3999 * If you're wondering why this is separate from PushTransaction: it's because
4000 * we can't conveniently do this stuff right inside DefineSavepoint. The
4001 * SAVEPOINT utility command will be executed inside a Portal, and if we
4002 * muck with CurrentMemoryContext or CurrentResourceOwner then exit from
4003 * the Portal will undo those settings. So we make DefineSavepoint just
4004 * push a dummy transaction block, and when control returns to the main
4005 * idle loop, CommitTransactionCommand will be called, and we'll come here
4006 * to finish starting the subtransaction.
4009 StartSubTransaction(void)
4011 TransactionState s = CurrentTransactionState;
4013 if (s->state != TRANS_DEFAULT)
4014 elog(WARNING, "StartSubTransaction while in %s state",
4015 TransStateAsString(s->state));
4017 s->state = TRANS_START;
4020 * Initialize subsystems for new subtransaction
4022 * must initialize resource-management stuff first
4024 AtSubStart_Memory();
4025 AtSubStart_ResourceOwner();
4027 AtSubStart_Notify();
4028 AfterTriggerBeginSubXact();
4030 s->state = TRANS_INPROGRESS;
4033 * Call start-of-subxact callbacks
4035 CallSubXactCallbacks(SUBXACT_EVENT_START_SUB, s->subTransactionId,
4036 s->parent->subTransactionId);
4038 ShowTransactionState("StartSubTransaction");
4042 * CommitSubTransaction
4044 * The caller has to make sure to always reassign CurrentTransactionState
4045 * if it has a local pointer to it after calling this function.
4048 CommitSubTransaction(void)
4050 TransactionState s = CurrentTransactionState;
4052 ShowTransactionState("CommitSubTransaction");
4054 if (s->state != TRANS_INPROGRESS)
4055 elog(WARNING, "CommitSubTransaction while in %s state",
4056 TransStateAsString(s->state));
4058 /* Pre-commit processing goes here -- nothing to do at the moment */
4060 s->state = TRANS_COMMIT;
4062 /* Must CCI to ensure commands of subtransaction are seen as done */
4063 CommandCounterIncrement();
4066 * Prior to 8.4 we marked subcommit in clog at this point. We now only
4067 * perform that step, if required, as part of the atomic update of the
4068 * whole transaction tree at top level commit or abort.
4071 /* Post-commit cleanup */
4072 if (TransactionIdIsValid(s->transactionId))
4073 AtSubCommit_childXids();
4074 AfterTriggerEndSubXact(true);
4075 AtSubCommit_Portals(s->subTransactionId,
4076 s->parent->subTransactionId,
4077 s->parent->curTransactionOwner);
4078 AtEOSubXact_LargeObject(true, s->subTransactionId,
4079 s->parent->subTransactionId);
4080 AtSubCommit_Notify();
4082 CallSubXactCallbacks(SUBXACT_EVENT_COMMIT_SUB, s->subTransactionId,
4083 s->parent->subTransactionId);
4085 ResourceOwnerRelease(s->curTransactionOwner,
4086 RESOURCE_RELEASE_BEFORE_LOCKS,
4088 AtEOSubXact_RelationCache(true, s->subTransactionId,
4089 s->parent->subTransactionId);
4090 AtEOSubXact_Inval(true);
4094 * The only lock we actually release here is the subtransaction XID lock.
4096 CurrentResourceOwner = s->curTransactionOwner;
4097 if (TransactionIdIsValid(s->transactionId))
4098 XactLockTableDelete(s->transactionId);
4101 * Other locks should get transferred to their parent resource owner.
4103 ResourceOwnerRelease(s->curTransactionOwner,
4104 RESOURCE_RELEASE_LOCKS,
4106 ResourceOwnerRelease(s->curTransactionOwner,
4107 RESOURCE_RELEASE_AFTER_LOCKS,
4110 AtEOXact_GUC(true, s->gucNestLevel);
4111 AtEOSubXact_SPI(true, s->subTransactionId);
4112 AtEOSubXact_on_commit_actions(true, s->subTransactionId,
4113 s->parent->subTransactionId);
4114 AtEOSubXact_Namespace(true, s->subTransactionId,
4115 s->parent->subTransactionId);
4116 AtEOSubXact_Files(true, s->subTransactionId,
4117 s->parent->subTransactionId);
4118 AtEOSubXact_HashTables(true, s->nestingLevel);
4119 AtEOSubXact_PgStat(true, s->nestingLevel);
4120 AtSubCommit_Snapshot(s->nestingLevel);
4123 * We need to restore the upper transaction's read-only state, in case the
4124 * upper is read-write while the child is read-only; GUC will incorrectly
4125 * think it should leave the child state in place.
4127 XactReadOnly = s->prevXactReadOnly;
4129 CurrentResourceOwner = s->parent->curTransactionOwner;
4130 CurTransactionResourceOwner = s->parent->curTransactionOwner;
4131 ResourceOwnerDelete(s->curTransactionOwner);
4132 s->curTransactionOwner = NULL;
4134 AtSubCommit_Memory();
4136 s->state = TRANS_DEFAULT;
4142 * AbortSubTransaction
4145 AbortSubTransaction(void)
4147 TransactionState s = CurrentTransactionState;
4149 /* Prevent cancel/die interrupt while cleaning up */
4152 /* Make sure we have a valid memory context and resource owner */
4153 AtSubAbort_Memory();
4154 AtSubAbort_ResourceOwner();
4157 * Release any LW locks we might be holding as quickly as possible.
4158 * (Regular locks, however, must be held till we finish aborting.)
4159 * Releasing LW locks is critical since we might try to grab them again
4160 * while cleaning up!
4162 * FIXME This may be incorrect --- Are there some locks we should keep?
4163 * Buffer locks, for example? I don't think so but I'm not sure.
4173 * check the current transaction state
4175 ShowTransactionState("AbortSubTransaction");
4177 if (s->state != TRANS_INPROGRESS)
4178 elog(WARNING, "AbortSubTransaction while in %s state",
4179 TransStateAsString(s->state));
4181 s->state = TRANS_ABORT;
4184 * Reset user ID which might have been changed transiently. (See notes in
4185 * AbortTransaction.)
4187 SetUserIdAndSecContext(s->prevUser, s->prevSecContext);
4190 * We can skip all this stuff if the subxact failed before creating a
4193 if (s->curTransactionOwner)
4195 AfterTriggerEndSubXact(false);
4196 AtSubAbort_Portals(s->subTransactionId,
4197 s->parent->subTransactionId,
4198 s->parent->curTransactionOwner);
4199 AtEOSubXact_LargeObject(false, s->subTransactionId,
4200 s->parent->subTransactionId);
4201 AtSubAbort_Notify();
4203 /* Advertise the fact that we aborted in pg_clog. */
4204 (void) RecordTransactionAbort(true);
4206 /* Post-abort cleanup */
4207 if (TransactionIdIsValid(s->transactionId))
4208 AtSubAbort_childXids();
4210 CallSubXactCallbacks(SUBXACT_EVENT_ABORT_SUB, s->subTransactionId,
4211 s->parent->subTransactionId);
4213 ResourceOwnerRelease(s->curTransactionOwner,
4214 RESOURCE_RELEASE_BEFORE_LOCKS,
4216 AtEOSubXact_RelationCache(false, s->subTransactionId,
4217 s->parent->subTransactionId);
4218 AtEOSubXact_Inval(false);
4219 ResourceOwnerRelease(s->curTransactionOwner,
4220 RESOURCE_RELEASE_LOCKS,
4222 ResourceOwnerRelease(s->curTransactionOwner,
4223 RESOURCE_RELEASE_AFTER_LOCKS,
4227 AtEOXact_GUC(false, s->gucNestLevel);
4228 AtEOSubXact_SPI(false, s->subTransactionId);
4229 AtEOSubXact_on_commit_actions(false, s->subTransactionId,
4230 s->parent->subTransactionId);
4231 AtEOSubXact_Namespace(false, s->subTransactionId,
4232 s->parent->subTransactionId);
4233 AtEOSubXact_Files(false, s->subTransactionId,
4234 s->parent->subTransactionId);
4235 AtEOSubXact_HashTables(false, s->nestingLevel);
4236 AtEOSubXact_PgStat(false, s->nestingLevel);
4237 AtSubAbort_Snapshot(s->nestingLevel);
4241 * Restore the upper transaction's read-only state, too. This should be
4242 * redundant with GUC's cleanup but we may as well do it for consistency
4243 * with the commit case.
4245 XactReadOnly = s->prevXactReadOnly;
4247 RESUME_INTERRUPTS();
4251 * CleanupSubTransaction
4253 * The caller has to make sure to always reassign CurrentTransactionState
4254 * if it has a local pointer to it after calling this function.
4257 CleanupSubTransaction(void)
4259 TransactionState s = CurrentTransactionState;
4261 ShowTransactionState("CleanupSubTransaction");
4263 if (s->state != TRANS_ABORT)
4264 elog(WARNING, "CleanupSubTransaction while in %s state",
4265 TransStateAsString(s->state));
4267 AtSubCleanup_Portals(s->subTransactionId);
4269 CurrentResourceOwner = s->parent->curTransactionOwner;
4270 CurTransactionResourceOwner = s->parent->curTransactionOwner;
4271 if (s->curTransactionOwner)
4272 ResourceOwnerDelete(s->curTransactionOwner);
4273 s->curTransactionOwner = NULL;
4275 AtSubCleanup_Memory();
4277 s->state = TRANS_DEFAULT;
4284 * Create transaction state stack entry for a subtransaction
4286 * The caller has to make sure to always reassign CurrentTransactionState
4287 * if it has a local pointer to it after calling this function.
4290 PushTransaction(void)
4292 TransactionState p = CurrentTransactionState;
4296 * We keep subtransaction state nodes in TopTransactionContext.
4298 s = (TransactionState)
4299 MemoryContextAllocZero(TopTransactionContext,
4300 sizeof(TransactionStateData));
4303 * Assign a subtransaction ID, watching out for counter wraparound.
4305 currentSubTransactionId += 1;
4306 if (currentSubTransactionId == InvalidSubTransactionId)
4308 currentSubTransactionId -= 1;
4311 (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
4312 errmsg("cannot have more than 2^32-1 subtransactions in a transaction")));
4316 * We can now stack a minimally valid subtransaction without fear of
4319 s->transactionId = InvalidTransactionId; /* until assigned */
4320 s->subTransactionId = currentSubTransactionId;
4322 s->nestingLevel = p->nestingLevel + 1;
4323 s->gucNestLevel = NewGUCNestLevel();
4324 s->savepointLevel = p->savepointLevel;
4325 s->state = TRANS_DEFAULT;
4326 s->blockState = TBLOCK_SUBBEGIN;
4327 GetUserIdAndSecContext(&s->prevUser, &s->prevSecContext);
4328 s->prevXactReadOnly = XactReadOnly;
4330 CurrentTransactionState = s;
4333 * AbortSubTransaction and CleanupSubTransaction have to be able to cope
4334 * with the subtransaction from here on out; in particular they should not
4335 * assume that it necessarily has a transaction context, resource owner,
4342 * Pop back to parent transaction state
4344 * The caller has to make sure to always reassign CurrentTransactionState
4345 * if it has a local pointer to it after calling this function.
4348 PopTransaction(void)
4350 TransactionState s = CurrentTransactionState;
4352 if (s->state != TRANS_DEFAULT)
4353 elog(WARNING, "PopTransaction while in %s state",
4354 TransStateAsString(s->state));
4356 if (s->parent == NULL)
4357 elog(FATAL, "PopTransaction with no parent");
4359 CurrentTransactionState = s->parent;
4361 /* Let's just make sure CurTransactionContext is good */
4362 CurTransactionContext = s->parent->curTransactionContext;
4363 MemoryContextSwitchTo(CurTransactionContext);
4365 /* Ditto for ResourceOwner links */
4366 CurTransactionResourceOwner = s->parent->curTransactionOwner;
4367 CurrentResourceOwner = s->parent->curTransactionOwner;
4369 /* Free the old child structure */
4376 * ShowTransactionState
4380 ShowTransactionState(const char *str)
4382 /* skip work if message will definitely not be printed */
4383 if (log_min_messages <= DEBUG3 || client_min_messages <= DEBUG3)
4385 elog(DEBUG3, "%s", str);
4386 ShowTransactionStateRec(CurrentTransactionState);
4391 * ShowTransactionStateRec
4392 * Recursive subroutine for ShowTransactionState
4395 ShowTransactionStateRec(TransactionState s)
4399 initStringInfo(&buf);
4401 if (s->nChildXids > 0)
4405 appendStringInfo(&buf, "%u", s->childXids[0]);
4406 for (i = 1; i < s->nChildXids; i++)
4407 appendStringInfo(&buf, " %u", s->childXids[i]);
4411 ShowTransactionStateRec(s->parent);
4413 /* use ereport to suppress computation if msg will not be printed */
4415 (errmsg_internal("name: %s; blockState: %13s; state: %7s, xid/subid/cid: %u/%u/%u%s, nestlvl: %d, children: %s",
4416 PointerIsValid(s->name) ? s->name : "unnamed",
4417 BlockStateAsString(s->blockState),
4418 TransStateAsString(s->state),
4419 (unsigned int) s->transactionId,
4420 (unsigned int) s->subTransactionId,
4421 (unsigned int) currentCommandId,
4422 currentCommandIdUsed ? " (used)" : "",
4423 s->nestingLevel, buf.data)));
4429 * BlockStateAsString
4433 BlockStateAsString(TBlockState blockState)
4437 case TBLOCK_DEFAULT:
4439 case TBLOCK_STARTED:
4443 case TBLOCK_INPROGRESS:
4444 return "INPROGRESS";
4449 case TBLOCK_ABORT_END:
4451 case TBLOCK_ABORT_PENDING:
4452 return "ABORT PEND";
4453 case TBLOCK_PREPARE:
4455 case TBLOCK_SUBBEGIN:
4457 case TBLOCK_SUBINPROGRESS:
4458 return "SUB INPROGRS";
4459 case TBLOCK_SUBRELEASE:
4460 return "SUB RELEASE";
4461 case TBLOCK_SUBCOMMIT:
4462 return "SUB COMMIT";
4463 case TBLOCK_SUBABORT:
4465 case TBLOCK_SUBABORT_END:
4466 return "SUB ABORT END";
4467 case TBLOCK_SUBABORT_PENDING:
4468 return "SUB ABRT PEND";
4469 case TBLOCK_SUBRESTART:
4470 return "SUB RESTART";
4471 case TBLOCK_SUBABORT_RESTART:
4472 return "SUB AB RESTRT";
4474 return "UNRECOGNIZED";
4478 * TransStateAsString
4482 TransStateAsString(TransState state)
4490 case TRANS_INPROGRESS:
4499 return "UNRECOGNIZED";
4503 * xactGetCommittedChildren
4505 * Gets the list of committed children of the current transaction. The return
4506 * value is the number of child transactions. *ptr is set to point to an
4507 * array of TransactionIds. The array is allocated in TopTransactionContext;
4508 * the caller should *not* pfree() it (this is a change from pre-8.4 code!).
4509 * If there are no subxacts, *ptr is set to NULL.
4512 xactGetCommittedChildren(TransactionId **ptr)
4514 TransactionState s = CurrentTransactionState;
4516 if (s->nChildXids == 0)
4519 *ptr = s->childXids;
4521 return s->nChildXids;
4525 * XLOG support routines
4529 * Before 9.0 this was a fairly short function, but now it performs many
4530 * actions for which the order of execution is critical.
4533 xact_redo_commit_internal(TransactionId xid, XLogRecPtr lsn,
4534 TransactionId *sub_xids, int nsubxacts,
4535 SharedInvalidationMessage *inval_msgs, int nmsgs,
4536 RelFileNode *xnodes, int nrels,
4540 TransactionId max_xid;
4543 max_xid = TransactionIdLatest(xid, nsubxacts, sub_xids);
4546 * Make sure nextXid is beyond any XID mentioned in the record.
4548 * We don't expect anyone else to modify nextXid, hence we don't need to
4549 * hold a lock while checking this. We still acquire the lock to modify
4552 if (TransactionIdFollowsOrEquals(max_xid,
4553 ShmemVariableCache->nextXid))
4555 LWLockAcquire(XidGenLock, LW_EXCLUSIVE);
4556 ShmemVariableCache->nextXid = max_xid;
4557 TransactionIdAdvance(ShmemVariableCache->nextXid);
4558 LWLockRelease(XidGenLock);
4561 if (standbyState == STANDBY_DISABLED)
4564 * Mark the transaction committed in pg_clog.
4566 TransactionIdCommitTree(xid, nsubxacts, sub_xids);
4571 * If a transaction completion record arrives that has as-yet
4572 * unobserved subtransactions then this will not have been fully
4573 * handled by the call to RecordKnownAssignedTransactionIds() in the
4574 * main recovery loop in xlog.c. So we need to do bookkeeping again to
4575 * cover that case. This is confusing and it is easy to think this
4576 * call is irrelevant, which has happened three times in development
4577 * already. Leave it in.
4579 RecordKnownAssignedTransactionIds(max_xid);
4582 * Mark the transaction committed in pg_clog. We use async commit
4583 * protocol during recovery to provide information on database
4584 * consistency for when users try to set hint bits. It is important
4585 * that we do not set hint bits until the minRecoveryPoint is past
4586 * this commit record. This ensures that if we crash we don't see hint
4587 * bits set on changes made by transactions that haven't yet
4588 * recovered. It's unlikely but it's good to be safe.
4590 TransactionIdAsyncCommitTree(xid, nsubxacts, sub_xids, lsn);
4593 * We must mark clog before we update the ProcArray.
4595 ExpireTreeKnownAssignedTransactionIds(xid, nsubxacts, sub_xids, max_xid);
4598 * Send any cache invalidations attached to the commit. We must
4599 * maintain the same order of invalidation then release locks as
4600 * occurs in CommitTransaction().
4602 ProcessCommittedInvalidationMessages(inval_msgs, nmsgs,
4603 XactCompletionRelcacheInitFileInval(xinfo),
4607 * Release locks, if any. We do this for both two phase and normal one
4608 * phase transactions. In effect we are ignoring the prepare phase and
4609 * just going straight to lock release.
4611 StandbyReleaseLockTree(xid, nsubxacts, sub_xids);
4614 /* Make sure files supposed to be dropped are dropped */
4615 for (i = 0; i < nrels; i++)
4617 SMgrRelation srel = smgropen(xnodes[i], InvalidBackendId);
4620 for (fork = 0; fork <= MAX_FORKNUM; fork++)
4621 XLogDropRelation(xnodes[i], fork);
4622 smgrdounlink(srel, true);
4627 * We issue an XLogFlush() for the same reason we emit ForceSyncCommit()
4628 * in normal operation. For example, in DROP DATABASE, we delete all the
4629 * files belonging to the database, and then commit the transaction. If we
4630 * crash after all the files have been deleted but before the commit, you
4631 * have an entry in pg_database without any files. To minimize the window
4632 * for that, we use ForceSyncCommit() to rush the commit record to disk as
4633 * quick as possible. We have the same window during recovery, and forcing
4634 * an XLogFlush() (which updates minRecoveryPoint during recovery) helps
4635 * to reduce that problem window, for any user that requested
4636 * ForceSyncCommit().
4638 if (XactCompletionForceSyncCommit(xinfo))
4644 * Utility function to call xact_redo_commit_internal after breaking down xlrec
4647 xact_redo_commit(xl_xact_commit *xlrec,
4648 TransactionId xid, XLogRecPtr lsn)
4650 TransactionId *subxacts;
4651 SharedInvalidationMessage *inval_msgs;
4653 /* subxid array follows relfilenodes */
4654 subxacts = (TransactionId *) &(xlrec->xnodes[xlrec->nrels]);
4655 /* invalidation messages array follows subxids */
4656 inval_msgs = (SharedInvalidationMessage *) &(subxacts[xlrec->nsubxacts]);
4658 xact_redo_commit_internal(xid, lsn, subxacts, xlrec->nsubxacts,
4659 inval_msgs, xlrec->nmsgs,
4660 xlrec->xnodes, xlrec->nrels,
4667 * Utility function to call xact_redo_commit_internal for compact form of message.
4670 xact_redo_commit_compact(xl_xact_commit_compact *xlrec,
4671 TransactionId xid, XLogRecPtr lsn)
4673 xact_redo_commit_internal(xid, lsn, xlrec->subxacts, xlrec->nsubxacts,
4674 NULL, 0, /* inval msgs */
4675 NULL, 0, /* relfilenodes */
4676 InvalidOid, /* dbId */
4677 InvalidOid, /* tsId */
4682 * Be careful with the order of execution, as with xact_redo_commit().
4683 * The two functions are similar but differ in key places.
4685 * Note also that an abort can be for a subtransaction and its children,
4686 * not just for a top level abort. That means we have to consider
4687 * topxid != xid, whereas in commit we would find topxid == xid always
4688 * because subtransaction commit is never WAL logged.
4691 xact_redo_abort(xl_xact_abort *xlrec, TransactionId xid)
4693 TransactionId *sub_xids;
4694 TransactionId max_xid;
4697 sub_xids = (TransactionId *) &(xlrec->xnodes[xlrec->nrels]);
4698 max_xid = TransactionIdLatest(xid, xlrec->nsubxacts, sub_xids);
4701 * Make sure nextXid is beyond any XID mentioned in the record.
4703 * We don't expect anyone else to modify nextXid, hence we don't need to
4704 * hold a lock while checking this. We still acquire the lock to modify
4707 if (TransactionIdFollowsOrEquals(max_xid,
4708 ShmemVariableCache->nextXid))
4710 LWLockAcquire(XidGenLock, LW_EXCLUSIVE);
4711 ShmemVariableCache->nextXid = max_xid;
4712 TransactionIdAdvance(ShmemVariableCache->nextXid);
4713 LWLockRelease(XidGenLock);
4716 if (standbyState == STANDBY_DISABLED)
4718 /* Mark the transaction aborted in pg_clog, no need for async stuff */
4719 TransactionIdAbortTree(xid, xlrec->nsubxacts, sub_xids);
4724 * If a transaction completion record arrives that has as-yet
4725 * unobserved subtransactions then this will not have been fully
4726 * handled by the call to RecordKnownAssignedTransactionIds() in the
4727 * main recovery loop in xlog.c. So we need to do bookkeeping again to
4728 * cover that case. This is confusing and it is easy to think this
4729 * call is irrelevant, which has happened three times in development
4730 * already. Leave it in.
4732 RecordKnownAssignedTransactionIds(max_xid);
4734 /* Mark the transaction aborted in pg_clog, no need for async stuff */
4735 TransactionIdAbortTree(xid, xlrec->nsubxacts, sub_xids);
4738 * We must update the ProcArray after we have marked clog.
4740 ExpireTreeKnownAssignedTransactionIds(xid, xlrec->nsubxacts, sub_xids, max_xid);
4743 * There are no flat files that need updating, nor invalidation
4744 * messages to send or undo.
4748 * Release locks, if any. There are no invalidations to send.
4750 StandbyReleaseLockTree(xid, xlrec->nsubxacts, sub_xids);
4753 /* Make sure files supposed to be dropped are dropped */
4754 for (i = 0; i < xlrec->nrels; i++)
4756 SMgrRelation srel = smgropen(xlrec->xnodes[i], InvalidBackendId);
4759 for (fork = 0; fork <= MAX_FORKNUM; fork++)
4760 XLogDropRelation(xlrec->xnodes[i], fork);
4761 smgrdounlink(srel, true);
4767 xact_redo(XLogRecPtr lsn, XLogRecord *record)
4769 uint8 info = record->xl_info & ~XLR_INFO_MASK;
4771 /* Backup blocks are not used in xact records */
4772 Assert(!(record->xl_info & XLR_BKP_BLOCK_MASK));
4774 if (info == XLOG_XACT_COMMIT_COMPACT)
4776 xl_xact_commit_compact *xlrec = (xl_xact_commit_compact *) XLogRecGetData(record);
4778 xact_redo_commit_compact(xlrec, record->xl_xid, lsn);
4780 else if (info == XLOG_XACT_COMMIT)
4782 xl_xact_commit *xlrec = (xl_xact_commit *) XLogRecGetData(record);
4784 xact_redo_commit(xlrec, record->xl_xid, lsn);
4786 else if (info == XLOG_XACT_ABORT)
4788 xl_xact_abort *xlrec = (xl_xact_abort *) XLogRecGetData(record);
4790 xact_redo_abort(xlrec, record->xl_xid);
4792 else if (info == XLOG_XACT_PREPARE)
4794 /* the record contents are exactly the 2PC file */
4795 RecreateTwoPhaseFile(record->xl_xid,
4796 XLogRecGetData(record), record->xl_len);
4798 else if (info == XLOG_XACT_COMMIT_PREPARED)
4800 xl_xact_commit_prepared *xlrec = (xl_xact_commit_prepared *) XLogRecGetData(record);
4802 xact_redo_commit(&xlrec->crec, xlrec->xid, lsn);
4803 RemoveTwoPhaseFile(xlrec->xid, false);
4805 else if (info == XLOG_XACT_ABORT_PREPARED)
4807 xl_xact_abort_prepared *xlrec = (xl_xact_abort_prepared *) XLogRecGetData(record);
4809 xact_redo_abort(&xlrec->arec, xlrec->xid);
4810 RemoveTwoPhaseFile(xlrec->xid, false);
4812 else if (info == XLOG_XACT_ASSIGNMENT)
4814 xl_xact_assignment *xlrec = (xl_xact_assignment *) XLogRecGetData(record);
4816 if (standbyState >= STANDBY_INITIALIZED)
4817 ProcArrayApplyXidAssignment(xlrec->xtop,
4818 xlrec->nsubxacts, xlrec->xsub);
4821 elog(PANIC, "xact_redo: unknown op code %u", info);
4825 xact_desc_commit(StringInfo buf, xl_xact_commit *xlrec)
4828 TransactionId *subxacts;
4830 subxacts = (TransactionId *) &xlrec->xnodes[xlrec->nrels];
4832 appendStringInfoString(buf, timestamptz_to_str(xlrec->xact_time));
4834 if (xlrec->nrels > 0)
4836 appendStringInfo(buf, "; rels:");
4837 for (i = 0; i < xlrec->nrels; i++)
4839 char *path = relpathperm(xlrec->xnodes[i], MAIN_FORKNUM);
4841 appendStringInfo(buf, " %s", path);
4845 if (xlrec->nsubxacts > 0)
4847 appendStringInfo(buf, "; subxacts:");
4848 for (i = 0; i < xlrec->nsubxacts; i++)
4849 appendStringInfo(buf, " %u", subxacts[i]);
4851 if (xlrec->nmsgs > 0)
4853 SharedInvalidationMessage *msgs;
4855 msgs = (SharedInvalidationMessage *) &subxacts[xlrec->nsubxacts];
4857 if (XactCompletionRelcacheInitFileInval(xlrec->xinfo))
4858 appendStringInfo(buf, "; relcache init file inval dbid %u tsid %u",
4859 xlrec->dbId, xlrec->tsId);
4861 appendStringInfo(buf, "; inval msgs:");
4862 for (i = 0; i < xlrec->nmsgs; i++)
4864 SharedInvalidationMessage *msg = &msgs[i];
4867 appendStringInfo(buf, " catcache %d", msg->id);
4868 else if (msg->id == SHAREDINVALCATALOG_ID)
4869 appendStringInfo(buf, " catalog %u", msg->cat.catId);
4870 else if (msg->id == SHAREDINVALRELCACHE_ID)
4871 appendStringInfo(buf, " relcache %u", msg->rc.relId);
4872 /* remaining cases not expected, but print something anyway */
4873 else if (msg->id == SHAREDINVALSMGR_ID)
4874 appendStringInfo(buf, " smgr");
4875 else if (msg->id == SHAREDINVALRELMAP_ID)
4876 appendStringInfo(buf, " relmap");
4878 appendStringInfo(buf, " unknown id %d", msg->id);
4884 xact_desc_commit_compact(StringInfo buf, xl_xact_commit_compact *xlrec)
4888 appendStringInfoString(buf, timestamptz_to_str(xlrec->xact_time));
4890 if (xlrec->nsubxacts > 0)
4892 appendStringInfo(buf, "; subxacts:");
4893 for (i = 0; i < xlrec->nsubxacts; i++)
4894 appendStringInfo(buf, " %u", xlrec->subxacts[i]);
4899 xact_desc_abort(StringInfo buf, xl_xact_abort *xlrec)
4903 appendStringInfoString(buf, timestamptz_to_str(xlrec->xact_time));
4904 if (xlrec->nrels > 0)
4906 appendStringInfo(buf, "; rels:");
4907 for (i = 0; i < xlrec->nrels; i++)
4909 char *path = relpathperm(xlrec->xnodes[i], MAIN_FORKNUM);
4911 appendStringInfo(buf, " %s", path);
4915 if (xlrec->nsubxacts > 0)
4917 TransactionId *xacts = (TransactionId *)
4918 &xlrec->xnodes[xlrec->nrels];
4920 appendStringInfo(buf, "; subxacts:");
4921 for (i = 0; i < xlrec->nsubxacts; i++)
4922 appendStringInfo(buf, " %u", xacts[i]);
4927 xact_desc_assignment(StringInfo buf, xl_xact_assignment *xlrec)
4931 appendStringInfo(buf, "subxacts:");
4933 for (i = 0; i < xlrec->nsubxacts; i++)
4934 appendStringInfo(buf, " %u", xlrec->xsub[i]);
4938 xact_desc(StringInfo buf, uint8 xl_info, char *rec)
4940 uint8 info = xl_info & ~XLR_INFO_MASK;
4942 if (info == XLOG_XACT_COMMIT_COMPACT)
4944 xl_xact_commit_compact *xlrec = (xl_xact_commit_compact *) rec;
4946 appendStringInfo(buf, "commit: ");
4947 xact_desc_commit_compact(buf, xlrec);
4949 else if (info == XLOG_XACT_COMMIT)
4951 xl_xact_commit *xlrec = (xl_xact_commit *) rec;
4953 appendStringInfo(buf, "commit: ");
4954 xact_desc_commit(buf, xlrec);
4956 else if (info == XLOG_XACT_ABORT)
4958 xl_xact_abort *xlrec = (xl_xact_abort *) rec;
4960 appendStringInfo(buf, "abort: ");
4961 xact_desc_abort(buf, xlrec);
4963 else if (info == XLOG_XACT_PREPARE)
4965 appendStringInfo(buf, "prepare");
4967 else if (info == XLOG_XACT_COMMIT_PREPARED)
4969 xl_xact_commit_prepared *xlrec = (xl_xact_commit_prepared *) rec;
4971 appendStringInfo(buf, "commit prepared %u: ", xlrec->xid);
4972 xact_desc_commit(buf, &xlrec->crec);
4974 else if (info == XLOG_XACT_ABORT_PREPARED)
4976 xl_xact_abort_prepared *xlrec = (xl_xact_abort_prepared *) rec;
4978 appendStringInfo(buf, "abort prepared %u: ", xlrec->xid);
4979 xact_desc_abort(buf, &xlrec->arec);
4981 else if (info == XLOG_XACT_ASSIGNMENT)
4983 xl_xact_assignment *xlrec = (xl_xact_assignment *) rec;
4986 * Note that we ignore the WAL record's xid, since we're more
4987 * interested in the top-level xid that issued the record and which
4988 * xids are being reported here.
4990 appendStringInfo(buf, "xid assignment xtop %u: ", xlrec->xtop);
4991 xact_desc_assignment(buf, xlrec);
4994 appendStringInfo(buf, "UNKNOWN");