1 /*-------------------------------------------------------------------------
4 * top level transaction system support routines
6 * Portions Copyright (c) 1996-2001, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
11 * $Header: /cvsroot/pgsql/src/backend/access/transam/xact.c,v 1.123 2002/05/21 22:05:53 tgl Exp $
14 * Transaction aborts can now occur two ways:
16 * 1) system dies from some internal cause (Assert, etc..)
19 * These two cases used to be treated identically, but now
20 * we need to distinguish them. Why? consider the following
25 * 1) user types BEGIN 1) user types BEGIN
26 * 2) user does something 2) user does something
27 * 3) user does not like what 3) system aborts for some reason
28 * she sees and types ABORT
30 * In case 1, we want to abort the transaction and return to the
31 * default state. In case 2, there may be more commands coming
32 * our way which are part of the same transaction block and we have
33 * to ignore these commands until we see an END transaction.
34 * (or an ABORT! --djm)
36 * Internal aborts are now handled by AbortTransactionBlock(), just as
37 * they always have been, and user aborts are now handled by
38 * UserAbortTransactionBlock(). Both of them rely on AbortTransaction()
39 * to do all the real work. The only difference is what state we
40 * enter after AbortTransaction() does its work:
42 * * AbortTransactionBlock() leaves us in TBLOCK_ABORT and
43 * * UserAbortTransactionBlock() leaves us in TBLOCK_ENDABORT
45 * Low-level transaction abort handling is divided into two phases:
46 * * AbortTransaction() executes as soon as we realize the transaction
47 * has failed. It should release all shared resources (locks etc)
48 * so that we do not delay other backends unnecessarily.
49 * * CleanupTransaction() executes when we finally see a user COMMIT
50 * or ROLLBACK command; it cleans things up and gets us out of
51 * the transaction internally. In particular, we mustn't destroy
52 * TransactionCommandContext until this point.
55 * This file is an attempt at a redesign of the upper layer
56 * of the V1 transaction system which was too poorly thought
57 * out to describe. This new system hopes to be both simpler
58 * in design, simpler to extend and needs to contain added
59 * functionality to solve problems beyond the scope of the V1
60 * system. (In particuler, communication of transaction
61 * information between parallel backends has to be supported)
63 * The essential aspects of the transaction system are:
65 * o transaction id generation
66 * o transaction log updating
68 * o cache invalidation
71 * Hence, the functional division of the transaction code is
72 * based on what of the above things need to be done during
73 * a start/commit/abort transaction. For instance, the
74 * routine AtCommit_Memory() takes care of all the memory
75 * cleanup stuff done at commit time.
77 * The code is layered as follows:
84 * are provided to do the lower level work like recording
85 * the transaction status in the log and doing memory cleanup.
86 * above these routines are another set of functions:
88 * StartTransactionCommand
89 * CommitTransactionCommand
90 * AbortCurrentTransaction
92 * These are the routines used in the postgres main processing
93 * loop. They are sensitive to the current transaction block state
94 * and make calls to the lower level routines appropriately.
96 * Support for transaction blocks is provided via the functions:
98 * StartTransactionBlock
99 * CommitTransactionBlock
100 * AbortTransactionBlock
102 * These are invoked only in responce to a user "BEGIN", "END",
103 * or "ABORT" command. The tricky part about these functions
104 * is that they are called within the postgres main loop, in between
105 * the StartTransactionCommand() and CommitTransactionCommand().
107 * For example, consider the following sequence of user commands:
110 * 2) retrieve (foo.all)
111 * 3) append foo (bar = baz)
114 * in the main processing loop, this results in the following
115 * transaction sequence:
117 * / StartTransactionCommand();
118 * 1) / ProcessUtility(); << begin
119 * \ StartTransactionBlock();
120 * \ CommitTransactionCommand();
122 * / StartTransactionCommand();
123 * 2) < ProcessQuery(); << retrieve (foo.all)
124 * \ CommitTransactionCommand();
126 * / StartTransactionCommand();
127 * 3) < ProcessQuery(); << append foo (bar = baz)
128 * \ CommitTransactionCommand();
130 * / StartTransactionCommand();
131 * 4) / ProcessUtility(); << end
132 * \ CommitTransactionBlock();
133 * \ CommitTransactionCommand();
135 * The point of this example is to demonstrate the need for
136 * StartTransactionCommand() and CommitTransactionCommand() to
137 * be state smart -- they should do nothing in between the calls
138 * to StartTransactionBlock() and EndTransactionBlock() and
139 * outside these calls they need to do normal start/commit
142 * Furthermore, suppose the "retrieve (foo.all)" caused an abort
143 * condition. We would then want to abort the transaction and
144 * ignore all subsequent commands up to the "end".
147 *-------------------------------------------------------------------------
151 * Large object clean up added in CommitTransaction() to prevent buffer leaks.
153 * [PA] is Pascal André <andre@via.ecp.fr>
155 #include "postgres.h"
158 #include <sys/time.h>
160 #include "access/gistscan.h"
161 #include "access/hash.h"
162 #include "access/nbtree.h"
163 #include "access/rtree.h"
164 #include "access/xact.h"
165 #include "catalog/heap.h"
166 #include "catalog/index.h"
167 #include "catalog/namespace.h"
168 #include "commands/async.h"
169 #include "commands/sequence.h"
170 #include "commands/trigger.h"
171 #include "executor/spi.h"
172 #include "libpq/be-fsstubs.h"
173 #include "miscadmin.h"
174 #include "storage/proc.h"
175 #include "storage/sinval.h"
176 #include "storage/smgr.h"
177 #include "utils/guc.h"
178 #include "utils/inval.h"
179 #include "utils/memutils.h"
180 #include "utils/portal.h"
181 #include "utils/catcache.h"
182 #include "utils/relcache.h"
186 extern bool SharedBufferChanged;
188 static void AbortTransaction(void);
189 static void AtAbort_Cache(void);
190 static void AtAbort_Locks(void);
191 static void AtAbort_Memory(void);
192 static void AtCleanup_Memory(void);
193 static void AtCommit_Cache(void);
194 static void AtCommit_LocalCache(void);
195 static void AtCommit_Locks(void);
196 static void AtCommit_Memory(void);
197 static void AtStart_Cache(void);
198 static void AtStart_Locks(void);
199 static void AtStart_Memory(void);
200 static void CleanupTransaction(void);
201 static void CommitTransaction(void);
202 static void RecordTransactionAbort(void);
203 static void StartTransaction(void);
206 * global variables holding the current transaction state.
209 static TransactionStateData CurrentTransactionStateData = {
210 0, /* transaction id */
211 FirstCommandId, /* command id */
212 0, /* scan command id */
213 0x0, /* start time */
214 TRANS_DEFAULT, /* transaction state */
215 TBLOCK_DEFAULT /* transaction block state */
218 TransactionState CurrentTransactionState = &CurrentTransactionStateData;
221 * User-tweakable parameters
223 int DefaultXactIsoLevel = XACT_READ_COMMITTED;
226 int CommitDelay = 0; /* precommit delay in microseconds */
227 int CommitSiblings = 5; /* number of concurrent xacts needed to
230 static void (*_RollbackFunc) (void *) = NULL;
231 static void *_RollbackData = NULL;
234 * catalog creation transaction bootstrapping flag.
235 * This should be eliminated and added to the transaction
236 * state stuff. -cim 3/19/90
239 bool AMI_OVERRIDE = false;
241 /* ----------------------------------------------------------------
242 * transaction state accessors
243 * ----------------------------------------------------------------
248 /* --------------------------------
249 * TransactionFlushEnabled()
250 * SetTransactionFlushEnabled()
252 * These are used to test and set the "TransactionFlushState"
253 * varable. If this variable is true (the default), then
254 * the system will flush all dirty buffers to disk at the end
255 * of each transaction. If false then we are assuming the
256 * buffer pool resides in stable main memory, in which case we
257 * only do writes as necessary.
258 * --------------------------------
260 static int TransactionFlushState = 1;
263 TransactionFlushEnabled(void)
265 return TransactionFlushState;
269 SetTransactionFlushEnabled(bool state)
271 TransactionFlushState = (state == true);
277 /* --------------------------------
280 * This returns true if we are currently running a query
281 * within an executing transaction.
282 * --------------------------------
285 IsTransactionState(void)
287 TransactionState s = CurrentTransactionState;
295 case TRANS_INPROGRESS:
304 * Shouldn't get here, but lint is not happy with this...
309 /* --------------------------------
310 * IsAbortedTransactionBlockState
312 * This returns true if we are currently running a query
313 * within an aborted transaction block.
314 * --------------------------------
317 IsAbortedTransactionBlockState(void)
319 TransactionState s = CurrentTransactionState;
321 if (s->blockState == TBLOCK_ABORT)
328 /* --------------------------------
329 * GetCurrentTransactionId
330 * --------------------------------
333 GetCurrentTransactionId(void)
335 TransactionState s = CurrentTransactionState;
337 return s->transactionIdData;
341 /* --------------------------------
342 * GetCurrentCommandId
343 * --------------------------------
346 GetCurrentCommandId(void)
348 TransactionState s = CurrentTransactionState;
354 /* --------------------------------
355 * GetCurrentTransactionStartTime
356 * --------------------------------
359 GetCurrentTransactionStartTime(void)
361 TransactionState s = CurrentTransactionState;
367 /* --------------------------------
368 * GetCurrentTransactionStartTimeUsec
369 * --------------------------------
372 GetCurrentTransactionStartTimeUsec(int *msec)
374 TransactionState s = CurrentTransactionState;
376 *msec = s->startTimeUsec;
382 /* --------------------------------
383 * TransactionIdIsCurrentTransactionId
384 * --------------------------------
387 TransactionIdIsCurrentTransactionId(TransactionId xid)
389 TransactionState s = CurrentTransactionState;
394 return TransactionIdEquals(xid, s->transactionIdData);
398 /* --------------------------------
399 * CommandIdIsCurrentCommandId
400 * --------------------------------
403 CommandIdIsCurrentCommandId(CommandId cid)
405 TransactionState s = CurrentTransactionState;
410 return (cid == s->commandId) ? true : false;
414 /* --------------------------------
415 * CommandCounterIncrement
416 * --------------------------------
419 CommandCounterIncrement(void)
421 TransactionState s = CurrentTransactionState;
424 if (s->commandId == FirstCommandId) /* check for overflow */
425 elog(ERROR, "You may only have 2^32-1 commands per transaction");
427 /* Propagate new command ID into query snapshots, if set */
429 QuerySnapshot->curcid = s->commandId;
430 if (SerializableSnapshot)
431 SerializableSnapshot->curcid = s->commandId;
434 * make cache changes visible to me. AtCommit_LocalCache() instead of
435 * AtCommit_Cache() is called here.
437 AtCommit_LocalCache();
442 /* ----------------------------------------------------------------
443 * StartTransaction stuff
444 * ----------------------------------------------------------------
447 /* --------------------------------
449 * --------------------------------
454 AcceptInvalidationMessages();
457 /* --------------------------------
459 * --------------------------------
465 * at present, it is unknown to me what belongs here -cim 3/18/90
467 * There isn't anything to do at the start of a xact for locks. -mer
472 /* --------------------------------
474 * --------------------------------
480 * We shouldn't have any transaction contexts already.
482 Assert(TopTransactionContext == NULL);
483 Assert(TransactionCommandContext == NULL);
486 * Create a toplevel context for the transaction.
488 TopTransactionContext =
489 AllocSetContextCreate(TopMemoryContext,
490 "TopTransactionContext",
491 ALLOCSET_DEFAULT_MINSIZE,
492 ALLOCSET_DEFAULT_INITSIZE,
493 ALLOCSET_DEFAULT_MAXSIZE);
496 * Create a statement-level context and make it active.
498 TransactionCommandContext =
499 AllocSetContextCreate(TopTransactionContext,
500 "TransactionCommandContext",
501 ALLOCSET_DEFAULT_MINSIZE,
502 ALLOCSET_DEFAULT_INITSIZE,
503 ALLOCSET_DEFAULT_MAXSIZE);
504 MemoryContextSwitchTo(TransactionCommandContext);
508 /* ----------------------------------------------------------------
509 * CommitTransaction stuff
510 * ----------------------------------------------------------------
513 /* --------------------------------
514 * RecordTransactionCommit
516 * Note: the two calls to BufferManagerFlush() exist to ensure
517 * that data pages are written before log pages. These
518 * explicit calls should be replaced by a more efficient
519 * ordered page write scheme in the buffer manager
521 * --------------------------------
524 RecordTransactionCommit(void)
529 leak = BufferPoolCheckLeak();
531 xid = GetCurrentTransactionId();
534 * We only need to log the commit in xlog and clog if the transaction made
535 * any transaction-controlled XLOG entries. (Otherwise, its XID appears
536 * nowhere in permanent storage, so no one will ever care if it
537 * committed.) However, we must flush XLOG to disk if we made any XLOG
538 * entries, whether in or out of transaction control. For example, if we
539 * reported a nextval() result to the client, this ensures that any XLOG
540 * record generated by nextval will hit the disk before we report the
541 * transaction committed.
543 if (MyXactMadeXLogEntry)
549 START_CRIT_SECTION();
551 if (MyLastRecPtr.xrecoff != 0)
553 /* Need to emit a commit record */
555 xl_xact_commit xlrec;
557 xlrec.xtime = time(NULL);
558 rdata.buffer = InvalidBuffer;
559 rdata.data = (char *) (&xlrec);
560 rdata.len = SizeOfXactCommit;
564 * XXX SHOULD SAVE ARRAY OF RELFILENODE-s TO DROP
566 recptr = XLogInsert(RM_XACT_ID, XLOG_XACT_COMMIT, &rdata);
570 /* Just flush through last record written by me */
571 recptr = ProcLastRecEnd;
575 * Sleep before flush! So we can flush more than one commit
576 * records per single fsync. (The idea is some other backend may
577 * do the XLogFlush while we're sleeping. This needs work still,
578 * because on most Unixen, the minimum select() delay is 10msec or
579 * more, which is way too long.)
581 * We do not sleep if enableFsync is not turned on, nor if there are
582 * fewer than CommitSiblings other backends with active
585 if (CommitDelay > 0 && enableFsync &&
586 CountActiveBackends() >= CommitSiblings)
588 struct timeval delay;
591 delay.tv_usec = CommitDelay;
592 (void) select(0, NULL, NULL, NULL, &delay);
597 /* Mark the transaction committed in clog, if needed */
598 if (MyLastRecPtr.xrecoff != 0)
599 TransactionIdCommit(xid);
604 /* Break the chain of back-links in the XLOG records I output */
605 MyLastRecPtr.xrecoff = 0;
606 MyXactMadeXLogEntry = false;
608 /* Show myself as out of the transaction in PROC array */
609 MyProc->logRec.xrecoff = 0;
612 ResetBufferPool(true);
616 /* --------------------------------
618 * --------------------------------
624 * Make catalog changes visible to all backends.
626 AtEOXactInvalidationMessages(true);
629 /* --------------------------------
630 * AtCommit_LocalCache
631 * --------------------------------
634 AtCommit_LocalCache(void)
637 * Make catalog changes visible to me for the next command.
639 CommandEndInvalidationMessages(true);
642 /* --------------------------------
644 * --------------------------------
650 * XXX What if ProcReleaseLocks fails? (race condition?)
652 * Then you're up a creek! -mer 5/24/92
654 ProcReleaseLocks(true);
657 /* --------------------------------
659 * --------------------------------
662 AtCommit_Memory(void)
665 * Now that we're "out" of a transaction, have the system allocate
666 * things in the top memory context instead of per-transaction
669 MemoryContextSwitchTo(TopMemoryContext);
672 * Release all transaction-local memory.
674 Assert(TopTransactionContext != NULL);
675 MemoryContextDelete(TopTransactionContext);
676 TopTransactionContext = NULL;
677 TransactionCommandContext = NULL;
680 /* ----------------------------------------------------------------
681 * AbortTransaction stuff
682 * ----------------------------------------------------------------
685 /* --------------------------------
686 * RecordTransactionAbort
687 * --------------------------------
690 RecordTransactionAbort(void)
692 TransactionId xid = GetCurrentTransactionId();
695 * We only need to log the abort in xlog and clog if the transaction made
696 * any transaction-controlled XLOG entries. (Otherwise, its XID appears
697 * nowhere in permanent storage, so no one will ever care if it
698 * committed.) We do not flush XLOG to disk in any case, since the
699 * default assumption after a crash would be that we aborted, anyway.
701 * Extra check here is to catch case that we aborted partway through
702 * RecordTransactionCommit ...
704 if (MyLastRecPtr.xrecoff != 0 && !TransactionIdDidCommit(xid))
710 xlrec.xtime = time(NULL);
711 rdata.buffer = InvalidBuffer;
712 rdata.data = (char *) (&xlrec);
713 rdata.len = SizeOfXactAbort;
716 START_CRIT_SECTION();
719 * SHOULD SAVE ARRAY OF RELFILENODE-s TO DROP
721 recptr = XLogInsert(RM_XACT_ID, XLOG_XACT_ABORT, &rdata);
723 /* Mark the transaction aborted in clog */
724 TransactionIdAbort(xid);
729 /* Break the chain of back-links in the XLOG records I output */
730 MyLastRecPtr.xrecoff = 0;
731 MyXactMadeXLogEntry = false;
733 /* Show myself as out of the transaction in PROC array */
734 MyProc->logRec.xrecoff = 0;
737 * Tell bufmgr and smgr to release resources.
739 ResetBufferPool(false); /* false -> is abort */
742 /* --------------------------------
744 * --------------------------------
749 RelationCacheAbort();
750 AtEOXactInvalidationMessages(false);
753 /* --------------------------------
755 * --------------------------------
761 * XXX What if ProcReleaseLocks() fails? (race condition?)
763 * Then you're up a creek without a paddle! -mer
765 ProcReleaseLocks(false);
769 /* --------------------------------
771 * --------------------------------
777 * Make sure we are in a valid context (not a child of
778 * TransactionCommandContext...). Note that it is possible for this
779 * code to be called when we aren't in a transaction at all; go
780 * directly to TopMemoryContext in that case.
782 if (TransactionCommandContext != NULL)
784 MemoryContextSwitchTo(TransactionCommandContext);
787 * We do not want to destroy transaction contexts yet, but it
788 * should be OK to delete any command-local memory.
790 MemoryContextResetAndDeleteChildren(TransactionCommandContext);
793 MemoryContextSwitchTo(TopMemoryContext);
797 /* ----------------------------------------------------------------
798 * CleanupTransaction stuff
799 * ----------------------------------------------------------------
802 /* --------------------------------
804 * --------------------------------
807 AtCleanup_Memory(void)
810 * Now that we're "out" of a transaction, have the system allocate
811 * things in the top memory context instead of per-transaction
814 MemoryContextSwitchTo(TopMemoryContext);
817 * Release all transaction-local memory.
819 if (TopTransactionContext != NULL)
820 MemoryContextDelete(TopTransactionContext);
821 TopTransactionContext = NULL;
822 TransactionCommandContext = NULL;
826 /* ----------------------------------------------------------------
828 * ----------------------------------------------------------------
831 /* --------------------------------
834 * --------------------------------
837 StartTransaction(void)
839 TransactionState s = CurrentTransactionState;
842 XactIsoLevel = DefaultXactIsoLevel;
845 * Check the current transaction state. If the transaction system is
846 * switched off, or if we're already in a transaction, do nothing.
847 * We're already in a transaction when the monitor sends a null
848 * command to the backend to flush the comm channel. This is a hacky
849 * fix to a communications problem, and we keep having to deal with it
850 * here. We should fix the comm channel code. mao 080891
852 if (s->state == TRANS_INPROGRESS)
856 * set the current transaction state information appropriately during
859 s->state = TRANS_START;
861 SetReindexProcessing(false);
864 * generate a new transaction id
866 s->transactionIdData = GetNewTransactionId();
868 XactLockTableInsert(s->transactionIdData);
871 * initialize current transaction state fields
873 s->commandId = FirstCommandId;
874 s->startTime = GetCurrentAbsoluteTimeUsec(&(s->startTimeUsec));
877 * initialize the various transaction subsystems
884 * Tell the trigger manager to we're starting a transaction
886 DeferredTriggerBeginXact();
889 * done with start processing, set current transaction state to "in
892 s->state = TRANS_INPROGRESS;
898 * Tell me if we are currently in progress
902 CurrentXactInProgress(void)
904 return CurrentTransactionState->state == TRANS_INPROGRESS;
908 /* --------------------------------
911 * --------------------------------
914 CommitTransaction(void)
916 TransactionState s = CurrentTransactionState;
919 * check the current transaction state
921 if (s->state != TRANS_INPROGRESS)
922 elog(WARNING, "CommitTransaction and not in in-progress state");
925 * Tell the trigger manager that this transaction is about to be
926 * committed. He'll invoke all trigger deferred until XACT before we
927 * really start on committing the transaction.
929 DeferredTriggerEndXact();
931 /* Prevent cancel/die interrupt while cleaning up */
935 * set the current transaction state information appropriately during
936 * the abort processing
938 s->state = TRANS_COMMIT;
941 * do commit processing
944 /* handle commit for large objects [ PA, 7/17/98 ] */
947 /* NOTIFY commit must also come before lower-level cleanup */
953 /* Here is where we really truly commit. */
954 RecordTransactionCommit();
957 * Let others know about no transaction in progress by me. Note that
958 * this must be done _before_ releasing locks we hold and _after_
959 * RecordTransactionCommit.
961 * LWLockAcquire(SInvalLock) is required: UPDATE with xid 0 is blocked by
962 * xid 1' UPDATE, xid 1 is doing commit while xid 2 gets snapshot - if
963 * xid 2' GetSnapshotData sees xid 1 as running then it must see xid 0
964 * as running as well or it will see two tuple versions - one deleted
965 * by xid 1 and one inserted by xid 0. See notes in GetSnapshotData.
967 if (MyProc != (PROC *) NULL)
969 /* Lock SInvalLock because that's what GetSnapshotData uses. */
970 LWLockAcquire(SInvalLock, LW_EXCLUSIVE);
971 MyProc->xid = InvalidTransactionId;
972 MyProc->xmin = InvalidTransactionId;
973 LWLockRelease(SInvalLock);
977 * This is all post-commit cleanup. Note that if an error is raised
978 * here, it's too late to abort the transaction. This should be just
979 * noncritical resource releasing.
982 RelationPurgeLocalRelation(true);
983 smgrDoPendingDeletes(true);
991 AtEOXact_Namespace(true);
994 AtEOXact_CatCache(true);
998 SharedBufferChanged = false; /* safest place to do it */
1000 /* Count transaction commit in statistics collector */
1001 pgstat_count_xact_commit();
1004 * done with commit processing, set current transaction state back to
1007 s->state = TRANS_DEFAULT;
1009 RESUME_INTERRUPTS();
1012 /* --------------------------------
1015 * --------------------------------
1018 AbortTransaction(void)
1020 TransactionState s = CurrentTransactionState;
1022 /* Prevent cancel/die interrupt while cleaning up */
1026 * Release any LW locks we might be holding as quickly as possible.
1027 * (Regular locks, however, must be held till we finish aborting.)
1028 * Releasing LW locks is critical since we might try to grab them
1029 * again while cleaning up!
1033 /* Clean up buffer I/O and buffer context locks, too */
1038 * Also clean up any open wait for lock, since the lock manager will
1039 * choke if we try to wait for another lock before doing this.
1044 * check the current transaction state
1046 if (s->state != TRANS_INPROGRESS)
1047 elog(WARNING, "AbortTransaction and not in in-progress state");
1050 * set the current transaction state information appropriately during
1051 * the abort processing
1053 s->state = TRANS_ABORT;
1056 * Reset user id which might have been changed transiently
1058 SetUserId(GetSessionUserId());
1061 * do abort processing
1063 DeferredTriggerAbortXact();
1064 lo_commit(false); /* 'false' means it's abort */
1069 /* Advertise the fact that we aborted in pg_clog. */
1070 RecordTransactionAbort();
1073 * Let others know about no transaction in progress by me. Note that
1074 * this must be done _before_ releasing locks we hold and _after_
1075 * RecordTransactionAbort.
1077 if (MyProc != (PROC *) NULL)
1079 /* Lock SInvalLock because that's what GetSnapshotData uses. */
1080 LWLockAcquire(SInvalLock, LW_EXCLUSIVE);
1081 MyProc->xid = InvalidTransactionId;
1082 MyProc->xmin = InvalidTransactionId;
1083 LWLockRelease(SInvalLock);
1086 RelationPurgeLocalRelation(false);
1087 smgrDoPendingDeletes(false);
1089 AtEOXact_GUC(false);
1095 AtEOXact_Namespace(false);
1097 AtEOXact_CatCache(false);
1102 SharedBufferChanged = false; /* safest place to do it */
1104 /* Count transaction abort in statistics collector */
1105 pgstat_count_xact_rollback();
1108 * State remains TRANS_ABORT until CleanupTransaction().
1110 RESUME_INTERRUPTS();
1113 /* --------------------------------
1114 * CleanupTransaction
1116 * --------------------------------
1119 CleanupTransaction(void)
1121 TransactionState s = CurrentTransactionState;
1124 * State should still be TRANS_ABORT from AbortTransaction().
1126 if (s->state != TRANS_ABORT)
1127 elog(FATAL, "CleanupTransaction and not in abort state");
1130 * do abort cleanup processing
1135 * done with abort processing, set current transaction state back to
1138 s->state = TRANS_DEFAULT;
1141 /* --------------------------------
1142 * StartTransactionCommand
1143 * --------------------------------
1146 StartTransactionCommand(void)
1148 TransactionState s = CurrentTransactionState;
1150 switch (s->blockState)
1153 * if we aren't in a transaction block, we just do our usual
1154 * start transaction.
1156 case TBLOCK_DEFAULT:
1161 * We should never experience this -- if we do it means the
1162 * BEGIN state was not changed in the previous
1163 * CommitTransactionCommand(). If we get it, we print a
1164 * warning and change to the in-progress state.
1167 elog(WARNING, "StartTransactionCommand: unexpected TBLOCK_BEGIN");
1168 s->blockState = TBLOCK_INPROGRESS;
1172 * This is the case when are somewhere in a transaction block
1173 * and about to start a new command. For now we do nothing
1174 * but someday we may do command-local resource
1177 case TBLOCK_INPROGRESS:
1181 * As with BEGIN, we should never experience this if we do it
1182 * means the END state was not changed in the previous
1183 * CommitTransactionCommand(). If we get it, we print a
1184 * warning, commit the transaction, start a new transaction
1185 * and change to the default state.
1188 elog(WARNING, "StartTransactionCommand: unexpected TBLOCK_END");
1189 s->blockState = TBLOCK_DEFAULT;
1190 CommitTransaction();
1195 * Here we are in the middle of a transaction block but one of
1196 * the commands caused an abort so we do nothing but remain in
1197 * the abort state. Eventually we will get to the "END
1198 * TRANSACTION" which will set things straight.
1204 * This means we somehow aborted and the last call to
1205 * CommitTransactionCommand() didn't clear the state so we
1206 * remain in the ENDABORT state and maybe next time we get to
1207 * CommitTransactionCommand() the state will get reset to
1210 case TBLOCK_ENDABORT:
1211 elog(WARNING, "StartTransactionCommand: unexpected TBLOCK_ENDABORT");
1216 * We must switch to TransactionCommandContext before returning. This
1217 * is already done if we called StartTransaction, otherwise not.
1219 Assert(TransactionCommandContext != NULL);
1220 MemoryContextSwitchTo(TransactionCommandContext);
1223 /* --------------------------------
1224 * CommitTransactionCommand
1225 * --------------------------------
1228 CommitTransactionCommand(void)
1230 TransactionState s = CurrentTransactionState;
1232 switch (s->blockState)
1235 * if we aren't in a transaction block, we just do our usual
1236 * transaction commit
1238 case TBLOCK_DEFAULT:
1239 CommitTransaction();
1243 * This is the case right after we get a "BEGIN TRANSACTION"
1244 * command, but the user hasn't done anything else yet, so we
1245 * change to the "transaction block in progress" state and
1249 s->blockState = TBLOCK_INPROGRESS;
1253 * This is the case when we have finished executing a command
1254 * someplace within a transaction block. We increment the
1255 * command counter and return. Someday we may free resources
1256 * local to the command.
1258 * That someday is today, at least for memory allocated in
1259 * TransactionCommandContext. - vadim 03/25/97
1261 case TBLOCK_INPROGRESS:
1262 CommandCounterIncrement();
1263 MemoryContextResetAndDeleteChildren(TransactionCommandContext);
1267 * This is the case when we just got the "END TRANSACTION"
1268 * statement, so we commit the transaction and go back to the
1272 CommitTransaction();
1273 s->blockState = TBLOCK_DEFAULT;
1277 * Here we are in the middle of a transaction block but one of
1278 * the commands caused an abort so we do nothing but remain in
1279 * the abort state. Eventually we will get to the "END
1280 * TRANSACTION" which will set things straight.
1286 * Here we were in an aborted transaction block which just
1287 * processed the "END TRANSACTION" command from the user, so
1288 * clean up and return to the default state.
1290 case TBLOCK_ENDABORT:
1291 CleanupTransaction();
1292 s->blockState = TBLOCK_DEFAULT;
1297 /* --------------------------------
1298 * AbortCurrentTransaction
1299 * --------------------------------
1302 AbortCurrentTransaction(void)
1304 TransactionState s = CurrentTransactionState;
1306 switch (s->blockState)
1309 * if we aren't in a transaction block, we just do the basic
1310 * abort & cleanup transaction.
1312 case TBLOCK_DEFAULT:
1314 CleanupTransaction();
1318 * If we are in the TBLOCK_BEGIN it means something screwed up
1319 * right after reading "BEGIN TRANSACTION" so we enter the
1320 * abort state. Eventually an "END TRANSACTION" will fix
1324 s->blockState = TBLOCK_ABORT;
1326 /* CleanupTransaction happens when we exit TBLOCK_ABORT */
1330 * This is the case when are somewhere in a transaction block
1331 * which aborted so we abort the transaction and set the ABORT
1332 * state. Eventually an "END TRANSACTION" will fix things and
1333 * restore us to a normal state.
1335 case TBLOCK_INPROGRESS:
1336 s->blockState = TBLOCK_ABORT;
1338 /* CleanupTransaction happens when we exit TBLOCK_ABORT */
1342 * Here, the system was fouled up just after the user wanted
1343 * to end the transaction block so we abort the transaction
1344 * and put us back into the default state.
1347 s->blockState = TBLOCK_DEFAULT;
1349 CleanupTransaction();
1353 * Here, we are already in an aborted transaction state and
1354 * are waiting for an "END TRANSACTION" to come along and lo
1355 * and behold, we abort again! So we just remain in the abort
1362 * Here we were in an aborted transaction block which just
1363 * processed the "END TRANSACTION" command but somehow aborted
1364 * again.. since we must have done the abort processing, we
1365 * clean up and return to the default state.
1367 case TBLOCK_ENDABORT:
1368 CleanupTransaction();
1369 s->blockState = TBLOCK_DEFAULT;
1374 /* ----------------------------------------------------------------
1375 * transaction block support
1376 * ----------------------------------------------------------------
1378 /* --------------------------------
1379 * BeginTransactionBlock
1380 * --------------------------------
1383 BeginTransactionBlock(void)
1385 TransactionState s = CurrentTransactionState;
1388 * check the current transaction state
1390 if (s->blockState != TBLOCK_DEFAULT)
1391 elog(WARNING, "BEGIN: already a transaction in progress");
1394 * set the current transaction block state information appropriately
1395 * during begin processing
1397 s->blockState = TBLOCK_BEGIN;
1400 * do begin processing
1404 * done with begin processing, set block state to inprogress
1406 s->blockState = TBLOCK_INPROGRESS;
1409 /* --------------------------------
1410 * EndTransactionBlock
1411 * --------------------------------
1414 EndTransactionBlock(void)
1416 TransactionState s = CurrentTransactionState;
1419 * check the current transaction state
1421 if (s->blockState == TBLOCK_INPROGRESS)
1424 * here we are in a transaction block which should commit when we
1425 * get to the upcoming CommitTransactionCommand() so we set the
1426 * state to "END". CommitTransactionCommand() will recognize this
1427 * and commit the transaction and return us to the default state
1429 s->blockState = TBLOCK_END;
1433 if (s->blockState == TBLOCK_ABORT)
1436 * here, we are in a transaction block which aborted and since the
1437 * AbortTransaction() was already done, we do whatever is needed
1438 * and change to the special "END ABORT" state. The upcoming
1439 * CommitTransactionCommand() will recognise this and then put us
1440 * back in the default state.
1442 s->blockState = TBLOCK_ENDABORT;
1447 * here, the user issued COMMIT when not inside a transaction. Issue a
1448 * WARNING and go to abort state. The upcoming call to
1449 * CommitTransactionCommand() will then put us back into the default
1452 elog(WARNING, "COMMIT: no transaction in progress");
1454 s->blockState = TBLOCK_ENDABORT;
1457 /* --------------------------------
1458 * AbortTransactionBlock
1459 * --------------------------------
1463 AbortTransactionBlock(void)
1465 TransactionState s = CurrentTransactionState;
1468 * check the current transaction state
1470 if (s->blockState == TBLOCK_INPROGRESS)
1473 * here we were inside a transaction block something screwed up
1474 * inside the system so we enter the abort state, do the abort
1475 * processing and then return. We remain in the abort state until
1476 * we see an END TRANSACTION command.
1478 s->blockState = TBLOCK_ABORT;
1484 * here, the user issued ABORT when not inside a transaction. Issue a
1485 * WARNING and go to abort state. The upcoming call to
1486 * CommitTransactionCommand() will then put us back into the default
1489 elog(WARNING, "ROLLBACK: no transaction in progress");
1491 s->blockState = TBLOCK_ENDABORT;
1495 /* --------------------------------
1496 * UserAbortTransactionBlock
1497 * --------------------------------
1500 UserAbortTransactionBlock(void)
1502 TransactionState s = CurrentTransactionState;
1505 * if the transaction has already been automatically aborted with an
1506 * error, and the user subsequently types 'abort', allow it. (the
1507 * behavior is the same as if they had typed 'end'.)
1509 if (s->blockState == TBLOCK_ABORT)
1511 s->blockState = TBLOCK_ENDABORT;
1515 if (s->blockState == TBLOCK_INPROGRESS)
1518 * here we were inside a transaction block and we got an abort
1519 * command from the user, so we move to the abort state, do the
1520 * abort processing and then change to the ENDABORT state so we
1521 * will end up in the default state after the upcoming
1522 * CommitTransactionCommand().
1524 s->blockState = TBLOCK_ABORT;
1526 s->blockState = TBLOCK_ENDABORT;
1531 * here, the user issued ABORT when not inside a transaction. Issue a
1532 * WARNING and go to abort state. The upcoming call to
1533 * CommitTransactionCommand() will then put us back into the default
1536 elog(WARNING, "ROLLBACK: no transaction in progress");
1538 s->blockState = TBLOCK_ENDABORT;
1541 /* --------------------------------
1542 * AbortOutOfAnyTransaction
1544 * This routine is provided for error recovery purposes. It aborts any
1545 * active transaction or transaction block, leaving the system in a known
1547 * --------------------------------
1550 AbortOutOfAnyTransaction(void)
1552 TransactionState s = CurrentTransactionState;
1555 * Get out of any low-level transaction
1560 case TRANS_INPROGRESS:
1562 /* In a transaction, so clean up */
1564 CleanupTransaction();
1567 /* AbortTransaction already done, still need Cleanup */
1568 CleanupTransaction();
1571 /* Not in a transaction, do nothing */
1576 * Now reset the high-level state
1578 s->blockState = TBLOCK_DEFAULT;
1582 IsTransactionBlock(void)
1584 TransactionState s = CurrentTransactionState;
1586 if (s->blockState == TBLOCK_INPROGRESS
1587 || s->blockState == TBLOCK_ABORT
1588 || s->blockState == TBLOCK_ENDABORT)
1595 xact_redo(XLogRecPtr lsn, XLogRecord *record)
1597 uint8 info = record->xl_info & ~XLR_INFO_MASK;
1599 if (info == XLOG_XACT_COMMIT)
1601 TransactionIdCommit(record->xl_xid);
1602 /* SHOULD REMOVE FILES OF ALL DROPPED RELATIONS */
1604 else if (info == XLOG_XACT_ABORT)
1606 TransactionIdAbort(record->xl_xid);
1607 /* SHOULD REMOVE FILES OF ALL FAILED-TO-BE-CREATED RELATIONS */
1610 elog(PANIC, "xact_redo: unknown op code %u", info);
1614 xact_undo(XLogRecPtr lsn, XLogRecord *record)
1616 uint8 info = record->xl_info & ~XLR_INFO_MASK;
1618 if (info == XLOG_XACT_COMMIT) /* shouldn't be called by XLOG */
1619 elog(PANIC, "xact_undo: can't undo committed xaction");
1620 else if (info != XLOG_XACT_ABORT)
1621 elog(PANIC, "xact_redo: unknown op code %u", info);
1625 xact_desc(char *buf, uint8 xl_info, char *rec)
1627 uint8 info = xl_info & ~XLR_INFO_MASK;
1629 if (info == XLOG_XACT_COMMIT)
1631 xl_xact_commit *xlrec = (xl_xact_commit *) rec;
1632 struct tm *tm = localtime(&xlrec->xtime);
1634 sprintf(buf + strlen(buf), "commit: %04u-%02u-%02u %02u:%02u:%02u",
1635 tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday,
1636 tm->tm_hour, tm->tm_min, tm->tm_sec);
1638 else if (info == XLOG_XACT_ABORT)
1640 xl_xact_abort *xlrec = (xl_xact_abort *) rec;
1641 struct tm *tm = localtime(&xlrec->xtime);
1643 sprintf(buf + strlen(buf), "abort: %04u-%02u-%02u %02u:%02u:%02u",
1644 tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday,
1645 tm->tm_hour, tm->tm_min, tm->tm_sec);
1648 strcat(buf, "UNKNOWN");
1652 XactPushRollback(void (*func) (void *), void *data)
1655 if (_RollbackFunc != NULL)
1656 elog(PANIC, "XactPushRollback: already installed");
1659 _RollbackFunc = func;
1660 _RollbackData = data;
1664 XactPopRollback(void)
1666 _RollbackFunc = NULL;