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.119 2002/03/31 06:26:29 tgl Exp $
14 * Transaction aborts can now occur two ways:
16 * 1) system dies from some internal cause (Assert, etc..)
19 * These two cases used to be treated identically, but now
20 * we need to distinguish them. Why? consider the following
25 * 1) user types BEGIN 1) user types BEGIN
26 * 2) user does something 2) user does something
27 * 3) user does not like what 3) system aborts for some reason
28 * she sees and types ABORT
30 * In case 1, we want to abort the transaction and return to the
31 * default state. In case 2, there may be more commands coming
32 * our way which are part of the same transaction block and we have
33 * to ignore these commands until we see an END transaction.
34 * (or an ABORT! --djm)
36 * Internal aborts are now handled by AbortTransactionBlock(), just as
37 * they always have been, and user aborts are now handled by
38 * UserAbortTransactionBlock(). Both of them rely on AbortTransaction()
39 * to do all the real work. The only difference is what state we
40 * enter after AbortTransaction() does its work:
42 * * AbortTransactionBlock() leaves us in TBLOCK_ABORT and
43 * * UserAbortTransactionBlock() leaves us in TBLOCK_ENDABORT
45 * Low-level transaction abort handling is divided into two phases:
46 * * AbortTransaction() executes as soon as we realize the transaction
47 * has failed. It should release all shared resources (locks etc)
48 * so that we do not delay other backends unnecessarily.
49 * * CleanupTransaction() executes when we finally see a user COMMIT
50 * or ROLLBACK command; it cleans things up and gets us out of
51 * the transaction internally. In particular, we mustn't destroy
52 * TransactionCommandContext until this point.
55 * This file is an attempt at a redesign of the upper layer
56 * of the V1 transaction system which was too poorly thought
57 * out to describe. This new system hopes to be both simpler
58 * in design, simpler to extend and needs to contain added
59 * functionality to solve problems beyond the scope of the V1
60 * system. (In particuler, communication of transaction
61 * information between parallel backends has to be supported)
63 * The essential aspects of the transaction system are:
65 * o transaction id generation
66 * o transaction log updating
68 * o cache invalidation
71 * Hence, the functional division of the transaction code is
72 * based on what of the above things need to be done during
73 * a start/commit/abort transaction. For instance, the
74 * routine AtCommit_Memory() takes care of all the memory
75 * cleanup stuff done at commit time.
77 * The code is layered as follows:
84 * are provided to do the lower level work like recording
85 * the transaction status in the log and doing memory cleanup.
86 * above these routines are another set of functions:
88 * StartTransactionCommand
89 * CommitTransactionCommand
90 * AbortCurrentTransaction
92 * These are the routines used in the postgres main processing
93 * loop. They are sensitive to the current transaction block state
94 * and make calls to the lower level routines appropriately.
96 * Support for transaction blocks is provided via the functions:
98 * StartTransactionBlock
99 * CommitTransactionBlock
100 * AbortTransactionBlock
102 * These are invoked only in responce to a user "BEGIN", "END",
103 * or "ABORT" command. The tricky part about these functions
104 * is that they are called within the postgres main loop, in between
105 * the StartTransactionCommand() and CommitTransactionCommand().
107 * For example, consider the following sequence of user commands:
110 * 2) retrieve (foo.all)
111 * 3) append foo (bar = baz)
114 * in the main processing loop, this results in the following
115 * transaction sequence:
117 * / StartTransactionCommand();
118 * 1) / ProcessUtility(); << begin
119 * \ StartTransactionBlock();
120 * \ CommitTransactionCommand();
122 * / StartTransactionCommand();
123 * 2) < ProcessQuery(); << retrieve (foo.all)
124 * \ CommitTransactionCommand();
126 * / StartTransactionCommand();
127 * 3) < ProcessQuery(); << append foo (bar = baz)
128 * \ CommitTransactionCommand();
130 * / StartTransactionCommand();
131 * 4) / ProcessUtility(); << end
132 * \ CommitTransactionBlock();
133 * \ CommitTransactionCommand();
135 * The point of this example is to demonstrate the need for
136 * StartTransactionCommand() and CommitTransactionCommand() to
137 * be state smart -- they should do nothing in between the calls
138 * to StartTransactionBlock() and EndTransactionBlock() and
139 * outside these calls they need to do normal start/commit
142 * Furthermore, suppose the "retrieve (foo.all)" caused an abort
143 * condition. We would then want to abort the transaction and
144 * ignore all subsequent commands up to the "end".
147 *-------------------------------------------------------------------------
151 * Large object clean up added in CommitTransaction() to prevent buffer leaks.
153 * [PA] is Pascal André <andre@via.ecp.fr>
155 #include "postgres.h"
158 #include <sys/time.h>
160 #include "access/gistscan.h"
161 #include "access/hash.h"
162 #include "access/nbtree.h"
163 #include "access/rtree.h"
164 #include "access/xact.h"
165 #include "catalog/heap.h"
166 #include "catalog/index.h"
167 #include "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"
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 only need to log the commit in xlog and clog if the transaction made
549 * any transaction-controlled XLOG entries. (Otherwise, its XID appears
550 * nowhere in permanent storage, so no one will ever care if it
551 * committed.) However, we must flush XLOG to disk if we made any XLOG
552 * entries, whether in or out of transaction control. For example, if we
553 * reported a nextval() result to the client, this ensures that any XLOG
554 * record generated by nextval will hit the disk before we report the
555 * transaction committed.
557 if (MyXactMadeXLogEntry)
563 START_CRIT_SECTION();
565 if (MyLastRecPtr.xrecoff != 0)
567 /* Need to emit a commit record */
569 xl_xact_commit xlrec;
571 xlrec.xtime = time(NULL);
572 rdata.buffer = InvalidBuffer;
573 rdata.data = (char *) (&xlrec);
574 rdata.len = SizeOfXactCommit;
578 * XXX SHOULD SAVE ARRAY OF RELFILENODE-s TO DROP
580 recptr = XLogInsert(RM_XACT_ID, XLOG_XACT_COMMIT, &rdata);
584 /* Just flush through last record written by me */
585 recptr = ProcLastRecEnd;
589 * Sleep before flush! So we can flush more than one commit
590 * records per single fsync. (The idea is some other backend may
591 * do the XLogFlush while we're sleeping. This needs work still,
592 * because on most Unixen, the minimum select() delay is 10msec or
593 * more, which is way too long.)
595 * We do not sleep if enableFsync is not turned on, nor if there are
596 * fewer than CommitSiblings other backends with active
599 if (CommitDelay > 0 && enableFsync &&
600 CountActiveBackends() >= CommitSiblings)
602 struct timeval delay;
605 delay.tv_usec = CommitDelay;
606 (void) select(0, NULL, NULL, NULL, &delay);
611 /* Mark the transaction committed in clog, if needed */
612 if (MyLastRecPtr.xrecoff != 0)
613 TransactionIdCommit(xid);
618 /* Break the chain of back-links in the XLOG records I output */
619 MyLastRecPtr.xrecoff = 0;
620 MyXactMadeXLogEntry = false;
622 /* Show myself as out of the transaction in PROC array */
623 MyProc->logRec.xrecoff = 0;
626 ResetBufferPool(true);
630 /* --------------------------------
632 * --------------------------------
638 * Make catalog changes visible to all backends.
640 AtEOXactInvalidationMessages(true);
643 /* --------------------------------
644 * AtCommit_LocalCache
645 * --------------------------------
648 AtCommit_LocalCache(void)
651 * Make catalog changes visible to me for the next command.
653 CommandEndInvalidationMessages(true);
656 /* --------------------------------
658 * --------------------------------
664 * XXX What if ProcReleaseLocks fails? (race condition?)
666 * Then you're up a creek! -mer 5/24/92
668 ProcReleaseLocks(true);
671 /* --------------------------------
673 * --------------------------------
676 AtCommit_Memory(void)
679 * Now that we're "out" of a transaction, have the system allocate
680 * things in the top memory context instead of per-transaction
683 MemoryContextSwitchTo(TopMemoryContext);
686 * Release all transaction-local memory.
688 Assert(TopTransactionContext != NULL);
689 MemoryContextDelete(TopTransactionContext);
690 TopTransactionContext = NULL;
691 TransactionCommandContext = NULL;
694 /* ----------------------------------------------------------------
695 * AbortTransaction stuff
696 * ----------------------------------------------------------------
699 /* --------------------------------
700 * RecordTransactionAbort
701 * --------------------------------
704 RecordTransactionAbort(void)
706 TransactionId xid = GetCurrentTransactionId();
709 * We only need to log the abort in xlog and clog if the transaction made
710 * any transaction-controlled XLOG entries. (Otherwise, its XID appears
711 * nowhere in permanent storage, so no one will ever care if it
712 * committed.) We do not flush XLOG to disk in any case, since the
713 * default assumption after a crash would be that we aborted, anyway.
715 * Extra check here is to catch case that we aborted partway through
716 * RecordTransactionCommit ...
718 if (MyLastRecPtr.xrecoff != 0 && !TransactionIdDidCommit(xid))
724 xlrec.xtime = time(NULL);
725 rdata.buffer = InvalidBuffer;
726 rdata.data = (char *) (&xlrec);
727 rdata.len = SizeOfXactAbort;
730 START_CRIT_SECTION();
733 * SHOULD SAVE ARRAY OF RELFILENODE-s TO DROP
735 recptr = XLogInsert(RM_XACT_ID, XLOG_XACT_ABORT, &rdata);
737 /* Mark the transaction aborted in clog */
738 TransactionIdAbort(xid);
743 /* Break the chain of back-links in the XLOG records I output */
744 MyLastRecPtr.xrecoff = 0;
745 MyXactMadeXLogEntry = false;
747 /* Show myself as out of the transaction in PROC array */
748 MyProc->logRec.xrecoff = 0;
751 * Tell bufmgr and smgr to release resources.
753 ResetBufferPool(false); /* false -> is abort */
756 /* --------------------------------
758 * --------------------------------
763 RelationCacheAbort();
764 AtEOXactInvalidationMessages(false);
767 /* --------------------------------
769 * --------------------------------
775 * XXX What if ProcReleaseLocks() fails? (race condition?)
777 * Then you're up a creek without a paddle! -mer
779 ProcReleaseLocks(false);
783 /* --------------------------------
785 * --------------------------------
791 * Make sure we are in a valid context (not a child of
792 * TransactionCommandContext...). Note that it is possible for this
793 * code to be called when we aren't in a transaction at all; go
794 * directly to TopMemoryContext in that case.
796 if (TransactionCommandContext != NULL)
798 MemoryContextSwitchTo(TransactionCommandContext);
801 * We do not want to destroy transaction contexts yet, but it
802 * should be OK to delete any command-local memory.
804 MemoryContextResetAndDeleteChildren(TransactionCommandContext);
807 MemoryContextSwitchTo(TopMemoryContext);
811 /* ----------------------------------------------------------------
812 * CleanupTransaction stuff
813 * ----------------------------------------------------------------
816 /* --------------------------------
818 * --------------------------------
821 AtCleanup_Memory(void)
824 * Now that we're "out" of a transaction, have the system allocate
825 * things in the top memory context instead of per-transaction
828 MemoryContextSwitchTo(TopMemoryContext);
831 * Release all transaction-local memory.
833 if (TopTransactionContext != NULL)
834 MemoryContextDelete(TopTransactionContext);
835 TopTransactionContext = NULL;
836 TransactionCommandContext = NULL;
840 /* ----------------------------------------------------------------
842 * ----------------------------------------------------------------
845 /* --------------------------------
848 * --------------------------------
851 StartTransaction(void)
853 TransactionState s = CurrentTransactionState;
856 XactIsoLevel = DefaultXactIsoLevel;
859 * Check the current transaction state. If the transaction system is
860 * switched off, or if we're already in a transaction, do nothing.
861 * We're already in a transaction when the monitor sends a null
862 * command to the backend to flush the comm channel. This is a hacky
863 * fix to a communications problem, and we keep having to deal with it
864 * here. We should fix the comm channel code. mao 080891
866 if (s->state == TRANS_INPROGRESS)
870 * set the current transaction state information appropriately during
873 s->state = TRANS_START;
875 SetReindexProcessing(false);
878 * generate a new transaction id
880 s->transactionIdData = GetNewTransactionId();
882 XactLockTableInsert(s->transactionIdData);
885 * initialize current transaction state fields
887 s->commandId = FirstCommandId;
888 s->scanCommandId = FirstCommandId;
890 s->startTime = GetCurrentAbsoluteTime();
892 s->startTime = GetCurrentAbsoluteTimeUsec(&(s->startTimeUsec));
895 * initialize the various transaction subsystems
902 * Tell the trigger manager to we're starting a transaction
904 DeferredTriggerBeginXact();
907 * done with start processing, set current transaction state to "in
910 s->state = TRANS_INPROGRESS;
916 * Tell me if we are currently in progress
920 CurrentXactInProgress(void)
922 return CurrentTransactionState->state == TRANS_INPROGRESS;
926 /* --------------------------------
929 * --------------------------------
932 CommitTransaction(void)
934 TransactionState s = CurrentTransactionState;
937 * check the current transaction state
939 if (s->state != TRANS_INPROGRESS)
940 elog(WARNING, "CommitTransaction and not in in-progress state");
943 * Tell the trigger manager that this transaction is about to be
944 * committed. He'll invoke all trigger deferred until XACT before we
945 * really start on committing the transaction.
947 DeferredTriggerEndXact();
949 /* Prevent cancel/die interrupt while cleaning up */
953 * set the current transaction state information appropriately during
954 * the abort processing
956 s->state = TRANS_COMMIT;
959 * do commit processing
962 /* handle commit for large objects [ PA, 7/17/98 ] */
965 /* NOTIFY commit must also come before lower-level cleanup */
971 /* Here is where we really truly commit. */
972 RecordTransactionCommit();
975 * Let others know about no transaction in progress by me. Note that
976 * this must be done _before_ releasing locks we hold and _after_
977 * RecordTransactionCommit.
979 * LWLockAcquire(SInvalLock) is required: UPDATE with xid 0 is blocked by
980 * xid 1' UPDATE, xid 1 is doing commit while xid 2 gets snapshot - if
981 * xid 2' GetSnapshotData sees xid 1 as running then it must see xid 0
982 * as running as well or it will see two tuple versions - one deleted
983 * by xid 1 and one inserted by xid 0. See notes in GetSnapshotData.
985 if (MyProc != (PROC *) NULL)
987 /* Lock SInvalLock because that's what GetSnapshotData uses. */
988 LWLockAcquire(SInvalLock, LW_EXCLUSIVE);
989 MyProc->xid = InvalidTransactionId;
990 MyProc->xmin = InvalidTransactionId;
991 LWLockRelease(SInvalLock);
995 * This is all post-commit cleanup. Note that if an error is raised
996 * here, it's too late to abort the transaction. This should be just
997 * noncritical resource releasing.
1000 RelationPurgeLocalRelation(true);
1001 smgrDoPendingDeletes(true);
1010 AtEOXact_CatCache(true);
1014 SharedBufferChanged = false; /* safest place to do it */
1016 /* Count transaction commit in statistics collector */
1017 pgstat_count_xact_commit();
1020 * done with commit processing, set current transaction state back to
1023 s->state = TRANS_DEFAULT;
1025 RESUME_INTERRUPTS();
1028 /* --------------------------------
1031 * --------------------------------
1034 AbortTransaction(void)
1036 TransactionState s = CurrentTransactionState;
1038 /* Prevent cancel/die interrupt while cleaning up */
1042 * Release any LW locks we might be holding as quickly as possible.
1043 * (Regular locks, however, must be held till we finish aborting.)
1044 * Releasing LW locks is critical since we might try to grab them
1045 * again while cleaning up!
1049 /* Clean up buffer I/O and buffer context locks, too */
1054 * Also clean up any open wait for lock, since the lock manager will
1055 * choke if we try to wait for another lock before doing this.
1060 * check the current transaction state
1062 if (s->state != TRANS_INPROGRESS)
1063 elog(WARNING, "AbortTransaction and not in in-progress state");
1066 * set the current transaction state information appropriately during
1067 * the abort processing
1069 s->state = TRANS_ABORT;
1072 * Reset user id which might have been changed transiently
1074 SetUserId(GetSessionUserId());
1077 * do abort processing
1079 DeferredTriggerAbortXact();
1080 lo_commit(false); /* 'false' means it's abort */
1085 /* Advertise the fact that we aborted in pg_clog. */
1086 RecordTransactionAbort();
1089 * Let others know about no transaction in progress by me. Note that
1090 * this must be done _before_ releasing locks we hold and _after_
1091 * RecordTransactionAbort.
1093 if (MyProc != (PROC *) NULL)
1095 /* Lock SInvalLock because that's what GetSnapshotData uses. */
1096 LWLockAcquire(SInvalLock, LW_EXCLUSIVE);
1097 MyProc->xid = InvalidTransactionId;
1098 MyProc->xmin = InvalidTransactionId;
1099 LWLockRelease(SInvalLock);
1102 RelationPurgeLocalRelation(false);
1103 smgrDoPendingDeletes(false);
1111 AtEOXact_CatCache(false);
1116 SharedBufferChanged = false; /* safest place to do it */
1118 /* Count transaction abort in statistics collector */
1119 pgstat_count_xact_rollback();
1122 * State remains TRANS_ABORT until CleanupTransaction().
1124 RESUME_INTERRUPTS();
1127 /* --------------------------------
1128 * CleanupTransaction
1130 * --------------------------------
1133 CleanupTransaction(void)
1135 TransactionState s = CurrentTransactionState;
1138 * State should still be TRANS_ABORT from AbortTransaction().
1140 if (s->state != TRANS_ABORT)
1141 elog(FATAL, "CleanupTransaction and not in abort state");
1144 * do abort cleanup processing
1149 * done with abort processing, set current transaction state back to
1152 s->state = TRANS_DEFAULT;
1155 /* --------------------------------
1156 * StartTransactionCommand
1157 * --------------------------------
1160 StartTransactionCommand(void)
1162 TransactionState s = CurrentTransactionState;
1164 switch (s->blockState)
1167 * if we aren't in a transaction block, we just do our usual
1168 * start transaction.
1170 case TBLOCK_DEFAULT:
1175 * We should never experience this -- if we do it means the
1176 * BEGIN state was not changed in the previous
1177 * CommitTransactionCommand(). If we get it, we print a
1178 * warning and change to the in-progress state.
1181 elog(WARNING, "StartTransactionCommand: unexpected TBLOCK_BEGIN");
1182 s->blockState = TBLOCK_INPROGRESS;
1186 * This is the case when are somewhere in a transaction block
1187 * and about to start a new command. For now we do nothing
1188 * but someday we may do command-local resource
1191 case TBLOCK_INPROGRESS:
1195 * As with BEGIN, we should never experience this if we do it
1196 * means the END state was not changed in the previous
1197 * CommitTransactionCommand(). If we get it, we print a
1198 * warning, commit the transaction, start a new transaction
1199 * and change to the default state.
1202 elog(WARNING, "StartTransactionCommand: unexpected TBLOCK_END");
1203 s->blockState = TBLOCK_DEFAULT;
1204 CommitTransaction();
1209 * Here we are in the middle of a transaction block but one of
1210 * the commands caused an abort so we do nothing but remain in
1211 * the abort state. Eventually we will get to the "END
1212 * TRANSACTION" which will set things straight.
1218 * This means we somehow aborted and the last call to
1219 * CommitTransactionCommand() didn't clear the state so we
1220 * remain in the ENDABORT state and maybe next time we get to
1221 * CommitTransactionCommand() the state will get reset to
1224 case TBLOCK_ENDABORT:
1225 elog(WARNING, "StartTransactionCommand: unexpected TBLOCK_ENDABORT");
1230 * We must switch to TransactionCommandContext before returning. This
1231 * is already done if we called StartTransaction, otherwise not.
1233 Assert(TransactionCommandContext != NULL);
1234 MemoryContextSwitchTo(TransactionCommandContext);
1237 /* --------------------------------
1238 * CommitTransactionCommand
1239 * --------------------------------
1242 CommitTransactionCommand(void)
1244 TransactionState s = CurrentTransactionState;
1246 switch (s->blockState)
1249 * if we aren't in a transaction block, we just do our usual
1250 * transaction commit
1252 case TBLOCK_DEFAULT:
1253 CommitTransaction();
1257 * This is the case right after we get a "BEGIN TRANSACTION"
1258 * command, but the user hasn't done anything else yet, so we
1259 * change to the "transaction block in progress" state and
1263 s->blockState = TBLOCK_INPROGRESS;
1267 * This is the case when we have finished executing a command
1268 * someplace within a transaction block. We increment the
1269 * command counter and return. Someday we may free resources
1270 * local to the command.
1272 * That someday is today, at least for memory allocated in
1273 * TransactionCommandContext. - vadim 03/25/97
1275 case TBLOCK_INPROGRESS:
1276 CommandCounterIncrement();
1277 MemoryContextResetAndDeleteChildren(TransactionCommandContext);
1281 * This is the case when we just got the "END TRANSACTION"
1282 * statement, so we commit the transaction and go back to the
1286 CommitTransaction();
1287 s->blockState = TBLOCK_DEFAULT;
1291 * Here we are in the middle of a transaction block but one of
1292 * the commands caused an abort so we do nothing but remain in
1293 * the abort state. Eventually we will get to the "END
1294 * TRANSACTION" which will set things straight.
1300 * Here we were in an aborted transaction block which just
1301 * processed the "END TRANSACTION" command from the user, so
1302 * clean up and return to the default state.
1304 case TBLOCK_ENDABORT:
1305 CleanupTransaction();
1306 s->blockState = TBLOCK_DEFAULT;
1311 /* --------------------------------
1312 * AbortCurrentTransaction
1313 * --------------------------------
1316 AbortCurrentTransaction(void)
1318 TransactionState s = CurrentTransactionState;
1320 switch (s->blockState)
1323 * if we aren't in a transaction block, we just do the basic
1324 * abort & cleanup transaction.
1326 case TBLOCK_DEFAULT:
1328 CleanupTransaction();
1332 * If we are in the TBLOCK_BEGIN it means something screwed up
1333 * right after reading "BEGIN TRANSACTION" so we enter the
1334 * abort state. Eventually an "END TRANSACTION" will fix
1338 s->blockState = TBLOCK_ABORT;
1340 /* CleanupTransaction happens when we exit TBLOCK_ABORT */
1344 * This is the case when are somewhere in a transaction block
1345 * which aborted so we abort the transaction and set the ABORT
1346 * state. Eventually an "END TRANSACTION" will fix things and
1347 * restore us to a normal state.
1349 case TBLOCK_INPROGRESS:
1350 s->blockState = TBLOCK_ABORT;
1352 /* CleanupTransaction happens when we exit TBLOCK_ABORT */
1356 * Here, the system was fouled up just after the user wanted
1357 * to end the transaction block so we abort the transaction
1358 * and put us back into the default state.
1361 s->blockState = TBLOCK_DEFAULT;
1363 CleanupTransaction();
1367 * Here, we are already in an aborted transaction state and
1368 * are waiting for an "END TRANSACTION" to come along and lo
1369 * and behold, we abort again! So we just remain in the abort
1376 * Here we were in an aborted transaction block which just
1377 * processed the "END TRANSACTION" command but somehow aborted
1378 * again.. since we must have done the abort processing, we
1379 * clean up and return to the default state.
1381 case TBLOCK_ENDABORT:
1382 CleanupTransaction();
1383 s->blockState = TBLOCK_DEFAULT;
1388 /* ----------------------------------------------------------------
1389 * transaction block support
1390 * ----------------------------------------------------------------
1392 /* --------------------------------
1393 * BeginTransactionBlock
1394 * --------------------------------
1397 BeginTransactionBlock(void)
1399 TransactionState s = CurrentTransactionState;
1402 * check the current transaction state
1404 if (s->blockState != TBLOCK_DEFAULT)
1405 elog(WARNING, "BEGIN: already a transaction in progress");
1408 * set the current transaction block state information appropriately
1409 * during begin processing
1411 s->blockState = TBLOCK_BEGIN;
1414 * do begin processing
1418 * done with begin processing, set block state to inprogress
1420 s->blockState = TBLOCK_INPROGRESS;
1423 /* --------------------------------
1424 * EndTransactionBlock
1425 * --------------------------------
1428 EndTransactionBlock(void)
1430 TransactionState s = CurrentTransactionState;
1433 * check the current transaction state
1435 if (s->blockState == TBLOCK_INPROGRESS)
1438 * here we are in a transaction block which should commit when we
1439 * get to the upcoming CommitTransactionCommand() so we set the
1440 * state to "END". CommitTransactionCommand() will recognize this
1441 * and commit the transaction and return us to the default state
1443 s->blockState = TBLOCK_END;
1447 if (s->blockState == TBLOCK_ABORT)
1450 * here, we are in a transaction block which aborted and since the
1451 * AbortTransaction() was already done, we do whatever is needed
1452 * and change to the special "END ABORT" state. The upcoming
1453 * CommitTransactionCommand() will recognise this and then put us
1454 * back in the default state.
1456 s->blockState = TBLOCK_ENDABORT;
1461 * here, the user issued COMMIT when not inside a transaction. Issue a
1462 * WARNING and go to abort state. The upcoming call to
1463 * CommitTransactionCommand() will then put us back into the default
1466 elog(WARNING, "COMMIT: no transaction in progress");
1468 s->blockState = TBLOCK_ENDABORT;
1471 /* --------------------------------
1472 * AbortTransactionBlock
1473 * --------------------------------
1477 AbortTransactionBlock(void)
1479 TransactionState s = CurrentTransactionState;
1482 * check the current transaction state
1484 if (s->blockState == TBLOCK_INPROGRESS)
1487 * here we were inside a transaction block something screwed up
1488 * inside the system so we enter the abort state, do the abort
1489 * processing and then return. We remain in the abort state until
1490 * we see an END TRANSACTION command.
1492 s->blockState = TBLOCK_ABORT;
1498 * here, the user issued ABORT when not inside a transaction. Issue a
1499 * WARNING and go to abort state. The upcoming call to
1500 * CommitTransactionCommand() will then put us back into the default
1503 elog(WARNING, "ROLLBACK: no transaction in progress");
1505 s->blockState = TBLOCK_ENDABORT;
1509 /* --------------------------------
1510 * UserAbortTransactionBlock
1511 * --------------------------------
1514 UserAbortTransactionBlock(void)
1516 TransactionState s = CurrentTransactionState;
1519 * if the transaction has already been automatically aborted with an
1520 * error, and the user subsequently types 'abort', allow it. (the
1521 * behavior is the same as if they had typed 'end'.)
1523 if (s->blockState == TBLOCK_ABORT)
1525 s->blockState = TBLOCK_ENDABORT;
1529 if (s->blockState == TBLOCK_INPROGRESS)
1532 * here we were inside a transaction block and we got an abort
1533 * command from the user, so we move to the abort state, do the
1534 * abort processing and then change to the ENDABORT state so we
1535 * will end up in the default state after the upcoming
1536 * CommitTransactionCommand().
1538 s->blockState = TBLOCK_ABORT;
1540 s->blockState = TBLOCK_ENDABORT;
1545 * here, the user issued ABORT when not inside a transaction. Issue a
1546 * WARNING and go to abort state. The upcoming call to
1547 * CommitTransactionCommand() will then put us back into the default
1550 elog(WARNING, "ROLLBACK: no transaction in progress");
1552 s->blockState = TBLOCK_ENDABORT;
1555 /* --------------------------------
1556 * AbortOutOfAnyTransaction
1558 * This routine is provided for error recovery purposes. It aborts any
1559 * active transaction or transaction block, leaving the system in a known
1561 * --------------------------------
1564 AbortOutOfAnyTransaction(void)
1566 TransactionState s = CurrentTransactionState;
1569 * Get out of any low-level transaction
1574 case TRANS_INPROGRESS:
1576 /* In a transaction, so clean up */
1578 CleanupTransaction();
1581 /* AbortTransaction already done, still need Cleanup */
1582 CleanupTransaction();
1585 /* Not in a transaction, do nothing */
1590 * Now reset the high-level state
1592 s->blockState = TBLOCK_DEFAULT;
1596 IsTransactionBlock(void)
1598 TransactionState s = CurrentTransactionState;
1600 if (s->blockState == TBLOCK_INPROGRESS
1601 || s->blockState == TBLOCK_ABORT
1602 || s->blockState == TBLOCK_ENDABORT)
1609 xact_redo(XLogRecPtr lsn, XLogRecord *record)
1611 uint8 info = record->xl_info & ~XLR_INFO_MASK;
1613 if (info == XLOG_XACT_COMMIT)
1615 TransactionIdCommit(record->xl_xid);
1616 /* SHOULD REMOVE FILES OF ALL DROPPED RELATIONS */
1618 else if (info == XLOG_XACT_ABORT)
1620 TransactionIdAbort(record->xl_xid);
1621 /* SHOULD REMOVE FILES OF ALL FAILED-TO-BE-CREATED RELATIONS */
1624 elog(PANIC, "xact_redo: unknown op code %u", info);
1628 xact_undo(XLogRecPtr lsn, XLogRecord *record)
1630 uint8 info = record->xl_info & ~XLR_INFO_MASK;
1632 if (info == XLOG_XACT_COMMIT) /* shouldn't be called by XLOG */
1633 elog(PANIC, "xact_undo: can't undo committed xaction");
1634 else if (info != XLOG_XACT_ABORT)
1635 elog(PANIC, "xact_redo: unknown op code %u", info);
1639 xact_desc(char *buf, uint8 xl_info, char *rec)
1641 uint8 info = xl_info & ~XLR_INFO_MASK;
1643 if (info == XLOG_XACT_COMMIT)
1645 xl_xact_commit *xlrec = (xl_xact_commit *) rec;
1646 struct tm *tm = localtime(&xlrec->xtime);
1648 sprintf(buf + strlen(buf), "commit: %04u-%02u-%02u %02u:%02u:%02u",
1649 tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday,
1650 tm->tm_hour, tm->tm_min, tm->tm_sec);
1652 else if (info == XLOG_XACT_ABORT)
1654 xl_xact_abort *xlrec = (xl_xact_abort *) rec;
1655 struct tm *tm = localtime(&xlrec->xtime);
1657 sprintf(buf + strlen(buf), "abort: %04u-%02u-%02u %02u:%02u:%02u",
1658 tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday,
1659 tm->tm_hour, tm->tm_min, tm->tm_sec);
1662 strcat(buf, "UNKNOWN");
1666 XactPushRollback(void (*func) (void *), void *data)
1669 if (_RollbackFunc != NULL)
1670 elog(PANIC, "XactPushRollback: already installed");
1673 _RollbackFunc = func;
1674 _RollbackData = data;
1678 XactPopRollback(void)
1680 _RollbackFunc = NULL;