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.108 2001/07/16 22:43:33 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"
157 #include <sys/time.h>
159 #include "access/gistscan.h"
160 #include "access/hash.h"
161 #include "access/nbtree.h"
162 #include "access/rtree.h"
163 #include "access/xact.h"
164 #include "catalog/heap.h"
165 #include "catalog/index.h"
166 #include "commands/async.h"
167 #include "commands/sequence.h"
168 #include "commands/trigger.h"
169 #include "executor/spi.h"
170 #include "libpq/be-fsstubs.h"
171 #include "miscadmin.h"
172 #include "storage/proc.h"
173 #include "storage/sinval.h"
174 #include "storage/smgr.h"
175 #include "utils/inval.h"
176 #include "utils/memutils.h"
177 #include "utils/portal.h"
178 #include "utils/catcache.h"
179 #include "utils/relcache.h"
180 #include "utils/temprel.h"
184 extern bool SharedBufferChanged;
186 static void AbortTransaction(void);
187 static void AtAbort_Cache(void);
188 static void AtAbort_Locks(void);
189 static void AtAbort_Memory(void);
190 static void AtCleanup_Memory(void);
191 static void AtCommit_Cache(void);
192 static void AtCommit_LocalCache(void);
193 static void AtCommit_Locks(void);
194 static void AtCommit_Memory(void);
195 static void AtStart_Cache(void);
196 static void AtStart_Locks(void);
197 static void AtStart_Memory(void);
198 static void CleanupTransaction(void);
199 static void CommitTransaction(void);
200 static void RecordTransactionAbort(void);
201 static void StartTransaction(void);
204 * global variables holding the current transaction state.
207 static TransactionStateData CurrentTransactionStateData = {
208 0, /* transaction id */
209 FirstCommandId, /* command id */
210 0, /* scan command id */
211 0x0, /* start time */
212 TRANS_DEFAULT, /* transaction state */
213 TBLOCK_DEFAULT /* transaction block state */
216 TransactionState CurrentTransactionState = &CurrentTransactionStateData;
219 * User-tweakable parameters
221 int DefaultXactIsoLevel = XACT_READ_COMMITTED;
224 int CommitDelay = 0; /* precommit delay in microseconds */
225 int CommitSiblings = 5; /* number of concurrent xacts needed to
228 static void (*_RollbackFunc) (void *) = NULL;
229 static void *_RollbackData = NULL;
232 * info returned when the system is disabled
234 * Apparently a lot of this code is inherited from other prototype systems.
236 * For DisabledStartTime, use a symbolic value to make the relationships clearer.
237 * The old value of 1073741823 corresponds to a date in y2004, which is coming closer
238 * every day. It appears that if we return a value guaranteed larger than
239 * any real time associated with a transaction then comparisons in other
240 * modules will still be correct. Let's use BIG_ABSTIME for this. tgl 2/14/97
243 static CommandId DisabledCommandId = (CommandId) -1;
245 static AbsoluteTime DisabledStartTime = (AbsoluteTime) BIG_ABSTIME;
248 * catalog creation transaction bootstrapping flag.
249 * This should be eliminated and added to the transaction
250 * state stuff. -cim 3/19/90
253 bool AMI_OVERRIDE = false;
255 /* ----------------------------------------------------------------
256 * transaction state accessors
257 * ----------------------------------------------------------------
260 /* --------------------------------
261 * TranactionFlushEnabled()
262 * SetTransactionFlushEnabled()
264 * These are used to test and set the "TransactionFlushState"
265 * varable. If this variable is true (the default), then
266 * the system will flush all dirty buffers to disk at the end
267 * of each transaction. If false then we are assuming the
268 * buffer pool resides in stable main memory, in which case we
269 * only do writes as necessary.
270 * --------------------------------
272 static int TransactionFlushState = 1;
275 TransactionFlushEnabled(void)
277 return TransactionFlushState;
282 SetTransactionFlushEnabled(bool state)
284 TransactionFlushState = (state == true);
288 /* --------------------------------
291 * This returns true if we are currently running a query
292 * within an executing transaction.
293 * --------------------------------
296 IsTransactionState(void)
298 TransactionState s = CurrentTransactionState;
306 case TRANS_INPROGRESS:
317 * Shouldn't get here, but lint is not happy with this...
324 /* --------------------------------
325 * IsAbortedTransactionBlockState
327 * This returns true if we are currently running a query
328 * within an aborted transaction block.
329 * --------------------------------
332 IsAbortedTransactionBlockState(void)
334 TransactionState s = CurrentTransactionState;
336 if (s->blockState == TBLOCK_ABORT)
342 /* --------------------------------
343 * OverrideTransactionSystem
345 * This is used to temporarily disable the transaction
346 * processing system in order to do initialization of
347 * the transaction system data structures and relations
349 * --------------------------------
351 static int SavedTransactionState;
354 OverrideTransactionSystem(bool flag)
356 TransactionState s = CurrentTransactionState;
360 if (s->state == TRANS_DISABLED)
363 SavedTransactionState = s->state;
364 s->state = TRANS_DISABLED;
368 if (s->state != TRANS_DISABLED)
371 s->state = SavedTransactionState;
375 /* --------------------------------
376 * GetCurrentTransactionId
378 * This returns the id of the current transaction, or
379 * the id of the "disabled" transaction.
380 * --------------------------------
383 GetCurrentTransactionId(void)
385 TransactionState s = CurrentTransactionState;
388 * if the transaction system is disabled, we return the special
389 * "disabled" transaction id.
391 if (s->state == TRANS_DISABLED)
392 return DisabledTransactionId;
395 * otherwise return the current transaction id.
397 return s->transactionIdData;
401 /* --------------------------------
402 * GetCurrentCommandId
403 * --------------------------------
406 GetCurrentCommandId(void)
408 TransactionState s = CurrentTransactionState;
411 * if the transaction system is disabled, we return the special
412 * "disabled" command id.
414 if (s->state == TRANS_DISABLED)
415 return DisabledCommandId;
421 GetScanCommandId(void)
423 TransactionState s = CurrentTransactionState;
426 * if the transaction system is disabled, we return the special
427 * "disabled" command id.
429 if (s->state == TRANS_DISABLED)
430 return DisabledCommandId;
432 return s->scanCommandId;
436 /* --------------------------------
437 * GetCurrentTransactionStartTime
438 * --------------------------------
441 GetCurrentTransactionStartTime(void)
443 TransactionState s = CurrentTransactionState;
446 * if the transaction system is disabled, we return the special
447 * "disabled" starting time.
449 if (s->state == TRANS_DISABLED)
450 return DisabledStartTime;
456 /* --------------------------------
457 * TransactionIdIsCurrentTransactionId
458 * --------------------------------
461 TransactionIdIsCurrentTransactionId(TransactionId xid)
463 TransactionState s = CurrentTransactionState;
468 return TransactionIdEquals(xid, s->transactionIdData);
472 /* --------------------------------
473 * CommandIdIsCurrentCommandId
474 * --------------------------------
477 CommandIdIsCurrentCommandId(CommandId cid)
479 TransactionState s = CurrentTransactionState;
484 return (cid == s->commandId) ? true : false;
488 CommandIdGEScanCommandId(CommandId cid)
490 TransactionState s = CurrentTransactionState;
495 return (cid >= s->scanCommandId) ? true : false;
499 /* --------------------------------
500 * CommandCounterIncrement
501 * --------------------------------
504 CommandCounterIncrement(void)
506 CurrentTransactionStateData.commandId += 1;
507 if (CurrentTransactionStateData.commandId == FirstCommandId)
508 elog(ERROR, "You may only have 2^32-1 commands per transaction");
510 CurrentTransactionStateData.scanCommandId = CurrentTransactionStateData.commandId;
513 * make cache changes visible to me. AtCommit_LocalCache() instead of
514 * AtCommit_Cache() is called here.
516 AtCommit_LocalCache();
521 SetScanCommandId(CommandId savedId)
523 CurrentTransactionStateData.scanCommandId = savedId;
526 /* ----------------------------------------------------------------
527 * initialization stuff
528 * ----------------------------------------------------------------
531 InitializeTransactionSystem(void)
533 InitializeTransactionLog();
536 /* ----------------------------------------------------------------
537 * StartTransaction stuff
538 * ----------------------------------------------------------------
541 /* --------------------------------
543 * --------------------------------
548 AcceptInvalidationMessages();
551 /* --------------------------------
553 * --------------------------------
560 * at present, it is unknown to me what belongs here -cim 3/18/90
562 * There isn't anything to do at the start of a xact for locks. -mer
567 /* --------------------------------
569 * --------------------------------
576 * We shouldn't have any transaction contexts already.
578 Assert(TopTransactionContext == NULL);
579 Assert(TransactionCommandContext == NULL);
582 * Create a toplevel context for the transaction.
584 TopTransactionContext =
585 AllocSetContextCreate(TopMemoryContext,
586 "TopTransactionContext",
587 ALLOCSET_DEFAULT_MINSIZE,
588 ALLOCSET_DEFAULT_INITSIZE,
589 ALLOCSET_DEFAULT_MAXSIZE);
592 * Create a statement-level context and make it active.
594 TransactionCommandContext =
595 AllocSetContextCreate(TopTransactionContext,
596 "TransactionCommandContext",
597 ALLOCSET_DEFAULT_MINSIZE,
598 ALLOCSET_DEFAULT_INITSIZE,
599 ALLOCSET_DEFAULT_MAXSIZE);
600 MemoryContextSwitchTo(TransactionCommandContext);
604 /* ----------------------------------------------------------------
605 * CommitTransaction stuff
606 * ----------------------------------------------------------------
609 /* --------------------------------
610 * RecordTransactionCommit
612 * Note: the two calls to BufferManagerFlush() exist to ensure
613 * that data pages are written before log pages. These
614 * explicit calls should be replaced by a more efficient
615 * ordered page write scheme in the buffer manager
617 * --------------------------------
620 RecordTransactionCommit()
625 xid = GetCurrentTransactionId();
627 leak = BufferPoolCheckLeak();
629 if (MyLastRecPtr.xrecoff != 0)
632 xl_xact_commit xlrec;
637 xlrec.xtime = time(NULL);
638 rdata.buffer = InvalidBuffer;
639 rdata.data = (char *) (&xlrec);
640 rdata.len = SizeOfXactCommit;
643 START_CRIT_SECTION();
646 * SHOULD SAVE ARRAY OF RELFILENODE-s TO DROP
648 recptr = XLogInsert(RM_XACT_ID, XLOG_XACT_COMMIT, &rdata);
651 * Sleep before commit! So we can flush more than one commit
652 * records per single fsync. (The idea is some other backend may
653 * do the XLogFlush while we're sleeping. This needs work still,
654 * because on most Unixen, the minimum select() delay is 10msec or
655 * more, which is way too long.)
657 * We do not sleep if enableFsync is not turned on, nor if there are
658 * fewer than CommitSiblings other backends with active
661 if (CommitDelay > 0 && enableFsync &&
662 CountActiveBackends() >= CommitSiblings)
664 struct timeval delay;
667 delay.tv_usec = CommitDelay;
668 (void) select(0, NULL, NULL, NULL, &delay);
673 /* Break the chain of back-links in the XLOG records I output */
674 MyLastRecPtr.xrecoff = 0;
676 TransactionIdCommit(xid);
681 /* Show myself as out of the transaction in PROC array */
682 MyProc->logRec.xrecoff = 0;
685 ResetBufferPool(true);
689 /* --------------------------------
691 * --------------------------------
697 * Make catalog changes visible to all backends.
699 AtEOXactInvalidationMessages(true);
702 /* --------------------------------
703 * AtCommit_LocalCache
704 * --------------------------------
707 AtCommit_LocalCache(void)
710 * Make catalog changes visible to me for the next command.
712 CommandEndInvalidationMessages(true);
715 /* --------------------------------
717 * --------------------------------
723 * XXX What if ProcReleaseLocks fails? (race condition?)
725 * Then you're up a creek! -mer 5/24/92
727 ProcReleaseLocks(true);
730 /* --------------------------------
732 * --------------------------------
735 AtCommit_Memory(void)
738 * Now that we're "out" of a transaction, have the system allocate
739 * things in the top memory context instead of per-transaction
742 MemoryContextSwitchTo(TopMemoryContext);
745 * Release all transaction-local memory.
747 Assert(TopTransactionContext != NULL);
748 MemoryContextDelete(TopTransactionContext);
749 TopTransactionContext = NULL;
750 TransactionCommandContext = NULL;
753 /* ----------------------------------------------------------------
754 * AbortTransaction stuff
755 * ----------------------------------------------------------------
758 /* --------------------------------
759 * RecordTransactionAbort
760 * --------------------------------
763 RecordTransactionAbort(void)
765 TransactionId xid = GetCurrentTransactionId();
768 * Double check here is to catch case that we aborted partway through
769 * RecordTransactionCommit ...
771 if (MyLastRecPtr.xrecoff != 0 && !TransactionIdDidCommit(xid))
777 xlrec.xtime = time(NULL);
778 rdata.buffer = InvalidBuffer;
779 rdata.data = (char *) (&xlrec);
780 rdata.len = SizeOfXactAbort;
783 START_CRIT_SECTION();
785 recptr = XLogInsert(RM_XACT_ID, XLOG_XACT_ABORT, &rdata);
787 TransactionIdAbort(xid);
792 /* Break the chain of back-links in the XLOG records I output */
793 MyLastRecPtr.xrecoff = 0;
794 /* Show myself as out of the transaction in PROC array */
795 MyProc->logRec.xrecoff = 0;
798 * Tell bufmgr and smgr to release resources.
800 ResetBufferPool(false); /* false -> is abort */
803 /* --------------------------------
805 * --------------------------------
810 RelationCacheAbort();
811 AtEOXactInvalidationMessages(false);
814 /* --------------------------------
816 * --------------------------------
823 * XXX What if ProcReleaseLocks() fails? (race condition?)
825 * Then you're up a creek without a paddle! -mer
827 ProcReleaseLocks(false);
831 /* --------------------------------
833 * --------------------------------
840 * Make sure we are in a valid context (not a child of
841 * TransactionCommandContext...). Note that it is possible for this
842 * code to be called when we aren't in a transaction at all; go
843 * directly to TopMemoryContext in that case.
845 if (TransactionCommandContext != NULL)
847 MemoryContextSwitchTo(TransactionCommandContext);
850 * We do not want to destroy transaction contexts yet, but it
851 * should be OK to delete any command-local memory.
853 MemoryContextResetAndDeleteChildren(TransactionCommandContext);
856 MemoryContextSwitchTo(TopMemoryContext);
860 /* ----------------------------------------------------------------
861 * CleanupTransaction stuff
862 * ----------------------------------------------------------------
865 /* --------------------------------
867 * --------------------------------
870 AtCleanup_Memory(void)
874 * Now that we're "out" of a transaction, have the system allocate
875 * things in the top memory context instead of per-transaction
878 MemoryContextSwitchTo(TopMemoryContext);
881 * Release all transaction-local memory.
883 if (TopTransactionContext != NULL)
884 MemoryContextDelete(TopTransactionContext);
885 TopTransactionContext = NULL;
886 TransactionCommandContext = NULL;
890 /* ----------------------------------------------------------------
892 * ----------------------------------------------------------------
895 /* --------------------------------
898 * --------------------------------
901 StartTransaction(void)
903 TransactionState s = CurrentTransactionState;
906 XactIsoLevel = DefaultXactIsoLevel;
909 * Check the current transaction state. If the transaction system is
910 * switched off, or if we're already in a transaction, do nothing.
911 * We're already in a transaction when the monitor sends a null
912 * command to the backend to flush the comm channel. This is a hacky
913 * fix to a communications problem, and we keep having to deal with it
914 * here. We should fix the comm channel code. mao 080891
916 if (s->state == TRANS_DISABLED || s->state == TRANS_INPROGRESS)
920 * set the current transaction state information appropriately during
923 s->state = TRANS_START;
925 SetReindexProcessing(false);
928 * generate a new transaction id
930 GetNewTransactionId(&(s->transactionIdData));
932 XactLockTableInsert(s->transactionIdData);
935 * initialize current transaction state fields
937 s->commandId = FirstCommandId;
938 s->scanCommandId = FirstCommandId;
939 s->startTime = GetCurrentAbsoluteTime();
942 * initialize the various transaction subsystems
949 * Tell the trigger manager to we're starting a transaction
951 DeferredTriggerBeginXact();
954 * done with start processing, set current transaction state to "in
957 s->state = TRANS_INPROGRESS;
963 * Tell me if we are currently in progress
967 CurrentXactInProgress(void)
969 return CurrentTransactionState->state == TRANS_INPROGRESS;
974 /* --------------------------------
977 * --------------------------------
980 CommitTransaction(void)
982 TransactionState s = CurrentTransactionState;
985 * check the current transaction state
987 if (s->state == TRANS_DISABLED)
990 if (s->state != TRANS_INPROGRESS)
991 elog(NOTICE, "CommitTransaction and not in in-progress state ");
994 * Tell the trigger manager that this transaction is about to be
995 * committed. He'll invoke all trigger deferred until XACT before we
996 * really start on committing the transaction.
998 DeferredTriggerEndXact();
1000 /* Prevent cancel/die interrupt while cleaning up */
1004 * set the current transaction state information appropriately during
1005 * the abort processing
1007 s->state = TRANS_COMMIT;
1010 * do commit processing
1013 /* handle commit for large objects [ PA, 7/17/98 ] */
1016 /* NOTIFY commit must also come before lower-level cleanup */
1022 /* Here is where we really truly commit. */
1023 RecordTransactionCommit();
1026 * Let others know about no transaction in progress by me. Note that
1027 * this must be done _before_ releasing locks we hold and _after_
1028 * RecordTransactionCommit.
1030 * SpinAcquire(SInvalLock) is required: UPDATE with xid 0 is blocked
1031 * by xid 1' UPDATE, xid 1 is doing commit while xid 2 gets snapshot -
1032 * if xid 2' GetSnapshotData sees xid 1 as running then it must see
1033 * xid 0 as running as well or it will see two tuple versions - one
1034 * deleted by xid 1 and one inserted by xid 0. See notes in
1037 if (MyProc != (PROC *) NULL)
1039 /* Lock SInvalLock because that's what GetSnapshotData uses. */
1040 SpinAcquire(SInvalLock);
1041 MyProc->xid = InvalidTransactionId;
1042 MyProc->xmin = InvalidTransactionId;
1043 SpinRelease(SInvalLock);
1047 * This is all post-commit cleanup. Note that if an error is raised
1048 * here, it's too late to abort the transaction. This should be just
1049 * noncritical resource releasing.
1052 RelationPurgeLocalRelation(true);
1053 AtEOXact_temp_relations(true);
1054 smgrDoPendingDeletes(true);
1063 AtEOXact_CatCache(true);
1067 SharedBufferChanged = false;/* safest place to do it */
1069 /* Count transaction commit in statistics collector */
1070 pgstat_count_xact_commit();
1073 * done with commit processing, set current transaction state back to
1076 s->state = TRANS_DEFAULT;
1078 RESUME_INTERRUPTS();
1081 /* --------------------------------
1084 * --------------------------------
1087 AbortTransaction(void)
1089 TransactionState s = CurrentTransactionState;
1091 /* Prevent cancel/die interrupt while cleaning up */
1095 * Release any spinlocks or buffer context locks we might be holding
1096 * as quickly as possible. (Real locks, however, must be held till we
1097 * finish aborting.) Releasing spinlocks is critical since we might
1098 * try to grab them again while cleaning up!
1100 ProcReleaseSpins(NULL);
1104 * Also clean up any open wait for lock, since the lock manager will
1105 * choke if we try to wait for another lock before doing this.
1110 * check the current transaction state
1112 if (s->state == TRANS_DISABLED)
1114 RESUME_INTERRUPTS();
1118 if (s->state != TRANS_INPROGRESS)
1119 elog(NOTICE, "AbortTransaction and not in in-progress state");
1122 * set the current transaction state information appropriately during
1123 * the abort processing
1125 s->state = TRANS_ABORT;
1128 * Reset user id which might have been changed transiently
1130 SetUserId(GetSessionUserId());
1133 * do abort processing
1135 DeferredTriggerAbortXact();
1136 lo_commit(false); /* 'false' means it's abort */
1141 /* Advertise the fact that we aborted in pg_log. */
1142 RecordTransactionAbort();
1145 * Let others know about no transaction in progress by me. Note that
1146 * this must be done _before_ releasing locks we hold and _after_
1147 * RecordTransactionAbort.
1149 if (MyProc != (PROC *) NULL)
1151 /* Lock SInvalLock because that's what GetSnapshotData uses. */
1152 SpinAcquire(SInvalLock);
1153 MyProc->xid = InvalidTransactionId;
1154 MyProc->xmin = InvalidTransactionId;
1155 SpinRelease(SInvalLock);
1158 RelationPurgeLocalRelation(false);
1159 AtEOXact_temp_relations(false);
1160 smgrDoPendingDeletes(false);
1168 AtEOXact_CatCache(false);
1173 SharedBufferChanged = false;/* safest place to do it */
1175 /* Count transaction abort in statistics collector */
1176 pgstat_count_xact_rollback();
1179 * State remains TRANS_ABORT until CleanupTransaction().
1181 RESUME_INTERRUPTS();
1184 /* --------------------------------
1185 * CleanupTransaction
1187 * --------------------------------
1190 CleanupTransaction(void)
1192 TransactionState s = CurrentTransactionState;
1194 if (s->state == TRANS_DISABLED)
1198 * State should still be TRANS_ABORT from AbortTransaction().
1200 if (s->state != TRANS_ABORT)
1201 elog(FATAL, "CleanupTransaction and not in abort state");
1204 * do abort cleanup processing
1209 * done with abort processing, set current transaction state back to
1212 s->state = TRANS_DEFAULT;
1215 /* --------------------------------
1216 * StartTransactionCommand
1217 * --------------------------------
1220 StartTransactionCommand(void)
1222 TransactionState s = CurrentTransactionState;
1224 switch (s->blockState)
1228 * if we aren't in a transaction block, we just do our usual
1229 * start transaction.
1231 case TBLOCK_DEFAULT:
1236 * We should never experience this -- if we do it means the
1237 * BEGIN state was not changed in the previous
1238 * CommitTransactionCommand(). If we get it, we print a
1239 * warning and change to the in-progress state.
1242 elog(NOTICE, "StartTransactionCommand: unexpected TBLOCK_BEGIN");
1243 s->blockState = TBLOCK_INPROGRESS;
1247 * This is the case when are somewhere in a transaction block
1248 * and about to start a new command. For now we do nothing
1249 * but someday we may do command-local resource
1252 case TBLOCK_INPROGRESS:
1256 * As with BEGIN, we should never experience this if we do it
1257 * means the END state was not changed in the previous
1258 * CommitTransactionCommand(). If we get it, we print a
1259 * warning, commit the transaction, start a new transaction
1260 * and change to the default state.
1263 elog(NOTICE, "StartTransactionCommand: unexpected TBLOCK_END");
1264 s->blockState = TBLOCK_DEFAULT;
1265 CommitTransaction();
1270 * Here we are in the middle of a transaction block but one of
1271 * the commands caused an abort so we do nothing but remain in
1272 * the abort state. Eventually we will get to the "END
1273 * TRANSACTION" which will set things straight.
1279 * This means we somehow aborted and the last call to
1280 * CommitTransactionCommand() didn't clear the state so we
1281 * remain in the ENDABORT state and maybe next time we get to
1282 * CommitTransactionCommand() the state will get reset to
1285 case TBLOCK_ENDABORT:
1286 elog(NOTICE, "StartTransactionCommand: unexpected TBLOCK_ENDABORT");
1291 * We must switch to TransactionCommandContext before returning. This
1292 * is already done if we called StartTransaction, otherwise not.
1294 Assert(TransactionCommandContext != NULL);
1295 MemoryContextSwitchTo(TransactionCommandContext);
1298 /* --------------------------------
1299 * CommitTransactionCommand
1300 * --------------------------------
1303 CommitTransactionCommand(void)
1305 TransactionState s = CurrentTransactionState;
1307 switch (s->blockState)
1311 * if we aren't in a transaction block, we just do our usual
1312 * transaction commit
1314 case TBLOCK_DEFAULT:
1315 CommitTransaction();
1319 * This is the case right after we get a "BEGIN TRANSACTION"
1320 * command, but the user hasn't done anything else yet, so we
1321 * change to the "transaction block in progress" state and
1325 s->blockState = TBLOCK_INPROGRESS;
1329 * This is the case when we have finished executing a command
1330 * someplace within a transaction block. We increment the
1331 * command counter and return. Someday we may free resources
1332 * local to the command.
1334 * That someday is today, at least for memory allocated in
1335 * TransactionCommandContext. - vadim 03/25/97
1337 case TBLOCK_INPROGRESS:
1338 CommandCounterIncrement();
1339 MemoryContextResetAndDeleteChildren(TransactionCommandContext);
1343 * This is the case when we just got the "END TRANSACTION"
1344 * statement, so we commit the transaction and go back to the
1348 CommitTransaction();
1349 s->blockState = TBLOCK_DEFAULT;
1353 * Here we are in the middle of a transaction block but one of
1354 * the commands caused an abort so we do nothing but remain in
1355 * the abort state. Eventually we will get to the "END
1356 * TRANSACTION" which will set things straight.
1362 * Here we were in an aborted transaction block which just
1363 * processed the "END TRANSACTION" command from the user, so
1364 * clean up and return to the default state.
1366 case TBLOCK_ENDABORT:
1367 CleanupTransaction();
1368 s->blockState = TBLOCK_DEFAULT;
1373 /* --------------------------------
1374 * AbortCurrentTransaction
1375 * --------------------------------
1378 AbortCurrentTransaction(void)
1380 TransactionState s = CurrentTransactionState;
1382 switch (s->blockState)
1386 * if we aren't in a transaction block, we just do the basic
1387 * abort & cleanup transaction.
1389 case TBLOCK_DEFAULT:
1391 CleanupTransaction();
1395 * If we are in the TBLOCK_BEGIN it means something screwed up
1396 * right after reading "BEGIN TRANSACTION" so we enter the
1397 * abort state. Eventually an "END TRANSACTION" will fix
1401 s->blockState = TBLOCK_ABORT;
1403 /* CleanupTransaction happens when we exit TBLOCK_ABORT */
1407 * This is the case when are somewhere in a transaction block
1408 * which aborted so we abort the transaction and set the ABORT
1409 * state. Eventually an "END TRANSACTION" will fix things and
1410 * restore us to a normal state.
1412 case TBLOCK_INPROGRESS:
1413 s->blockState = TBLOCK_ABORT;
1415 /* CleanupTransaction happens when we exit TBLOCK_ABORT */
1419 * Here, the system was fouled up just after the user wanted
1420 * to end the transaction block so we abort the transaction
1421 * and put us back into the default state.
1424 s->blockState = TBLOCK_DEFAULT;
1426 CleanupTransaction();
1430 * Here, we are already in an aborted transaction state and
1431 * are waiting for an "END TRANSACTION" to come along and lo
1432 * and behold, we abort again! So we just remain in the abort
1439 * Here we were in an aborted transaction block which just
1440 * processed the "END TRANSACTION" command but somehow aborted
1441 * again.. since we must have done the abort processing, we
1442 * clean up and return to the default state.
1444 case TBLOCK_ENDABORT:
1445 CleanupTransaction();
1446 s->blockState = TBLOCK_DEFAULT;
1451 /* ----------------------------------------------------------------
1452 * transaction block support
1453 * ----------------------------------------------------------------
1455 /* --------------------------------
1456 * BeginTransactionBlock
1457 * --------------------------------
1460 BeginTransactionBlock(void)
1462 TransactionState s = CurrentTransactionState;
1465 * check the current transaction state
1467 if (s->state == TRANS_DISABLED)
1470 if (s->blockState != TBLOCK_DEFAULT)
1471 elog(NOTICE, "BEGIN: already a transaction in progress");
1474 * set the current transaction block state information appropriately
1475 * during begin processing
1477 s->blockState = TBLOCK_BEGIN;
1480 * do begin processing
1484 * done with begin processing, set block state to inprogress
1486 s->blockState = TBLOCK_INPROGRESS;
1489 /* --------------------------------
1490 * EndTransactionBlock
1491 * --------------------------------
1494 EndTransactionBlock(void)
1496 TransactionState s = CurrentTransactionState;
1499 * check the current transaction state
1501 if (s->state == TRANS_DISABLED)
1504 if (s->blockState == TBLOCK_INPROGRESS)
1508 * here we are in a transaction block which should commit when we
1509 * get to the upcoming CommitTransactionCommand() so we set the
1510 * state to "END". CommitTransactionCommand() will recognize this
1511 * and commit the transaction and return us to the default state
1513 s->blockState = TBLOCK_END;
1517 if (s->blockState == TBLOCK_ABORT)
1521 * here, we are in a transaction block which aborted and since the
1522 * AbortTransaction() was already done, we do whatever is needed
1523 * and change to the special "END ABORT" state. The upcoming
1524 * CommitTransactionCommand() will recognise this and then put us
1525 * back in the default state.
1527 s->blockState = TBLOCK_ENDABORT;
1532 * here, the user issued COMMIT when not inside a transaction. Issue a
1533 * notice and go to abort state. The upcoming call to
1534 * CommitTransactionCommand() will then put us back into the default
1537 elog(NOTICE, "COMMIT: no transaction in progress");
1539 s->blockState = TBLOCK_ENDABORT;
1542 /* --------------------------------
1543 * AbortTransactionBlock
1544 * --------------------------------
1548 AbortTransactionBlock(void)
1550 TransactionState s = CurrentTransactionState;
1553 * check the current transaction state
1555 if (s->state == TRANS_DISABLED)
1558 if (s->blockState == TBLOCK_INPROGRESS)
1562 * here we were inside a transaction block something screwed up
1563 * inside the system so we enter the abort state, do the abort
1564 * processing and then return. We remain in the abort state until
1565 * we see an END TRANSACTION command.
1567 s->blockState = TBLOCK_ABORT;
1573 * here, the user issued ABORT when not inside a transaction. Issue a
1574 * notice and go to abort state. The upcoming call to
1575 * CommitTransactionCommand() will then put us back into the default
1578 elog(NOTICE, "ROLLBACK: no transaction in progress");
1580 s->blockState = TBLOCK_ENDABORT;
1585 /* --------------------------------
1586 * UserAbortTransactionBlock
1587 * --------------------------------
1590 UserAbortTransactionBlock(void)
1592 TransactionState s = CurrentTransactionState;
1595 * check the current transaction state
1597 if (s->state == TRANS_DISABLED)
1601 * if the transaction has already been automatically aborted with an
1602 * error, and the user subsequently types 'abort', allow it. (the
1603 * behavior is the same as if they had typed 'end'.)
1605 if (s->blockState == TBLOCK_ABORT)
1607 s->blockState = TBLOCK_ENDABORT;
1611 if (s->blockState == TBLOCK_INPROGRESS)
1615 * here we were inside a transaction block and we got an abort
1616 * command from the user, so we move to the abort state, do the
1617 * abort processing and then change to the ENDABORT state so we
1618 * will end up in the default state after the upcoming
1619 * CommitTransactionCommand().
1621 s->blockState = TBLOCK_ABORT;
1623 s->blockState = TBLOCK_ENDABORT;
1628 * here, the user issued ABORT when not inside a transaction. Issue a
1629 * notice and go to abort state. The upcoming call to
1630 * CommitTransactionCommand() will then put us back into the default
1633 elog(NOTICE, "ROLLBACK: no transaction in progress");
1635 s->blockState = TBLOCK_ENDABORT;
1638 /* --------------------------------
1639 * AbortOutOfAnyTransaction
1641 * This routine is provided for error recovery purposes. It aborts any
1642 * active transaction or transaction block, leaving the system in a known
1644 * --------------------------------
1647 AbortOutOfAnyTransaction(void)
1649 TransactionState s = CurrentTransactionState;
1652 * Get out of any low-level transaction
1657 case TRANS_INPROGRESS:
1659 /* In a transaction, so clean up */
1661 CleanupTransaction();
1664 /* AbortTransaction already done, still need Cleanup */
1665 CleanupTransaction();
1668 case TRANS_DISABLED:
1669 /* Not in a transaction, do nothing */
1674 * Now reset the high-level state
1676 s->blockState = TBLOCK_DEFAULT;
1680 IsTransactionBlock(void)
1682 TransactionState s = CurrentTransactionState;
1684 if (s->blockState == TBLOCK_INPROGRESS
1685 || s->blockState == TBLOCK_ABORT
1686 || s->blockState == TBLOCK_ENDABORT)
1693 xact_redo(XLogRecPtr lsn, XLogRecord *record)
1695 uint8 info = record->xl_info & ~XLR_INFO_MASK;
1697 if (info == XLOG_XACT_COMMIT)
1699 TransactionIdCommit(record->xl_xid);
1700 /* SHOULD REMOVE FILES OF ALL DROPPED RELATIONS */
1702 else if (info == XLOG_XACT_ABORT)
1703 TransactionIdAbort(record->xl_xid);
1705 elog(STOP, "xact_redo: unknown op code %u", info);
1709 xact_undo(XLogRecPtr lsn, XLogRecord *record)
1711 uint8 info = record->xl_info & ~XLR_INFO_MASK;
1713 if (info == XLOG_XACT_COMMIT) /* shouldn't be called by XLOG */
1714 elog(STOP, "xact_undo: can't undo committed xaction");
1715 else if (info != XLOG_XACT_ABORT)
1716 elog(STOP, "xact_redo: unknown op code %u", info);
1720 xact_desc(char *buf, uint8 xl_info, char *rec)
1722 uint8 info = xl_info & ~XLR_INFO_MASK;
1724 if (info == XLOG_XACT_COMMIT)
1726 xl_xact_commit *xlrec = (xl_xact_commit *) rec;
1727 struct tm *tm = localtime(&xlrec->xtime);
1729 sprintf(buf + strlen(buf), "commit: %04u-%02u-%02u %02u:%02u:%02u",
1730 tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday,
1731 tm->tm_hour, tm->tm_min, tm->tm_sec);
1733 else if (info == XLOG_XACT_ABORT)
1735 xl_xact_abort *xlrec = (xl_xact_abort *) rec;
1736 struct tm *tm = localtime(&xlrec->xtime);
1738 sprintf(buf + strlen(buf), "abort: %04u-%02u-%02u %02u:%02u:%02u",
1739 tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday,
1740 tm->tm_hour, tm->tm_min, tm->tm_sec);
1743 strcat(buf, "UNKNOWN");
1747 XactPushRollback(void (*func) (void *), void *data)
1750 if (_RollbackFunc != NULL)
1751 elog(STOP, "XactPushRollback: already installed");
1754 _RollbackFunc = func;
1755 _RollbackData = data;
1759 XactPopRollback(void)
1761 _RollbackFunc = NULL;