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.117 2002/03/06 06:09:21 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"
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 "commands/async.h"
168 #include "commands/sequence.h"
169 #include "commands/trigger.h"
170 #include "executor/spi.h"
171 #include "libpq/be-fsstubs.h"
172 #include "miscadmin.h"
173 #include "storage/proc.h"
174 #include "storage/sinval.h"
175 #include "storage/smgr.h"
176 #include "utils/inval.h"
177 #include "utils/memutils.h"
178 #include "utils/portal.h"
179 #include "utils/catcache.h"
180 #include "utils/relcache.h"
181 #include "utils/temprel.h"
185 extern bool SharedBufferChanged;
187 static void AbortTransaction(void);
188 static void AtAbort_Cache(void);
189 static void AtAbort_Locks(void);
190 static void AtAbort_Memory(void);
191 static void AtCleanup_Memory(void);
192 static void AtCommit_Cache(void);
193 static void AtCommit_LocalCache(void);
194 static void AtCommit_Locks(void);
195 static void AtCommit_Memory(void);
196 static void AtStart_Cache(void);
197 static void AtStart_Locks(void);
198 static void AtStart_Memory(void);
199 static void CleanupTransaction(void);
200 static void CommitTransaction(void);
201 static void RecordTransactionAbort(void);
202 static void StartTransaction(void);
205 * global variables holding the current transaction state.
208 static TransactionStateData CurrentTransactionStateData = {
209 0, /* transaction id */
210 FirstCommandId, /* command id */
211 0, /* scan command id */
212 0x0, /* start time */
213 TRANS_DEFAULT, /* transaction state */
214 TBLOCK_DEFAULT /* transaction block state */
217 TransactionState CurrentTransactionState = &CurrentTransactionStateData;
220 * User-tweakable parameters
222 int DefaultXactIsoLevel = XACT_READ_COMMITTED;
225 int CommitDelay = 0; /* precommit delay in microseconds */
226 int CommitSiblings = 5; /* number of concurrent xacts needed to
229 static void (*_RollbackFunc) (void *) = NULL;
230 static void *_RollbackData = NULL;
233 * catalog creation transaction bootstrapping flag.
234 * This should be eliminated and added to the transaction
235 * state stuff. -cim 3/19/90
238 bool AMI_OVERRIDE = false;
240 /* ----------------------------------------------------------------
241 * transaction state accessors
242 * ----------------------------------------------------------------
245 /* --------------------------------
246 * TranactionFlushEnabled()
247 * SetTransactionFlushEnabled()
249 * These are used to test and set the "TransactionFlushState"
250 * varable. If this variable is true (the default), then
251 * the system will flush all dirty buffers to disk at the end
252 * of each transaction. If false then we are assuming the
253 * buffer pool resides in stable main memory, in which case we
254 * only do writes as necessary.
255 * --------------------------------
257 static int TransactionFlushState = 1;
260 TransactionFlushEnabled(void)
262 return TransactionFlushState;
267 SetTransactionFlushEnabled(bool state)
269 TransactionFlushState = (state == true);
273 /* --------------------------------
276 * This returns true if we are currently running a query
277 * within an executing transaction.
278 * --------------------------------
281 IsTransactionState(void)
283 TransactionState s = CurrentTransactionState;
291 case TRANS_INPROGRESS:
300 * Shouldn't get here, but lint is not happy with this...
306 /* --------------------------------
307 * IsAbortedTransactionBlockState
309 * This returns true if we are currently running a query
310 * within an aborted transaction block.
311 * --------------------------------
314 IsAbortedTransactionBlockState(void)
316 TransactionState s = CurrentTransactionState;
318 if (s->blockState == TBLOCK_ABORT)
325 /* --------------------------------
326 * GetCurrentTransactionId
327 * --------------------------------
330 GetCurrentTransactionId(void)
332 TransactionState s = CurrentTransactionState;
334 return s->transactionIdData;
338 /* --------------------------------
339 * GetCurrentCommandId
340 * --------------------------------
343 GetCurrentCommandId(void)
345 TransactionState s = CurrentTransactionState;
351 GetScanCommandId(void)
353 TransactionState s = CurrentTransactionState;
355 return s->scanCommandId;
359 /* --------------------------------
360 * GetCurrentTransactionStartTime
361 * --------------------------------
364 GetCurrentTransactionStartTime(void)
366 TransactionState s = CurrentTransactionState;
372 /* --------------------------------
373 * GetCurrentTransactionStartTimeUsec
374 * --------------------------------
377 GetCurrentTransactionStartTimeUsec(int *msec)
379 TransactionState s = CurrentTransactionState;
381 *msec = s->startTimeUsec;
387 /* --------------------------------
388 * TransactionIdIsCurrentTransactionId
389 * --------------------------------
392 TransactionIdIsCurrentTransactionId(TransactionId xid)
394 TransactionState s = CurrentTransactionState;
399 return TransactionIdEquals(xid, s->transactionIdData);
403 /* --------------------------------
404 * CommandIdIsCurrentCommandId
405 * --------------------------------
408 CommandIdIsCurrentCommandId(CommandId cid)
410 TransactionState s = CurrentTransactionState;
415 return (cid == s->commandId) ? true : false;
419 CommandIdGEScanCommandId(CommandId cid)
421 TransactionState s = CurrentTransactionState;
426 return (cid >= s->scanCommandId) ? true : false;
430 /* --------------------------------
431 * CommandCounterIncrement
432 * --------------------------------
435 CommandCounterIncrement(void)
437 CurrentTransactionStateData.commandId += 1;
438 if (CurrentTransactionStateData.commandId == FirstCommandId)
439 elog(ERROR, "You may only have 2^32-1 commands per transaction");
441 CurrentTransactionStateData.scanCommandId = CurrentTransactionStateData.commandId;
444 * make cache changes visible to me. AtCommit_LocalCache() instead of
445 * AtCommit_Cache() is called here.
447 AtCommit_LocalCache();
452 SetScanCommandId(CommandId savedId)
454 CurrentTransactionStateData.scanCommandId = savedId;
457 /* ----------------------------------------------------------------
458 * StartTransaction stuff
459 * ----------------------------------------------------------------
462 /* --------------------------------
464 * --------------------------------
469 AcceptInvalidationMessages();
472 /* --------------------------------
474 * --------------------------------
480 * at present, it is unknown to me what belongs here -cim 3/18/90
482 * There isn't anything to do at the start of a xact for locks. -mer
487 /* --------------------------------
489 * --------------------------------
495 * We shouldn't have any transaction contexts already.
497 Assert(TopTransactionContext == NULL);
498 Assert(TransactionCommandContext == NULL);
501 * Create a toplevel context for the transaction.
503 TopTransactionContext =
504 AllocSetContextCreate(TopMemoryContext,
505 "TopTransactionContext",
506 ALLOCSET_DEFAULT_MINSIZE,
507 ALLOCSET_DEFAULT_INITSIZE,
508 ALLOCSET_DEFAULT_MAXSIZE);
511 * Create a statement-level context and make it active.
513 TransactionCommandContext =
514 AllocSetContextCreate(TopTransactionContext,
515 "TransactionCommandContext",
516 ALLOCSET_DEFAULT_MINSIZE,
517 ALLOCSET_DEFAULT_INITSIZE,
518 ALLOCSET_DEFAULT_MAXSIZE);
519 MemoryContextSwitchTo(TransactionCommandContext);
523 /* ----------------------------------------------------------------
524 * CommitTransaction stuff
525 * ----------------------------------------------------------------
528 /* --------------------------------
529 * RecordTransactionCommit
531 * Note: the two calls to BufferManagerFlush() exist to ensure
532 * that data pages are written before log pages. These
533 * explicit calls should be replaced by a more efficient
534 * ordered page write scheme in the buffer manager
536 * --------------------------------
539 RecordTransactionCommit(void)
544 leak = BufferPoolCheckLeak();
546 xid = GetCurrentTransactionId();
549 * We needn't write anything in xlog or clog if the transaction was
550 * read-only, which we check by testing if it made any xlog entries.
552 if (MyLastRecPtr.xrecoff != 0)
555 xl_xact_commit xlrec;
560 xlrec.xtime = time(NULL);
561 rdata.buffer = InvalidBuffer;
562 rdata.data = (char *) (&xlrec);
563 rdata.len = SizeOfXactCommit;
566 START_CRIT_SECTION();
569 * SHOULD SAVE ARRAY OF RELFILENODE-s TO DROP
571 recptr = XLogInsert(RM_XACT_ID, XLOG_XACT_COMMIT, &rdata);
574 * Sleep before commit! So we can flush more than one commit
575 * records per single fsync. (The idea is some other backend may
576 * do the XLogFlush while we're sleeping. This needs work still,
577 * because on most Unixen, the minimum select() delay is 10msec or
578 * more, which is way too long.)
580 * We do not sleep if enableFsync is not turned on, nor if there are
581 * fewer than CommitSiblings other backends with active
584 if (CommitDelay > 0 && enableFsync &&
585 CountActiveBackends() >= CommitSiblings)
587 struct timeval delay;
590 delay.tv_usec = CommitDelay;
591 (void) select(0, NULL, NULL, NULL, &delay);
596 /* Break the chain of back-links in the XLOG records I output */
597 MyLastRecPtr.xrecoff = 0;
599 /* Mark the transaction committed in clog */
600 TransactionIdCommit(xid);
605 /* Show myself as out of the transaction in PROC array */
606 MyProc->logRec.xrecoff = 0;
609 ResetBufferPool(true);
613 /* --------------------------------
615 * --------------------------------
621 * Make catalog changes visible to all backends.
623 AtEOXactInvalidationMessages(true);
626 /* --------------------------------
627 * AtCommit_LocalCache
628 * --------------------------------
631 AtCommit_LocalCache(void)
634 * Make catalog changes visible to me for the next command.
636 CommandEndInvalidationMessages(true);
639 /* --------------------------------
641 * --------------------------------
647 * XXX What if ProcReleaseLocks fails? (race condition?)
649 * Then you're up a creek! -mer 5/24/92
651 ProcReleaseLocks(true);
654 /* --------------------------------
656 * --------------------------------
659 AtCommit_Memory(void)
662 * Now that we're "out" of a transaction, have the system allocate
663 * things in the top memory context instead of per-transaction
666 MemoryContextSwitchTo(TopMemoryContext);
669 * Release all transaction-local memory.
671 Assert(TopTransactionContext != NULL);
672 MemoryContextDelete(TopTransactionContext);
673 TopTransactionContext = NULL;
674 TransactionCommandContext = NULL;
677 /* ----------------------------------------------------------------
678 * AbortTransaction stuff
679 * ----------------------------------------------------------------
682 /* --------------------------------
683 * RecordTransactionAbort
684 * --------------------------------
687 RecordTransactionAbort(void)
689 TransactionId xid = GetCurrentTransactionId();
692 * We needn't write anything in xlog or clog if the transaction was
693 * read-only, which we check by testing if it made any xlog entries.
695 * Extra check here is to catch case that we aborted partway through
696 * RecordTransactionCommit ...
698 if (MyLastRecPtr.xrecoff != 0 && !TransactionIdDidCommit(xid))
704 xlrec.xtime = time(NULL);
705 rdata.buffer = InvalidBuffer;
706 rdata.data = (char *) (&xlrec);
707 rdata.len = SizeOfXactAbort;
710 START_CRIT_SECTION();
713 * SHOULD SAVE ARRAY OF RELFILENODE-s TO DROP
715 recptr = XLogInsert(RM_XACT_ID, XLOG_XACT_ABORT, &rdata);
718 * There's no need for XLogFlush here, since the default
719 * assumption would be that we aborted, anyway.
722 /* Mark the transaction aborted in clog */
723 TransactionIdAbort(xid);
728 /* Break the chain of back-links in the XLOG records I output */
729 MyLastRecPtr.xrecoff = 0;
730 /* Show myself as out of the transaction in PROC array */
731 MyProc->logRec.xrecoff = 0;
734 * Tell bufmgr and smgr to release resources.
736 ResetBufferPool(false); /* false -> is abort */
739 /* --------------------------------
741 * --------------------------------
746 RelationCacheAbort();
747 AtEOXactInvalidationMessages(false);
750 /* --------------------------------
752 * --------------------------------
758 * XXX What if ProcReleaseLocks() fails? (race condition?)
760 * Then you're up a creek without a paddle! -mer
762 ProcReleaseLocks(false);
766 /* --------------------------------
768 * --------------------------------
774 * Make sure we are in a valid context (not a child of
775 * TransactionCommandContext...). Note that it is possible for this
776 * code to be called when we aren't in a transaction at all; go
777 * directly to TopMemoryContext in that case.
779 if (TransactionCommandContext != NULL)
781 MemoryContextSwitchTo(TransactionCommandContext);
784 * We do not want to destroy transaction contexts yet, but it
785 * should be OK to delete any command-local memory.
787 MemoryContextResetAndDeleteChildren(TransactionCommandContext);
790 MemoryContextSwitchTo(TopMemoryContext);
794 /* ----------------------------------------------------------------
795 * CleanupTransaction stuff
796 * ----------------------------------------------------------------
799 /* --------------------------------
801 * --------------------------------
804 AtCleanup_Memory(void)
807 * Now that we're "out" of a transaction, have the system allocate
808 * things in the top memory context instead of per-transaction
811 MemoryContextSwitchTo(TopMemoryContext);
814 * Release all transaction-local memory.
816 if (TopTransactionContext != NULL)
817 MemoryContextDelete(TopTransactionContext);
818 TopTransactionContext = NULL;
819 TransactionCommandContext = NULL;
823 /* ----------------------------------------------------------------
825 * ----------------------------------------------------------------
828 /* --------------------------------
831 * --------------------------------
834 StartTransaction(void)
836 TransactionState s = CurrentTransactionState;
839 XactIsoLevel = DefaultXactIsoLevel;
842 * Check the current transaction state. If the transaction system is
843 * switched off, or if we're already in a transaction, do nothing.
844 * We're already in a transaction when the monitor sends a null
845 * command to the backend to flush the comm channel. This is a hacky
846 * fix to a communications problem, and we keep having to deal with it
847 * here. We should fix the comm channel code. mao 080891
849 if (s->state == TRANS_INPROGRESS)
853 * set the current transaction state information appropriately during
856 s->state = TRANS_START;
858 SetReindexProcessing(false);
861 * generate a new transaction id
863 s->transactionIdData = GetNewTransactionId();
865 XactLockTableInsert(s->transactionIdData);
868 * initialize current transaction state fields
870 s->commandId = FirstCommandId;
871 s->scanCommandId = FirstCommandId;
873 s->startTime = GetCurrentAbsoluteTime();
875 s->startTime = GetCurrentAbsoluteTimeUsec(&(s->startTimeUsec));
878 * initialize the various transaction subsystems
885 * Tell the trigger manager to we're starting a transaction
887 DeferredTriggerBeginXact();
890 * done with start processing, set current transaction state to "in
893 s->state = TRANS_INPROGRESS;
899 * Tell me if we are currently in progress
903 CurrentXactInProgress(void)
905 return CurrentTransactionState->state == TRANS_INPROGRESS;
909 /* --------------------------------
912 * --------------------------------
915 CommitTransaction(void)
917 TransactionState s = CurrentTransactionState;
920 * check the current transaction state
922 if (s->state != TRANS_INPROGRESS)
923 elog(WARNING, "CommitTransaction and not in in-progress state");
926 * Tell the trigger manager that this transaction is about to be
927 * committed. He'll invoke all trigger deferred until XACT before we
928 * really start on committing the transaction.
930 DeferredTriggerEndXact();
932 /* Prevent cancel/die interrupt while cleaning up */
936 * set the current transaction state information appropriately during
937 * the abort processing
939 s->state = TRANS_COMMIT;
942 * do commit processing
945 /* handle commit for large objects [ PA, 7/17/98 ] */
948 /* NOTIFY commit must also come before lower-level cleanup */
954 /* Here is where we really truly commit. */
955 RecordTransactionCommit();
958 * Let others know about no transaction in progress by me. Note that
959 * this must be done _before_ releasing locks we hold and _after_
960 * RecordTransactionCommit.
962 * LWLockAcquire(SInvalLock) is required: UPDATE with xid 0 is blocked by
963 * xid 1' UPDATE, xid 1 is doing commit while xid 2 gets snapshot - if
964 * xid 2' GetSnapshotData sees xid 1 as running then it must see xid 0
965 * as running as well or it will see two tuple versions - one deleted
966 * by xid 1 and one inserted by xid 0. See notes in GetSnapshotData.
968 if (MyProc != (PROC *) NULL)
970 /* Lock SInvalLock because that's what GetSnapshotData uses. */
971 LWLockAcquire(SInvalLock, LW_EXCLUSIVE);
972 MyProc->xid = InvalidTransactionId;
973 MyProc->xmin = InvalidTransactionId;
974 LWLockRelease(SInvalLock);
978 * This is all post-commit cleanup. Note that if an error is raised
979 * here, it's too late to abort the transaction. This should be just
980 * noncritical resource releasing.
983 RelationPurgeLocalRelation(true);
984 AtEOXact_temp_relations(true);
985 smgrDoPendingDeletes(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 AtEOXact_temp_relations(false);
1088 smgrDoPendingDeletes(false);
1096 AtEOXact_CatCache(false);
1101 SharedBufferChanged = false; /* safest place to do it */
1103 /* Count transaction abort in statistics collector */
1104 pgstat_count_xact_rollback();
1107 * State remains TRANS_ABORT until CleanupTransaction().
1109 RESUME_INTERRUPTS();
1112 /* --------------------------------
1113 * CleanupTransaction
1115 * --------------------------------
1118 CleanupTransaction(void)
1120 TransactionState s = CurrentTransactionState;
1123 * State should still be TRANS_ABORT from AbortTransaction().
1125 if (s->state != TRANS_ABORT)
1126 elog(FATAL, "CleanupTransaction and not in abort state");
1129 * do abort cleanup processing
1134 * done with abort processing, set current transaction state back to
1137 s->state = TRANS_DEFAULT;
1140 /* --------------------------------
1141 * StartTransactionCommand
1142 * --------------------------------
1145 StartTransactionCommand(void)
1147 TransactionState s = CurrentTransactionState;
1149 switch (s->blockState)
1152 * if we aren't in a transaction block, we just do our usual
1153 * start transaction.
1155 case TBLOCK_DEFAULT:
1160 * We should never experience this -- if we do it means the
1161 * BEGIN state was not changed in the previous
1162 * CommitTransactionCommand(). If we get it, we print a
1163 * warning and change to the in-progress state.
1166 elog(WARNING, "StartTransactionCommand: unexpected TBLOCK_BEGIN");
1167 s->blockState = TBLOCK_INPROGRESS;
1171 * This is the case when are somewhere in a transaction block
1172 * and about to start a new command. For now we do nothing
1173 * but someday we may do command-local resource
1176 case TBLOCK_INPROGRESS:
1180 * As with BEGIN, we should never experience this if we do it
1181 * means the END state was not changed in the previous
1182 * CommitTransactionCommand(). If we get it, we print a
1183 * warning, commit the transaction, start a new transaction
1184 * and change to the default state.
1187 elog(WARNING, "StartTransactionCommand: unexpected TBLOCK_END");
1188 s->blockState = TBLOCK_DEFAULT;
1189 CommitTransaction();
1194 * Here we are in the middle of a transaction block but one of
1195 * the commands caused an abort so we do nothing but remain in
1196 * the abort state. Eventually we will get to the "END
1197 * TRANSACTION" which will set things straight.
1203 * This means we somehow aborted and the last call to
1204 * CommitTransactionCommand() didn't clear the state so we
1205 * remain in the ENDABORT state and maybe next time we get to
1206 * CommitTransactionCommand() the state will get reset to
1209 case TBLOCK_ENDABORT:
1210 elog(WARNING, "StartTransactionCommand: unexpected TBLOCK_ENDABORT");
1215 * We must switch to TransactionCommandContext before returning. This
1216 * is already done if we called StartTransaction, otherwise not.
1218 Assert(TransactionCommandContext != NULL);
1219 MemoryContextSwitchTo(TransactionCommandContext);
1222 /* --------------------------------
1223 * CommitTransactionCommand
1224 * --------------------------------
1227 CommitTransactionCommand(void)
1229 TransactionState s = CurrentTransactionState;
1231 switch (s->blockState)
1234 * if we aren't in a transaction block, we just do our usual
1235 * transaction commit
1237 case TBLOCK_DEFAULT:
1238 CommitTransaction();
1242 * This is the case right after we get a "BEGIN TRANSACTION"
1243 * command, but the user hasn't done anything else yet, so we
1244 * change to the "transaction block in progress" state and
1248 s->blockState = TBLOCK_INPROGRESS;
1252 * This is the case when we have finished executing a command
1253 * someplace within a transaction block. We increment the
1254 * command counter and return. Someday we may free resources
1255 * local to the command.
1257 * That someday is today, at least for memory allocated in
1258 * TransactionCommandContext. - vadim 03/25/97
1260 case TBLOCK_INPROGRESS:
1261 CommandCounterIncrement();
1262 MemoryContextResetAndDeleteChildren(TransactionCommandContext);
1266 * This is the case when we just got the "END TRANSACTION"
1267 * statement, so we commit the transaction and go back to the
1271 CommitTransaction();
1272 s->blockState = TBLOCK_DEFAULT;
1276 * Here we are in the middle of a transaction block but one of
1277 * the commands caused an abort so we do nothing but remain in
1278 * the abort state. Eventually we will get to the "END
1279 * TRANSACTION" which will set things straight.
1285 * Here we were in an aborted transaction block which just
1286 * processed the "END TRANSACTION" command from the user, so
1287 * clean up and return to the default state.
1289 case TBLOCK_ENDABORT:
1290 CleanupTransaction();
1291 s->blockState = TBLOCK_DEFAULT;
1296 /* --------------------------------
1297 * AbortCurrentTransaction
1298 * --------------------------------
1301 AbortCurrentTransaction(void)
1303 TransactionState s = CurrentTransactionState;
1305 switch (s->blockState)
1308 * if we aren't in a transaction block, we just do the basic
1309 * abort & cleanup transaction.
1311 case TBLOCK_DEFAULT:
1313 CleanupTransaction();
1317 * If we are in the TBLOCK_BEGIN it means something screwed up
1318 * right after reading "BEGIN TRANSACTION" so we enter the
1319 * abort state. Eventually an "END TRANSACTION" will fix
1323 s->blockState = TBLOCK_ABORT;
1325 /* CleanupTransaction happens when we exit TBLOCK_ABORT */
1329 * This is the case when are somewhere in a transaction block
1330 * which aborted so we abort the transaction and set the ABORT
1331 * state. Eventually an "END TRANSACTION" will fix things and
1332 * restore us to a normal state.
1334 case TBLOCK_INPROGRESS:
1335 s->blockState = TBLOCK_ABORT;
1337 /* CleanupTransaction happens when we exit TBLOCK_ABORT */
1341 * Here, the system was fouled up just after the user wanted
1342 * to end the transaction block so we abort the transaction
1343 * and put us back into the default state.
1346 s->blockState = TBLOCK_DEFAULT;
1348 CleanupTransaction();
1352 * Here, we are already in an aborted transaction state and
1353 * are waiting for an "END TRANSACTION" to come along and lo
1354 * and behold, we abort again! So we just remain in the abort
1361 * Here we were in an aborted transaction block which just
1362 * processed the "END TRANSACTION" command but somehow aborted
1363 * again.. since we must have done the abort processing, we
1364 * clean up and return to the default state.
1366 case TBLOCK_ENDABORT:
1367 CleanupTransaction();
1368 s->blockState = TBLOCK_DEFAULT;
1373 /* ----------------------------------------------------------------
1374 * transaction block support
1375 * ----------------------------------------------------------------
1377 /* --------------------------------
1378 * BeginTransactionBlock
1379 * --------------------------------
1382 BeginTransactionBlock(void)
1384 TransactionState s = CurrentTransactionState;
1387 * check the current transaction state
1389 if (s->blockState != TBLOCK_DEFAULT)
1390 elog(WARNING, "BEGIN: already a transaction in progress");
1393 * set the current transaction block state information appropriately
1394 * during begin processing
1396 s->blockState = TBLOCK_BEGIN;
1399 * do begin processing
1403 * done with begin processing, set block state to inprogress
1405 s->blockState = TBLOCK_INPROGRESS;
1408 /* --------------------------------
1409 * EndTransactionBlock
1410 * --------------------------------
1413 EndTransactionBlock(void)
1415 TransactionState s = CurrentTransactionState;
1418 * check the current transaction state
1420 if (s->blockState == TBLOCK_INPROGRESS)
1423 * here we are in a transaction block which should commit when we
1424 * get to the upcoming CommitTransactionCommand() so we set the
1425 * state to "END". CommitTransactionCommand() will recognize this
1426 * and commit the transaction and return us to the default state
1428 s->blockState = TBLOCK_END;
1432 if (s->blockState == TBLOCK_ABORT)
1435 * here, we are in a transaction block which aborted and since the
1436 * AbortTransaction() was already done, we do whatever is needed
1437 * and change to the special "END ABORT" state. The upcoming
1438 * CommitTransactionCommand() will recognise this and then put us
1439 * back in the default state.
1441 s->blockState = TBLOCK_ENDABORT;
1446 * here, the user issued COMMIT when not inside a transaction. Issue a
1447 * WARNING and go to abort state. The upcoming call to
1448 * CommitTransactionCommand() will then put us back into the default
1451 elog(WARNING, "COMMIT: no transaction in progress");
1453 s->blockState = TBLOCK_ENDABORT;
1456 /* --------------------------------
1457 * AbortTransactionBlock
1458 * --------------------------------
1462 AbortTransactionBlock(void)
1464 TransactionState s = CurrentTransactionState;
1467 * check the current transaction state
1469 if (s->blockState == TBLOCK_INPROGRESS)
1472 * here we were inside a transaction block something screwed up
1473 * inside the system so we enter the abort state, do the abort
1474 * processing and then return. We remain in the abort state until
1475 * we see an END TRANSACTION command.
1477 s->blockState = TBLOCK_ABORT;
1483 * here, the user issued ABORT when not inside a transaction. Issue a
1484 * WARNING and go to abort state. The upcoming call to
1485 * CommitTransactionCommand() will then put us back into the default
1488 elog(WARNING, "ROLLBACK: no transaction in progress");
1490 s->blockState = TBLOCK_ENDABORT;
1494 /* --------------------------------
1495 * UserAbortTransactionBlock
1496 * --------------------------------
1499 UserAbortTransactionBlock(void)
1501 TransactionState s = CurrentTransactionState;
1504 * if the transaction has already been automatically aborted with an
1505 * error, and the user subsequently types 'abort', allow it. (the
1506 * behavior is the same as if they had typed 'end'.)
1508 if (s->blockState == TBLOCK_ABORT)
1510 s->blockState = TBLOCK_ENDABORT;
1514 if (s->blockState == TBLOCK_INPROGRESS)
1517 * here we were inside a transaction block and we got an abort
1518 * command from the user, so we move to the abort state, do the
1519 * abort processing and then change to the ENDABORT state so we
1520 * will end up in the default state after the upcoming
1521 * CommitTransactionCommand().
1523 s->blockState = TBLOCK_ABORT;
1525 s->blockState = TBLOCK_ENDABORT;
1530 * here, the user issued ABORT when not inside a transaction. Issue a
1531 * WARNING and go to abort state. The upcoming call to
1532 * CommitTransactionCommand() will then put us back into the default
1535 elog(WARNING, "ROLLBACK: no transaction in progress");
1537 s->blockState = TBLOCK_ENDABORT;
1540 /* --------------------------------
1541 * AbortOutOfAnyTransaction
1543 * This routine is provided for error recovery purposes. It aborts any
1544 * active transaction or transaction block, leaving the system in a known
1546 * --------------------------------
1549 AbortOutOfAnyTransaction(void)
1551 TransactionState s = CurrentTransactionState;
1554 * Get out of any low-level transaction
1559 case TRANS_INPROGRESS:
1561 /* In a transaction, so clean up */
1563 CleanupTransaction();
1566 /* AbortTransaction already done, still need Cleanup */
1567 CleanupTransaction();
1570 /* Not in a transaction, do nothing */
1575 * Now reset the high-level state
1577 s->blockState = TBLOCK_DEFAULT;
1581 IsTransactionBlock(void)
1583 TransactionState s = CurrentTransactionState;
1585 if (s->blockState == TBLOCK_INPROGRESS
1586 || s->blockState == TBLOCK_ABORT
1587 || s->blockState == TBLOCK_ENDABORT)
1594 xact_redo(XLogRecPtr lsn, XLogRecord *record)
1596 uint8 info = record->xl_info & ~XLR_INFO_MASK;
1598 if (info == XLOG_XACT_COMMIT)
1600 TransactionIdCommit(record->xl_xid);
1601 /* SHOULD REMOVE FILES OF ALL DROPPED RELATIONS */
1603 else if (info == XLOG_XACT_ABORT)
1605 TransactionIdAbort(record->xl_xid);
1606 /* SHOULD REMOVE FILES OF ALL FAILED-TO-BE-CREATED RELATIONS */
1609 elog(PANIC, "xact_redo: unknown op code %u", info);
1613 xact_undo(XLogRecPtr lsn, XLogRecord *record)
1615 uint8 info = record->xl_info & ~XLR_INFO_MASK;
1617 if (info == XLOG_XACT_COMMIT) /* shouldn't be called by XLOG */
1618 elog(PANIC, "xact_undo: can't undo committed xaction");
1619 else if (info != XLOG_XACT_ABORT)
1620 elog(PANIC, "xact_redo: unknown op code %u", info);
1624 xact_desc(char *buf, uint8 xl_info, char *rec)
1626 uint8 info = xl_info & ~XLR_INFO_MASK;
1628 if (info == XLOG_XACT_COMMIT)
1630 xl_xact_commit *xlrec = (xl_xact_commit *) rec;
1631 struct tm *tm = localtime(&xlrec->xtime);
1633 sprintf(buf + strlen(buf), "commit: %04u-%02u-%02u %02u:%02u:%02u",
1634 tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday,
1635 tm->tm_hour, tm->tm_min, tm->tm_sec);
1637 else if (info == XLOG_XACT_ABORT)
1639 xl_xact_abort *xlrec = (xl_xact_abort *) rec;
1640 struct tm *tm = localtime(&xlrec->xtime);
1642 sprintf(buf + strlen(buf), "abort: %04u-%02u-%02u %02u:%02u:%02u",
1643 tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday,
1644 tm->tm_hour, tm->tm_min, tm->tm_sec);
1647 strcat(buf, "UNKNOWN");
1651 XactPushRollback(void (*func) (void *), void *data)
1654 if (_RollbackFunc != NULL)
1655 elog(PANIC, "XactPushRollback: already installed");
1658 _RollbackFunc = func;
1659 _RollbackData = data;
1663 XactPopRollback(void)
1665 _RollbackFunc = NULL;