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.113 2001/10/25 05:49:22 momjian 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 * catalog creation transaction bootstrapping flag.
233 * This should be eliminated and added to the transaction
234 * state stuff. -cim 3/19/90
237 bool AMI_OVERRIDE = false;
239 /* ----------------------------------------------------------------
240 * transaction state accessors
241 * ----------------------------------------------------------------
244 /* --------------------------------
245 * TranactionFlushEnabled()
246 * SetTransactionFlushEnabled()
248 * These are used to test and set the "TransactionFlushState"
249 * varable. If this variable is true (the default), then
250 * the system will flush all dirty buffers to disk at the end
251 * of each transaction. If false then we are assuming the
252 * buffer pool resides in stable main memory, in which case we
253 * only do writes as necessary.
254 * --------------------------------
256 static int TransactionFlushState = 1;
259 TransactionFlushEnabled(void)
261 return TransactionFlushState;
266 SetTransactionFlushEnabled(bool state)
268 TransactionFlushState = (state == true);
272 /* --------------------------------
275 * This returns true if we are currently running a query
276 * within an executing transaction.
277 * --------------------------------
280 IsTransactionState(void)
282 TransactionState s = CurrentTransactionState;
290 case TRANS_INPROGRESS:
299 * Shouldn't get here, but lint is not happy with this...
305 /* --------------------------------
306 * IsAbortedTransactionBlockState
308 * This returns true if we are currently running a query
309 * within an aborted transaction block.
310 * --------------------------------
313 IsAbortedTransactionBlockState(void)
315 TransactionState s = CurrentTransactionState;
317 if (s->blockState == TBLOCK_ABORT)
324 /* --------------------------------
325 * GetCurrentTransactionId
326 * --------------------------------
329 GetCurrentTransactionId(void)
331 TransactionState s = CurrentTransactionState;
333 return s->transactionIdData;
337 /* --------------------------------
338 * GetCurrentCommandId
339 * --------------------------------
342 GetCurrentCommandId(void)
344 TransactionState s = CurrentTransactionState;
350 GetScanCommandId(void)
352 TransactionState s = CurrentTransactionState;
354 return s->scanCommandId;
358 /* --------------------------------
359 * GetCurrentTransactionStartTime
360 * --------------------------------
363 GetCurrentTransactionStartTime(void)
365 TransactionState s = CurrentTransactionState;
371 /* --------------------------------
372 * GetCurrentTransactionStartTimeUsec
373 * --------------------------------
376 GetCurrentTransactionStartTimeUsec(int *msec)
378 TransactionState s = CurrentTransactionState;
380 *msec = s->startTimeUsec;
386 /* --------------------------------
387 * TransactionIdIsCurrentTransactionId
388 * --------------------------------
391 TransactionIdIsCurrentTransactionId(TransactionId xid)
393 TransactionState s = CurrentTransactionState;
398 return TransactionIdEquals(xid, s->transactionIdData);
402 /* --------------------------------
403 * CommandIdIsCurrentCommandId
404 * --------------------------------
407 CommandIdIsCurrentCommandId(CommandId cid)
409 TransactionState s = CurrentTransactionState;
414 return (cid == s->commandId) ? true : false;
418 CommandIdGEScanCommandId(CommandId cid)
420 TransactionState s = CurrentTransactionState;
425 return (cid >= s->scanCommandId) ? true : false;
429 /* --------------------------------
430 * CommandCounterIncrement
431 * --------------------------------
434 CommandCounterIncrement(void)
436 CurrentTransactionStateData.commandId += 1;
437 if (CurrentTransactionStateData.commandId == FirstCommandId)
438 elog(ERROR, "You may only have 2^32-1 commands per transaction");
440 CurrentTransactionStateData.scanCommandId = CurrentTransactionStateData.commandId;
443 * make cache changes visible to me. AtCommit_LocalCache() instead of
444 * AtCommit_Cache() is called here.
446 AtCommit_LocalCache();
451 SetScanCommandId(CommandId savedId)
453 CurrentTransactionStateData.scanCommandId = savedId;
456 /* ----------------------------------------------------------------
457 * StartTransaction stuff
458 * ----------------------------------------------------------------
461 /* --------------------------------
463 * --------------------------------
468 AcceptInvalidationMessages();
471 /* --------------------------------
473 * --------------------------------
479 * at present, it is unknown to me what belongs here -cim 3/18/90
481 * There isn't anything to do at the start of a xact for locks. -mer
486 /* --------------------------------
488 * --------------------------------
494 * We shouldn't have any transaction contexts already.
496 Assert(TopTransactionContext == NULL);
497 Assert(TransactionCommandContext == NULL);
500 * Create a toplevel context for the transaction.
502 TopTransactionContext =
503 AllocSetContextCreate(TopMemoryContext,
504 "TopTransactionContext",
505 ALLOCSET_DEFAULT_MINSIZE,
506 ALLOCSET_DEFAULT_INITSIZE,
507 ALLOCSET_DEFAULT_MAXSIZE);
510 * Create a statement-level context and make it active.
512 TransactionCommandContext =
513 AllocSetContextCreate(TopTransactionContext,
514 "TransactionCommandContext",
515 ALLOCSET_DEFAULT_MINSIZE,
516 ALLOCSET_DEFAULT_INITSIZE,
517 ALLOCSET_DEFAULT_MAXSIZE);
518 MemoryContextSwitchTo(TransactionCommandContext);
522 /* ----------------------------------------------------------------
523 * CommitTransaction stuff
524 * ----------------------------------------------------------------
527 /* --------------------------------
528 * RecordTransactionCommit
530 * Note: the two calls to BufferManagerFlush() exist to ensure
531 * that data pages are written before log pages. These
532 * explicit calls should be replaced by a more efficient
533 * ordered page write scheme in the buffer manager
535 * --------------------------------
538 RecordTransactionCommit(void)
543 leak = BufferPoolCheckLeak();
545 xid = GetCurrentTransactionId();
548 * We needn't write anything in xlog or clog if the transaction was
549 * read-only, which we check by testing if it made any xlog entries.
551 if (MyLastRecPtr.xrecoff != 0)
554 xl_xact_commit xlrec;
559 xlrec.xtime = time(NULL);
560 rdata.buffer = InvalidBuffer;
561 rdata.data = (char *) (&xlrec);
562 rdata.len = SizeOfXactCommit;
565 START_CRIT_SECTION();
568 * SHOULD SAVE ARRAY OF RELFILENODE-s TO DROP
570 recptr = XLogInsert(RM_XACT_ID, XLOG_XACT_COMMIT, &rdata);
573 * Sleep before commit! So we can flush more than one commit
574 * records per single fsync. (The idea is some other backend may
575 * do the XLogFlush while we're sleeping. This needs work still,
576 * because on most Unixen, the minimum select() delay is 10msec or
577 * more, which is way too long.)
579 * We do not sleep if enableFsync is not turned on, nor if there are
580 * fewer than CommitSiblings other backends with active
583 if (CommitDelay > 0 && enableFsync &&
584 CountActiveBackends() >= CommitSiblings)
586 struct timeval delay;
589 delay.tv_usec = CommitDelay;
590 (void) select(0, NULL, NULL, NULL, &delay);
595 /* Break the chain of back-links in the XLOG records I output */
596 MyLastRecPtr.xrecoff = 0;
598 /* Mark the transaction committed in clog */
599 TransactionIdCommit(xid);
604 /* Show myself as out of the transaction in PROC array */
605 MyProc->logRec.xrecoff = 0;
608 ResetBufferPool(true);
612 /* --------------------------------
614 * --------------------------------
620 * Make catalog changes visible to all backends.
622 AtEOXactInvalidationMessages(true);
625 /* --------------------------------
626 * AtCommit_LocalCache
627 * --------------------------------
630 AtCommit_LocalCache(void)
633 * Make catalog changes visible to me for the next command.
635 CommandEndInvalidationMessages(true);
638 /* --------------------------------
640 * --------------------------------
646 * XXX What if ProcReleaseLocks fails? (race condition?)
648 * Then you're up a creek! -mer 5/24/92
650 ProcReleaseLocks(true);
653 /* --------------------------------
655 * --------------------------------
658 AtCommit_Memory(void)
661 * Now that we're "out" of a transaction, have the system allocate
662 * things in the top memory context instead of per-transaction
665 MemoryContextSwitchTo(TopMemoryContext);
668 * Release all transaction-local memory.
670 Assert(TopTransactionContext != NULL);
671 MemoryContextDelete(TopTransactionContext);
672 TopTransactionContext = NULL;
673 TransactionCommandContext = NULL;
676 /* ----------------------------------------------------------------
677 * AbortTransaction stuff
678 * ----------------------------------------------------------------
681 /* --------------------------------
682 * RecordTransactionAbort
683 * --------------------------------
686 RecordTransactionAbort(void)
688 TransactionId xid = GetCurrentTransactionId();
691 * We needn't write anything in xlog or clog if the transaction was
692 * read-only, which we check by testing if it made any xlog entries.
694 * Extra check here is to catch case that we aborted partway through
695 * RecordTransactionCommit ...
697 if (MyLastRecPtr.xrecoff != 0 && !TransactionIdDidCommit(xid))
703 xlrec.xtime = time(NULL);
704 rdata.buffer = InvalidBuffer;
705 rdata.data = (char *) (&xlrec);
706 rdata.len = SizeOfXactAbort;
709 START_CRIT_SECTION();
712 * SHOULD SAVE ARRAY OF RELFILENODE-s TO DROP
714 recptr = XLogInsert(RM_XACT_ID, XLOG_XACT_ABORT, &rdata);
717 * There's no need for XLogFlush here, since the default
718 * assumption would be that we aborted, anyway.
721 /* Mark the transaction aborted in clog */
722 TransactionIdAbort(xid);
727 /* Break the chain of back-links in the XLOG records I output */
728 MyLastRecPtr.xrecoff = 0;
729 /* Show myself as out of the transaction in PROC array */
730 MyProc->logRec.xrecoff = 0;
733 * Tell bufmgr and smgr to release resources.
735 ResetBufferPool(false); /* false -> is abort */
738 /* --------------------------------
740 * --------------------------------
745 RelationCacheAbort();
746 AtEOXactInvalidationMessages(false);
749 /* --------------------------------
751 * --------------------------------
757 * XXX What if ProcReleaseLocks() fails? (race condition?)
759 * Then you're up a creek without a paddle! -mer
761 ProcReleaseLocks(false);
765 /* --------------------------------
767 * --------------------------------
773 * Make sure we are in a valid context (not a child of
774 * TransactionCommandContext...). Note that it is possible for this
775 * code to be called when we aren't in a transaction at all; go
776 * directly to TopMemoryContext in that case.
778 if (TransactionCommandContext != NULL)
780 MemoryContextSwitchTo(TransactionCommandContext);
783 * We do not want to destroy transaction contexts yet, but it
784 * should be OK to delete any command-local memory.
786 MemoryContextResetAndDeleteChildren(TransactionCommandContext);
789 MemoryContextSwitchTo(TopMemoryContext);
793 /* ----------------------------------------------------------------
794 * CleanupTransaction stuff
795 * ----------------------------------------------------------------
798 /* --------------------------------
800 * --------------------------------
803 AtCleanup_Memory(void)
806 * Now that we're "out" of a transaction, have the system allocate
807 * things in the top memory context instead of per-transaction
810 MemoryContextSwitchTo(TopMemoryContext);
813 * Release all transaction-local memory.
815 if (TopTransactionContext != NULL)
816 MemoryContextDelete(TopTransactionContext);
817 TopTransactionContext = NULL;
818 TransactionCommandContext = NULL;
822 /* ----------------------------------------------------------------
824 * ----------------------------------------------------------------
827 /* --------------------------------
830 * --------------------------------
833 StartTransaction(void)
835 TransactionState s = CurrentTransactionState;
838 XactIsoLevel = DefaultXactIsoLevel;
841 * Check the current transaction state. If the transaction system is
842 * switched off, or if we're already in a transaction, do nothing.
843 * We're already in a transaction when the monitor sends a null
844 * command to the backend to flush the comm channel. This is a hacky
845 * fix to a communications problem, and we keep having to deal with it
846 * here. We should fix the comm channel code. mao 080891
848 if (s->state == TRANS_INPROGRESS)
852 * set the current transaction state information appropriately during
855 s->state = TRANS_START;
857 SetReindexProcessing(false);
860 * generate a new transaction id
862 s->transactionIdData = GetNewTransactionId();
864 XactLockTableInsert(s->transactionIdData);
867 * initialize current transaction state fields
869 s->commandId = FirstCommandId;
870 s->scanCommandId = FirstCommandId;
872 s->startTime = GetCurrentAbsoluteTime();
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(NOTICE, "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 AtEOXact_temp_relations(true);
984 smgrDoPendingDeletes(true);
993 AtEOXact_CatCache(true);
997 SharedBufferChanged = false; /* safest place to do it */
999 /* Count transaction commit in statistics collector */
1000 pgstat_count_xact_commit();
1003 * done with commit processing, set current transaction state back to
1006 s->state = TRANS_DEFAULT;
1008 RESUME_INTERRUPTS();
1011 /* --------------------------------
1014 * --------------------------------
1017 AbortTransaction(void)
1019 TransactionState s = CurrentTransactionState;
1021 /* Prevent cancel/die interrupt while cleaning up */
1025 * Release any LW locks we might be holding as quickly as possible.
1026 * (Regular locks, however, must be held till we finish aborting.)
1027 * Releasing LW locks is critical since we might try to grab them
1028 * again while cleaning up!
1032 /* Clean up buffer I/O and buffer context locks, too */
1037 * Also clean up any open wait for lock, since the lock manager will
1038 * choke if we try to wait for another lock before doing this.
1043 * check the current transaction state
1045 if (s->state != TRANS_INPROGRESS)
1046 elog(NOTICE, "AbortTransaction and not in in-progress state");
1049 * set the current transaction state information appropriately during
1050 * the abort processing
1052 s->state = TRANS_ABORT;
1055 * Reset user id which might have been changed transiently
1057 SetUserId(GetSessionUserId());
1060 * do abort processing
1062 DeferredTriggerAbortXact();
1063 lo_commit(false); /* 'false' means it's abort */
1068 /* Advertise the fact that we aborted in pg_clog. */
1069 RecordTransactionAbort();
1072 * Let others know about no transaction in progress by me. Note that
1073 * this must be done _before_ releasing locks we hold and _after_
1074 * RecordTransactionAbort.
1076 if (MyProc != (PROC *) NULL)
1078 /* Lock SInvalLock because that's what GetSnapshotData uses. */
1079 LWLockAcquire(SInvalLock, LW_EXCLUSIVE);
1080 MyProc->xid = InvalidTransactionId;
1081 MyProc->xmin = InvalidTransactionId;
1082 LWLockRelease(SInvalLock);
1085 RelationPurgeLocalRelation(false);
1086 AtEOXact_temp_relations(false);
1087 smgrDoPendingDeletes(false);
1095 AtEOXact_CatCache(false);
1100 SharedBufferChanged = false; /* safest place to do it */
1102 /* Count transaction abort in statistics collector */
1103 pgstat_count_xact_rollback();
1106 * State remains TRANS_ABORT until CleanupTransaction().
1108 RESUME_INTERRUPTS();
1111 /* --------------------------------
1112 * CleanupTransaction
1114 * --------------------------------
1117 CleanupTransaction(void)
1119 TransactionState s = CurrentTransactionState;
1122 * State should still be TRANS_ABORT from AbortTransaction().
1124 if (s->state != TRANS_ABORT)
1125 elog(FATAL, "CleanupTransaction and not in abort state");
1128 * do abort cleanup processing
1133 * done with abort processing, set current transaction state back to
1136 s->state = TRANS_DEFAULT;
1139 /* --------------------------------
1140 * StartTransactionCommand
1141 * --------------------------------
1144 StartTransactionCommand(void)
1146 TransactionState s = CurrentTransactionState;
1148 switch (s->blockState)
1151 * if we aren't in a transaction block, we just do our usual
1152 * start transaction.
1154 case TBLOCK_DEFAULT:
1159 * We should never experience this -- if we do it means the
1160 * BEGIN state was not changed in the previous
1161 * CommitTransactionCommand(). If we get it, we print a
1162 * warning and change to the in-progress state.
1165 elog(NOTICE, "StartTransactionCommand: unexpected TBLOCK_BEGIN");
1166 s->blockState = TBLOCK_INPROGRESS;
1170 * This is the case when are somewhere in a transaction block
1171 * and about to start a new command. For now we do nothing
1172 * but someday we may do command-local resource
1175 case TBLOCK_INPROGRESS:
1179 * As with BEGIN, we should never experience this if we do it
1180 * means the END state was not changed in the previous
1181 * CommitTransactionCommand(). If we get it, we print a
1182 * warning, commit the transaction, start a new transaction
1183 * and change to the default state.
1186 elog(NOTICE, "StartTransactionCommand: unexpected TBLOCK_END");
1187 s->blockState = TBLOCK_DEFAULT;
1188 CommitTransaction();
1193 * Here we are in the middle of a transaction block but one of
1194 * the commands caused an abort so we do nothing but remain in
1195 * the abort state. Eventually we will get to the "END
1196 * TRANSACTION" which will set things straight.
1202 * This means we somehow aborted and the last call to
1203 * CommitTransactionCommand() didn't clear the state so we
1204 * remain in the ENDABORT state and maybe next time we get to
1205 * CommitTransactionCommand() the state will get reset to
1208 case TBLOCK_ENDABORT:
1209 elog(NOTICE, "StartTransactionCommand: unexpected TBLOCK_ENDABORT");
1214 * We must switch to TransactionCommandContext before returning. This
1215 * is already done if we called StartTransaction, otherwise not.
1217 Assert(TransactionCommandContext != NULL);
1218 MemoryContextSwitchTo(TransactionCommandContext);
1221 /* --------------------------------
1222 * CommitTransactionCommand
1223 * --------------------------------
1226 CommitTransactionCommand(void)
1228 TransactionState s = CurrentTransactionState;
1230 switch (s->blockState)
1233 * if we aren't in a transaction block, we just do our usual
1234 * transaction commit
1236 case TBLOCK_DEFAULT:
1237 CommitTransaction();
1241 * This is the case right after we get a "BEGIN TRANSACTION"
1242 * command, but the user hasn't done anything else yet, so we
1243 * change to the "transaction block in progress" state and
1247 s->blockState = TBLOCK_INPROGRESS;
1251 * This is the case when we have finished executing a command
1252 * someplace within a transaction block. We increment the
1253 * command counter and return. Someday we may free resources
1254 * local to the command.
1256 * That someday is today, at least for memory allocated in
1257 * TransactionCommandContext. - vadim 03/25/97
1259 case TBLOCK_INPROGRESS:
1260 CommandCounterIncrement();
1261 MemoryContextResetAndDeleteChildren(TransactionCommandContext);
1265 * This is the case when we just got the "END TRANSACTION"
1266 * statement, so we commit the transaction and go back to the
1270 CommitTransaction();
1271 s->blockState = TBLOCK_DEFAULT;
1275 * Here we are in the middle of a transaction block but one of
1276 * the commands caused an abort so we do nothing but remain in
1277 * the abort state. Eventually we will get to the "END
1278 * TRANSACTION" which will set things straight.
1284 * Here we were in an aborted transaction block which just
1285 * processed the "END TRANSACTION" command from the user, so
1286 * clean up and return to the default state.
1288 case TBLOCK_ENDABORT:
1289 CleanupTransaction();
1290 s->blockState = TBLOCK_DEFAULT;
1295 /* --------------------------------
1296 * AbortCurrentTransaction
1297 * --------------------------------
1300 AbortCurrentTransaction(void)
1302 TransactionState s = CurrentTransactionState;
1304 switch (s->blockState)
1307 * if we aren't in a transaction block, we just do the basic
1308 * abort & cleanup transaction.
1310 case TBLOCK_DEFAULT:
1312 CleanupTransaction();
1316 * If we are in the TBLOCK_BEGIN it means something screwed up
1317 * right after reading "BEGIN TRANSACTION" so we enter the
1318 * abort state. Eventually an "END TRANSACTION" will fix
1322 s->blockState = TBLOCK_ABORT;
1324 /* CleanupTransaction happens when we exit TBLOCK_ABORT */
1328 * This is the case when are somewhere in a transaction block
1329 * which aborted so we abort the transaction and set the ABORT
1330 * state. Eventually an "END TRANSACTION" will fix things and
1331 * restore us to a normal state.
1333 case TBLOCK_INPROGRESS:
1334 s->blockState = TBLOCK_ABORT;
1336 /* CleanupTransaction happens when we exit TBLOCK_ABORT */
1340 * Here, the system was fouled up just after the user wanted
1341 * to end the transaction block so we abort the transaction
1342 * and put us back into the default state.
1345 s->blockState = TBLOCK_DEFAULT;
1347 CleanupTransaction();
1351 * Here, we are already in an aborted transaction state and
1352 * are waiting for an "END TRANSACTION" to come along and lo
1353 * and behold, we abort again! So we just remain in the abort
1360 * Here we were in an aborted transaction block which just
1361 * processed the "END TRANSACTION" command but somehow aborted
1362 * again.. since we must have done the abort processing, we
1363 * clean up and return to the default state.
1365 case TBLOCK_ENDABORT:
1366 CleanupTransaction();
1367 s->blockState = TBLOCK_DEFAULT;
1372 /* ----------------------------------------------------------------
1373 * transaction block support
1374 * ----------------------------------------------------------------
1376 /* --------------------------------
1377 * BeginTransactionBlock
1378 * --------------------------------
1381 BeginTransactionBlock(void)
1383 TransactionState s = CurrentTransactionState;
1386 * check the current transaction state
1388 if (s->blockState != TBLOCK_DEFAULT)
1389 elog(NOTICE, "BEGIN: already a transaction in progress");
1392 * set the current transaction block state information appropriately
1393 * during begin processing
1395 s->blockState = TBLOCK_BEGIN;
1398 * do begin processing
1402 * done with begin processing, set block state to inprogress
1404 s->blockState = TBLOCK_INPROGRESS;
1407 /* --------------------------------
1408 * EndTransactionBlock
1409 * --------------------------------
1412 EndTransactionBlock(void)
1414 TransactionState s = CurrentTransactionState;
1417 * check the current transaction state
1419 if (s->blockState == TBLOCK_INPROGRESS)
1422 * here we are in a transaction block which should commit when we
1423 * get to the upcoming CommitTransactionCommand() so we set the
1424 * state to "END". CommitTransactionCommand() will recognize this
1425 * and commit the transaction and return us to the default state
1427 s->blockState = TBLOCK_END;
1431 if (s->blockState == TBLOCK_ABORT)
1434 * here, we are in a transaction block which aborted and since the
1435 * AbortTransaction() was already done, we do whatever is needed
1436 * and change to the special "END ABORT" state. The upcoming
1437 * CommitTransactionCommand() will recognise this and then put us
1438 * back in the default state.
1440 s->blockState = TBLOCK_ENDABORT;
1445 * here, the user issued COMMIT when not inside a transaction. Issue a
1446 * notice and go to abort state. The upcoming call to
1447 * CommitTransactionCommand() will then put us back into the default
1450 elog(NOTICE, "COMMIT: no transaction in progress");
1452 s->blockState = TBLOCK_ENDABORT;
1455 /* --------------------------------
1456 * AbortTransactionBlock
1457 * --------------------------------
1461 AbortTransactionBlock(void)
1463 TransactionState s = CurrentTransactionState;
1466 * check the current transaction state
1468 if (s->blockState == TBLOCK_INPROGRESS)
1471 * here we were inside a transaction block something screwed up
1472 * inside the system so we enter the abort state, do the abort
1473 * processing and then return. We remain in the abort state until
1474 * we see an END TRANSACTION command.
1476 s->blockState = TBLOCK_ABORT;
1482 * here, the user issued ABORT when not inside a transaction. Issue a
1483 * notice and go to abort state. The upcoming call to
1484 * CommitTransactionCommand() will then put us back into the default
1487 elog(NOTICE, "ROLLBACK: no transaction in progress");
1489 s->blockState = TBLOCK_ENDABORT;
1493 /* --------------------------------
1494 * UserAbortTransactionBlock
1495 * --------------------------------
1498 UserAbortTransactionBlock(void)
1500 TransactionState s = CurrentTransactionState;
1503 * if the transaction has already been automatically aborted with an
1504 * error, and the user subsequently types 'abort', allow it. (the
1505 * behavior is the same as if they had typed 'end'.)
1507 if (s->blockState == TBLOCK_ABORT)
1509 s->blockState = TBLOCK_ENDABORT;
1513 if (s->blockState == TBLOCK_INPROGRESS)
1516 * here we were inside a transaction block and we got an abort
1517 * command from the user, so we move to the abort state, do the
1518 * abort processing and then change to the ENDABORT state so we
1519 * will end up in the default state after the upcoming
1520 * CommitTransactionCommand().
1522 s->blockState = TBLOCK_ABORT;
1524 s->blockState = TBLOCK_ENDABORT;
1529 * here, the user issued ABORT when not inside a transaction. Issue a
1530 * notice and go to abort state. The upcoming call to
1531 * CommitTransactionCommand() will then put us back into the default
1534 elog(NOTICE, "ROLLBACK: no transaction in progress");
1536 s->blockState = TBLOCK_ENDABORT;
1539 /* --------------------------------
1540 * AbortOutOfAnyTransaction
1542 * This routine is provided for error recovery purposes. It aborts any
1543 * active transaction or transaction block, leaving the system in a known
1545 * --------------------------------
1548 AbortOutOfAnyTransaction(void)
1550 TransactionState s = CurrentTransactionState;
1553 * Get out of any low-level transaction
1558 case TRANS_INPROGRESS:
1560 /* In a transaction, so clean up */
1562 CleanupTransaction();
1565 /* AbortTransaction already done, still need Cleanup */
1566 CleanupTransaction();
1569 /* Not in a transaction, do nothing */
1574 * Now reset the high-level state
1576 s->blockState = TBLOCK_DEFAULT;
1580 IsTransactionBlock(void)
1582 TransactionState s = CurrentTransactionState;
1584 if (s->blockState == TBLOCK_INPROGRESS
1585 || s->blockState == TBLOCK_ABORT
1586 || s->blockState == TBLOCK_ENDABORT)
1593 xact_redo(XLogRecPtr lsn, XLogRecord *record)
1595 uint8 info = record->xl_info & ~XLR_INFO_MASK;
1597 if (info == XLOG_XACT_COMMIT)
1599 TransactionIdCommit(record->xl_xid);
1600 /* SHOULD REMOVE FILES OF ALL DROPPED RELATIONS */
1602 else if (info == XLOG_XACT_ABORT)
1604 TransactionIdAbort(record->xl_xid);
1605 /* SHOULD REMOVE FILES OF ALL FAILED-TO-BE-CREATED RELATIONS */
1608 elog(STOP, "xact_redo: unknown op code %u", info);
1612 xact_undo(XLogRecPtr lsn, XLogRecord *record)
1614 uint8 info = record->xl_info & ~XLR_INFO_MASK;
1616 if (info == XLOG_XACT_COMMIT) /* shouldn't be called by XLOG */
1617 elog(STOP, "xact_undo: can't undo committed xaction");
1618 else if (info != XLOG_XACT_ABORT)
1619 elog(STOP, "xact_redo: unknown op code %u", info);
1623 xact_desc(char *buf, uint8 xl_info, char *rec)
1625 uint8 info = xl_info & ~XLR_INFO_MASK;
1627 if (info == XLOG_XACT_COMMIT)
1629 xl_xact_commit *xlrec = (xl_xact_commit *) rec;
1630 struct tm *tm = localtime(&xlrec->xtime);
1632 sprintf(buf + strlen(buf), "commit: %04u-%02u-%02u %02u:%02u:%02u",
1633 tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday,
1634 tm->tm_hour, tm->tm_min, tm->tm_sec);
1636 else if (info == XLOG_XACT_ABORT)
1638 xl_xact_abort *xlrec = (xl_xact_abort *) rec;
1639 struct tm *tm = localtime(&xlrec->xtime);
1641 sprintf(buf + strlen(buf), "abort: %04u-%02u-%02u %02u:%02u:%02u",
1642 tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday,
1643 tm->tm_hour, tm->tm_min, tm->tm_sec);
1646 strcat(buf, "UNKNOWN");
1650 XactPushRollback(void (*func) (void *), void *data)
1653 if (_RollbackFunc != NULL)
1654 elog(STOP, "XactPushRollback: already installed");
1657 _RollbackFunc = func;
1658 _RollbackData = data;
1662 XactPopRollback(void)
1664 _RollbackFunc = NULL;