1 /*-------------------------------------------------------------------------
4 * top level transaction system support routines
6 * Portions Copyright (c) 1996-2002, 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.130 2002/08/06 02:36:33 tgl Exp $
14 * Transaction aborts can now occur two ways:
16 * 1) system dies from some internal cause (Assert, etc..)
19 * These two cases used to be treated identically, but now
20 * we need to distinguish them. Why? consider the following
25 * 1) user types BEGIN 1) user types BEGIN
26 * 2) user does something 2) user does something
27 * 3) user does not like what 3) system aborts for some reason
28 * she sees and types ABORT
30 * In case 1, we want to abort the transaction and return to the
31 * default state. In case 2, there may be more commands coming
32 * our way which are part of the same transaction block and we have
33 * to ignore these commands until we see an END transaction.
34 * (or an ABORT! --djm)
36 * Internal aborts are now handled by AbortTransactionBlock(), just as
37 * they always have been, and user aborts are now handled by
38 * UserAbortTransactionBlock(). Both of them rely on AbortTransaction()
39 * to do all the real work. The only difference is what state we
40 * enter after AbortTransaction() does its work:
42 * * AbortTransactionBlock() leaves us in TBLOCK_ABORT and
43 * * UserAbortTransactionBlock() leaves us in TBLOCK_ENDABORT
45 * Low-level transaction abort handling is divided into two phases:
46 * * AbortTransaction() executes as soon as we realize the transaction
47 * has failed. It should release all shared resources (locks etc)
48 * so that we do not delay other backends unnecessarily.
49 * * CleanupTransaction() executes when we finally see a user COMMIT
50 * or ROLLBACK command; it cleans things up and gets us out of
51 * the transaction internally. In particular, we mustn't destroy
52 * TransactionCommandContext until this point.
55 * This file is an attempt at a redesign of the upper layer
56 * of the V1 transaction system which was too poorly thought
57 * out to describe. This new system hopes to be both simpler
58 * in design, simpler to extend and needs to contain added
59 * functionality to solve problems beyond the scope of the V1
60 * system. (In particuler, communication of transaction
61 * information between parallel backends has to be supported)
63 * The essential aspects of the transaction system are:
65 * o transaction id generation
66 * o transaction log updating
68 * o cache invalidation
71 * Hence, the functional division of the transaction code is
72 * based on what of the above things need to be done during
73 * a start/commit/abort transaction. For instance, the
74 * routine AtCommit_Memory() takes care of all the memory
75 * cleanup stuff done at commit time.
77 * The code is layered as follows:
84 * are provided to do the lower level work like recording
85 * the transaction status in the log and doing memory cleanup.
86 * above these routines are another set of functions:
88 * StartTransactionCommand
89 * CommitTransactionCommand
90 * AbortCurrentTransaction
92 * These are the routines used in the postgres main processing
93 * loop. They are sensitive to the current transaction block state
94 * and make calls to the lower level routines appropriately.
96 * Support for transaction blocks is provided via the functions:
98 * StartTransactionBlock
99 * CommitTransactionBlock
100 * AbortTransactionBlock
102 * These are invoked only in responce to a user "BEGIN", "END",
103 * or "ABORT" command. The tricky part about these functions
104 * is that they are called within the postgres main loop, in between
105 * the StartTransactionCommand() and CommitTransactionCommand().
107 * For example, consider the following sequence of user commands:
110 * 2) retrieve (foo.all)
111 * 3) append foo (bar = baz)
114 * in the main processing loop, this results in the following
115 * transaction sequence:
117 * / StartTransactionCommand();
118 * 1) / ProcessUtility(); << begin
119 * \ StartTransactionBlock();
120 * \ CommitTransactionCommand();
122 * / StartTransactionCommand();
123 * 2) < ProcessQuery(); << retrieve (foo.all)
124 * \ CommitTransactionCommand();
126 * / StartTransactionCommand();
127 * 3) < ProcessQuery(); << append foo (bar = baz)
128 * \ CommitTransactionCommand();
130 * / StartTransactionCommand();
131 * 4) / ProcessUtility(); << end
132 * \ CommitTransactionBlock();
133 * \ CommitTransactionCommand();
135 * The point of this example is to demonstrate the need for
136 * StartTransactionCommand() and CommitTransactionCommand() to
137 * be state smart -- they should do nothing in between the calls
138 * to StartTransactionBlock() and EndTransactionBlock() and
139 * outside these calls they need to do normal start/commit
142 * Furthermore, suppose the "retrieve (foo.all)" caused an abort
143 * condition. We would then want to abort the transaction and
144 * ignore all subsequent commands up to the "end".
147 *-------------------------------------------------------------------------
151 * Large object clean up added in CommitTransaction() to prevent buffer leaks.
153 * [PA] is Pascal André <andre@via.ecp.fr>
155 #include "postgres.h"
158 #include <sys/time.h>
160 #include "access/gistscan.h"
161 #include "access/hash.h"
162 #include "access/nbtree.h"
163 #include "access/rtree.h"
164 #include "access/xact.h"
165 #include "catalog/heap.h"
166 #include "catalog/index.h"
167 #include "catalog/namespace.h"
168 #include "commands/async.h"
169 #include "commands/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/guc.h"
177 #include "utils/inval.h"
178 #include "utils/memutils.h"
179 #include "utils/portal.h"
180 #include "utils/catcache.h"
181 #include "utils/relcache.h"
185 static void AbortTransaction(void);
186 static void AtAbort_Cache(void);
187 static void AtAbort_Locks(void);
188 static void AtAbort_Memory(void);
189 static void AtCleanup_Memory(void);
190 static void AtCommit_Cache(void);
191 static void AtCommit_LocalCache(void);
192 static void AtCommit_Locks(void);
193 static void AtCommit_Memory(void);
194 static void AtStart_Cache(void);
195 static void AtStart_Locks(void);
196 static void AtStart_Memory(void);
197 static void CleanupTransaction(void);
198 static void CommitTransaction(void);
199 static void RecordTransactionAbort(void);
200 static void StartTransaction(void);
203 * global variables holding the current transaction state.
206 static TransactionStateData CurrentTransactionStateData = {
207 0, /* transaction id */
208 FirstCommandId, /* command id */
209 0, /* scan command id */
210 0x0, /* start time */
211 TRANS_DEFAULT, /* transaction state */
212 TBLOCK_DEFAULT /* transaction block state */
215 TransactionState CurrentTransactionState = &CurrentTransactionStateData;
218 * User-tweakable parameters
220 int DefaultXactIsoLevel = XACT_READ_COMMITTED;
223 int CommitDelay = 0; /* precommit delay in microseconds */
224 int CommitSiblings = 5; /* number of concurrent xacts needed to
227 static void (*_RollbackFunc) (void *) = NULL;
228 static void *_RollbackData = NULL;
231 /* ----------------------------------------------------------------
232 * transaction state accessors
233 * ----------------------------------------------------------------
238 /* --------------------------------
239 * TransactionFlushEnabled()
240 * SetTransactionFlushEnabled()
242 * These are used to test and set the "TransactionFlushState"
243 * varable. If this variable is true (the default), then
244 * the system will flush all dirty buffers to disk at the end
245 * of each transaction. If false then we are assuming the
246 * buffer pool resides in stable main memory, in which case we
247 * only do writes as necessary.
248 * --------------------------------
250 static int TransactionFlushState = 1;
253 TransactionFlushEnabled(void)
255 return TransactionFlushState;
259 SetTransactionFlushEnabled(bool state)
261 TransactionFlushState = (state == true);
267 /* --------------------------------
270 * This returns true if we are currently running a query
271 * within an executing transaction.
272 * --------------------------------
275 IsTransactionState(void)
277 TransactionState s = CurrentTransactionState;
285 case TRANS_INPROGRESS:
294 * Shouldn't get here, but lint is not happy with this...
299 /* --------------------------------
300 * IsAbortedTransactionBlockState
302 * This returns true if we are currently running a query
303 * within an aborted transaction block.
304 * --------------------------------
307 IsAbortedTransactionBlockState(void)
309 TransactionState s = CurrentTransactionState;
311 if (s->blockState == TBLOCK_ABORT)
318 /* --------------------------------
319 * GetCurrentTransactionId
320 * --------------------------------
323 GetCurrentTransactionId(void)
325 TransactionState s = CurrentTransactionState;
327 return s->transactionIdData;
331 /* --------------------------------
332 * GetCurrentCommandId
333 * --------------------------------
336 GetCurrentCommandId(void)
338 TransactionState s = CurrentTransactionState;
344 /* --------------------------------
345 * GetCurrentTransactionStartTime
346 * --------------------------------
349 GetCurrentTransactionStartTime(void)
351 TransactionState s = CurrentTransactionState;
357 /* --------------------------------
358 * GetCurrentTransactionStartTimeUsec
359 * --------------------------------
362 GetCurrentTransactionStartTimeUsec(int *msec)
364 TransactionState s = CurrentTransactionState;
366 *msec = s->startTimeUsec;
372 /* --------------------------------
373 * TransactionIdIsCurrentTransactionId
375 * During bootstrap, we cheat and say "it's not my transaction ID" even though
376 * it is. Along with transam.c's cheat to say that the bootstrap XID is
377 * already committed, this causes the tqual.c routines to see previously
378 * inserted tuples as committed, which is what we need during bootstrap.
379 * --------------------------------
382 TransactionIdIsCurrentTransactionId(TransactionId xid)
384 TransactionState s = CurrentTransactionState;
388 Assert(xid == BootstrapTransactionId);
392 return TransactionIdEquals(xid, s->transactionIdData);
396 /* --------------------------------
397 * CommandIdIsCurrentCommandId
398 * --------------------------------
401 CommandIdIsCurrentCommandId(CommandId cid)
403 TransactionState s = CurrentTransactionState;
405 return (cid == s->commandId) ? true : false;
409 /* --------------------------------
410 * CommandCounterIncrement
411 * --------------------------------
414 CommandCounterIncrement(void)
416 TransactionState s = CurrentTransactionState;
419 if (s->commandId == FirstCommandId) /* check for overflow */
420 elog(ERROR, "You may only have 2^32-1 commands per transaction");
422 /* Propagate new command ID into query snapshots, if set */
424 QuerySnapshot->curcid = s->commandId;
425 if (SerializableSnapshot)
426 SerializableSnapshot->curcid = s->commandId;
429 * make cache changes visible to me. AtCommit_LocalCache() instead of
430 * AtCommit_Cache() is called here.
432 AtCommit_LocalCache();
437 /* ----------------------------------------------------------------
438 * StartTransaction stuff
439 * ----------------------------------------------------------------
442 /* --------------------------------
444 * --------------------------------
449 AcceptInvalidationMessages();
452 /* --------------------------------
454 * --------------------------------
460 * at present, it is unknown to me what belongs here -cim 3/18/90
462 * There isn't anything to do at the start of a xact for locks. -mer
467 /* --------------------------------
469 * --------------------------------
475 * We shouldn't have any transaction contexts already.
477 Assert(TopTransactionContext == NULL);
478 Assert(TransactionCommandContext == NULL);
481 * Create a toplevel context for the transaction.
483 TopTransactionContext =
484 AllocSetContextCreate(TopMemoryContext,
485 "TopTransactionContext",
486 ALLOCSET_DEFAULT_MINSIZE,
487 ALLOCSET_DEFAULT_INITSIZE,
488 ALLOCSET_DEFAULT_MAXSIZE);
491 * Create a statement-level context and make it active.
493 TransactionCommandContext =
494 AllocSetContextCreate(TopTransactionContext,
495 "TransactionCommandContext",
496 ALLOCSET_DEFAULT_MINSIZE,
497 ALLOCSET_DEFAULT_INITSIZE,
498 ALLOCSET_DEFAULT_MAXSIZE);
499 MemoryContextSwitchTo(TransactionCommandContext);
503 /* ----------------------------------------------------------------
504 * CommitTransaction stuff
505 * ----------------------------------------------------------------
509 * RecordTransactionCommit
512 RecordTransactionCommit(void)
515 * If we made neither any XLOG entries nor any temp-rel updates,
516 * we can omit recording the transaction commit at all.
518 if (MyXactMadeXLogEntry || MyXactMadeTempRelUpdate)
520 TransactionId xid = GetCurrentTransactionId();
523 /* Tell bufmgr and smgr to prepare for commit */
526 START_CRIT_SECTION();
529 * We only need to log the commit in xlog if the transaction made any
530 * transaction-controlled XLOG entries. (Otherwise, its XID appears
531 * nowhere in permanent storage, so no one else will ever care if it
534 if (MyLastRecPtr.xrecoff != 0)
536 /* Need to emit a commit record */
538 xl_xact_commit xlrec;
540 xlrec.xtime = time(NULL);
541 rdata.buffer = InvalidBuffer;
542 rdata.data = (char *) (&xlrec);
543 rdata.len = SizeOfXactCommit;
547 * XXX SHOULD SAVE ARRAY OF RELFILENODE-s TO DROP
549 recptr = XLogInsert(RM_XACT_ID, XLOG_XACT_COMMIT, &rdata);
553 /* Just flush through last record written by me */
554 recptr = ProcLastRecEnd;
558 * We must flush our XLOG entries to disk if we made any XLOG entries,
559 * whether in or out of transaction control. For example, if we
560 * reported a nextval() result to the client, this ensures that any
561 * XLOG record generated by nextval will hit the disk before we report
562 * the transaction committed.
564 if (MyXactMadeXLogEntry)
567 * Sleep before flush! So we can flush more than one commit
568 * records per single fsync. (The idea is some other backend may
569 * do the XLogFlush while we're sleeping. This needs work still,
570 * because on most Unixen, the minimum select() delay is 10msec or
571 * more, which is way too long.)
573 * We do not sleep if enableFsync is not turned on, nor if there
574 * are fewer than CommitSiblings other backends with active
577 if (CommitDelay > 0 && enableFsync &&
578 CountActiveBackends() >= CommitSiblings)
580 struct timeval delay;
583 delay.tv_usec = CommitDelay;
584 (void) select(0, NULL, NULL, NULL, &delay);
591 * We must mark the transaction committed in clog if its XID appears
592 * either in permanent rels or in local temporary rels. We test
593 * this by seeing if we made transaction-controlled entries *OR*
594 * local-rel tuple updates. Note that if we made only the latter,
595 * we have not emitted an XLOG record for our commit, and so in the
596 * event of a crash the clog update might be lost. This is okay
597 * because no one else will ever care whether we committed.
599 if (MyLastRecPtr.xrecoff != 0 || MyXactMadeTempRelUpdate)
600 TransactionIdCommit(xid);
605 /* Break the chain of back-links in the XLOG records I output */
606 MyLastRecPtr.xrecoff = 0;
607 MyXactMadeXLogEntry = false;
608 MyXactMadeTempRelUpdate = false;
610 /* Show myself as out of the transaction in PGPROC array */
611 MyProc->logRec.xrecoff = 0;
615 /* --------------------------------
617 * --------------------------------
623 * Clean up the relation cache.
625 AtEOXact_RelationCache(true);
627 * Make catalog changes visible to all backends.
629 AtEOXactInvalidationMessages(true);
632 /* --------------------------------
633 * AtCommit_LocalCache
634 * --------------------------------
637 AtCommit_LocalCache(void)
640 * Make catalog changes visible to me for the next command.
642 CommandEndInvalidationMessages(true);
645 /* --------------------------------
647 * --------------------------------
653 * XXX What if ProcReleaseLocks fails? (race condition?)
655 * Then you're up a creek! -mer 5/24/92
657 ProcReleaseLocks(true);
660 /* --------------------------------
662 * --------------------------------
665 AtCommit_Memory(void)
668 * Now that we're "out" of a transaction, have the system allocate
669 * things in the top memory context instead of per-transaction
672 MemoryContextSwitchTo(TopMemoryContext);
675 * Release all transaction-local memory.
677 Assert(TopTransactionContext != NULL);
678 MemoryContextDelete(TopTransactionContext);
679 TopTransactionContext = NULL;
680 TransactionCommandContext = NULL;
683 /* ----------------------------------------------------------------
684 * AbortTransaction stuff
685 * ----------------------------------------------------------------
689 * RecordTransactionAbort
692 RecordTransactionAbort(void)
695 * If we made neither any transaction-controlled XLOG entries nor any
696 * temp-rel updates, we can omit recording the transaction abort at all.
697 * No one will ever care that it aborted.
699 if (MyLastRecPtr.xrecoff != 0 || MyXactMadeTempRelUpdate)
701 TransactionId xid = GetCurrentTransactionId();
704 * Catch the scenario where we aborted partway through
705 * RecordTransactionCommit ...
707 if (TransactionIdDidCommit(xid))
708 elog(PANIC, "RecordTransactionAbort: xact %u already committed",
711 START_CRIT_SECTION();
714 * We only need to log the abort in XLOG if the transaction made any
715 * transaction-controlled XLOG entries. (Otherwise, its XID appears
716 * nowhere in permanent storage, so no one else will ever care if it
717 * committed.) We do not flush XLOG to disk in any case, since the
718 * default assumption after a crash would be that we aborted, anyway.
720 if (MyLastRecPtr.xrecoff != 0)
726 xlrec.xtime = time(NULL);
727 rdata.buffer = InvalidBuffer;
728 rdata.data = (char *) (&xlrec);
729 rdata.len = SizeOfXactAbort;
733 * SHOULD SAVE ARRAY OF RELFILENODE-s TO DROP
735 recptr = XLogInsert(RM_XACT_ID, XLOG_XACT_ABORT, &rdata);
739 * Mark the transaction aborted in clog. This is not absolutely
740 * necessary but we may as well do it while we are here.
742 TransactionIdAbort(xid);
747 /* Break the chain of back-links in the XLOG records I output */
748 MyLastRecPtr.xrecoff = 0;
749 MyXactMadeXLogEntry = false;
750 MyXactMadeTempRelUpdate = false;
752 /* Show myself as out of the transaction in PGPROC array */
753 MyProc->logRec.xrecoff = 0;
756 /* --------------------------------
758 * --------------------------------
763 AtEOXact_RelationCache(false);
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->startTime = GetCurrentAbsoluteTimeUsec(&(s->startTimeUsec));
891 * initialize the various transaction subsystems
898 * Tell the trigger manager to we're starting a transaction
900 DeferredTriggerBeginXact();
903 * done with start processing, set current transaction state to "in
906 s->state = TRANS_INPROGRESS;
912 * Tell me if we are currently in progress
916 CurrentXactInProgress(void)
918 return CurrentTransactionState->state == TRANS_INPROGRESS;
922 /* --------------------------------
925 * --------------------------------
928 CommitTransaction(void)
930 TransactionState s = CurrentTransactionState;
933 * check the current transaction state
935 if (s->state != TRANS_INPROGRESS)
936 elog(WARNING, "CommitTransaction and not in in-progress state");
939 * Tell the trigger manager that this transaction is about to be
940 * committed. He'll invoke all trigger deferred until XACT before we
941 * really start on committing the transaction.
943 DeferredTriggerEndXact();
945 /* Prevent cancel/die interrupt while cleaning up */
949 * set the current transaction state information appropriately during
950 * the abort processing
952 s->state = TRANS_COMMIT;
955 * do commit processing
958 /* handle commit for large objects [ PA, 7/17/98 ] */
961 /* NOTIFY commit must also come before lower-level cleanup */
966 /* Here is where we really truly commit. */
967 RecordTransactionCommit();
970 * Let others know about no transaction in progress by me. Note that
971 * this must be done _before_ releasing locks we hold and _after_
972 * RecordTransactionCommit.
974 * LWLockAcquire(SInvalLock) is required: UPDATE with xid 0 is blocked by
975 * xid 1' UPDATE, xid 1 is doing commit while xid 2 gets snapshot - if
976 * xid 2' GetSnapshotData sees xid 1 as running then it must see xid 0
977 * as running as well or it will see two tuple versions - one deleted
978 * by xid 1 and one inserted by xid 0. See notes in GetSnapshotData.
980 if (MyProc != (PGPROC *) NULL)
982 /* Lock SInvalLock because that's what GetSnapshotData uses. */
983 LWLockAcquire(SInvalLock, LW_EXCLUSIVE);
984 MyProc->xid = InvalidTransactionId;
985 MyProc->xmin = InvalidTransactionId;
986 LWLockRelease(SInvalLock);
990 * This is all post-commit cleanup. Note that if an error is raised
991 * here, it's too late to abort the transaction. This should be just
992 * noncritical resource releasing.
995 smgrDoPendingDeletes(true);
1003 AtEOXact_Namespace(true);
1006 AtEOXact_CatCache(true);
1008 AtEOXact_Buffers(true);
1012 /* Count transaction commit in statistics collector */
1013 pgstat_count_xact_commit();
1016 * done with commit processing, set current transaction state back to
1019 s->state = TRANS_DEFAULT;
1021 RESUME_INTERRUPTS();
1024 /* --------------------------------
1027 * --------------------------------
1030 AbortTransaction(void)
1032 TransactionState s = CurrentTransactionState;
1034 /* Prevent cancel/die interrupt while cleaning up */
1038 * Release any LW locks we might be holding as quickly as possible.
1039 * (Regular locks, however, must be held till we finish aborting.)
1040 * Releasing LW locks is critical since we might try to grab them
1041 * again while cleaning up!
1045 /* Clean up buffer I/O and buffer context locks, too */
1050 * Also clean up any open wait for lock, since the lock manager will
1051 * choke if we try to wait for another lock before doing this.
1056 * check the current transaction state
1058 if (s->state != TRANS_INPROGRESS)
1059 elog(WARNING, "AbortTransaction and not in in-progress state");
1062 * set the current transaction state information appropriately during
1063 * the abort processing
1065 s->state = TRANS_ABORT;
1068 * Reset user id which might have been changed transiently
1070 SetUserId(GetSessionUserId());
1073 * do abort processing
1075 DeferredTriggerAbortXact();
1076 lo_commit(false); /* 'false' means it's abort */
1080 /* Advertise the fact that we aborted in pg_clog. */
1081 RecordTransactionAbort();
1084 * Let others know about no transaction in progress by me. Note that
1085 * this must be done _before_ releasing locks we hold and _after_
1086 * RecordTransactionAbort.
1088 if (MyProc != (PGPROC *) NULL)
1090 /* Lock SInvalLock because that's what GetSnapshotData uses. */
1091 LWLockAcquire(SInvalLock, LW_EXCLUSIVE);
1092 MyProc->xid = InvalidTransactionId;
1093 MyProc->xmin = InvalidTransactionId;
1094 LWLockRelease(SInvalLock);
1097 smgrDoPendingDeletes(false);
1099 AtEOXact_GUC(false);
1105 AtEOXact_Namespace(false);
1107 AtEOXact_CatCache(false);
1109 AtEOXact_Buffers(false);
1113 /* Count transaction abort in statistics collector */
1114 pgstat_count_xact_rollback();
1117 * State remains TRANS_ABORT until CleanupTransaction().
1119 RESUME_INTERRUPTS();
1122 /* --------------------------------
1123 * CleanupTransaction
1125 * --------------------------------
1128 CleanupTransaction(void)
1130 TransactionState s = CurrentTransactionState;
1133 * State should still be TRANS_ABORT from AbortTransaction().
1135 if (s->state != TRANS_ABORT)
1136 elog(FATAL, "CleanupTransaction and not in abort state");
1139 * do abort cleanup processing
1144 * done with abort processing, set current transaction state back to
1147 s->state = TRANS_DEFAULT;
1150 /* --------------------------------
1151 * StartTransactionCommand
1152 * --------------------------------
1155 StartTransactionCommand(void)
1157 TransactionState s = CurrentTransactionState;
1159 switch (s->blockState)
1162 * if we aren't in a transaction block, we just do our usual
1163 * start transaction.
1165 case TBLOCK_DEFAULT:
1170 * We should never experience this -- if we do it means the
1171 * BEGIN state was not changed in the previous
1172 * CommitTransactionCommand(). If we get it, we print a
1173 * warning and change to the in-progress state.
1176 elog(WARNING, "StartTransactionCommand: unexpected TBLOCK_BEGIN");
1177 s->blockState = TBLOCK_INPROGRESS;
1181 * This is the case when are somewhere in a transaction block
1182 * and about to start a new command. For now we do nothing
1183 * but someday we may do command-local resource
1186 case TBLOCK_INPROGRESS:
1190 * As with BEGIN, we should never experience this if we do it
1191 * means the END state was not changed in the previous
1192 * CommitTransactionCommand(). If we get it, we print a
1193 * warning, commit the transaction, start a new transaction
1194 * and change to the default state.
1197 elog(WARNING, "StartTransactionCommand: unexpected TBLOCK_END");
1198 s->blockState = TBLOCK_DEFAULT;
1199 CommitTransaction();
1204 * Here we are in the middle of a transaction block but one of
1205 * the commands caused an abort so we do nothing but remain in
1206 * the abort state. Eventually we will get to the "END
1207 * TRANSACTION" which will set things straight.
1213 * This means we somehow aborted and the last call to
1214 * CommitTransactionCommand() didn't clear the state so we
1215 * remain in the ENDABORT state and maybe next time we get to
1216 * CommitTransactionCommand() the state will get reset to
1219 case TBLOCK_ENDABORT:
1220 elog(WARNING, "StartTransactionCommand: unexpected TBLOCK_ENDABORT");
1225 * We must switch to TransactionCommandContext before returning. This
1226 * is already done if we called StartTransaction, otherwise not.
1228 Assert(TransactionCommandContext != NULL);
1229 MemoryContextSwitchTo(TransactionCommandContext);
1232 /* --------------------------------
1233 * CommitTransactionCommand
1234 * --------------------------------
1237 CommitTransactionCommand(void)
1239 TransactionState s = CurrentTransactionState;
1241 switch (s->blockState)
1244 * if we aren't in a transaction block, we just do our usual
1245 * transaction commit
1247 case TBLOCK_DEFAULT:
1248 CommitTransaction();
1252 * This is the case right after we get a "BEGIN TRANSACTION"
1253 * command, but the user hasn't done anything else yet, so we
1254 * change to the "transaction block in progress" state and
1258 s->blockState = TBLOCK_INPROGRESS;
1262 * This is the case when we have finished executing a command
1263 * someplace within a transaction block. We increment the
1264 * command counter and return. Someday we may free resources
1265 * local to the command.
1267 * That someday is today, at least for memory allocated in
1268 * TransactionCommandContext. - vadim 03/25/97
1270 case TBLOCK_INPROGRESS:
1271 CommandCounterIncrement();
1272 MemoryContextResetAndDeleteChildren(TransactionCommandContext);
1276 * This is the case when we just got the "END TRANSACTION"
1277 * statement, so we commit the transaction and go back to the
1281 CommitTransaction();
1282 s->blockState = TBLOCK_DEFAULT;
1286 * Here we are in the middle of a transaction block but one of
1287 * the commands caused an abort so we do nothing but remain in
1288 * the abort state. Eventually we will get to the "END
1289 * TRANSACTION" which will set things straight.
1295 * Here we were in an aborted transaction block which just
1296 * processed the "END TRANSACTION" command from the user, so
1297 * clean up and return to the default state.
1299 case TBLOCK_ENDABORT:
1300 CleanupTransaction();
1301 s->blockState = TBLOCK_DEFAULT;
1306 /* --------------------------------
1307 * AbortCurrentTransaction
1308 * --------------------------------
1311 AbortCurrentTransaction(void)
1313 TransactionState s = CurrentTransactionState;
1315 switch (s->blockState)
1318 * if we aren't in a transaction block, we just do the basic
1319 * abort & cleanup transaction.
1321 case TBLOCK_DEFAULT:
1323 CleanupTransaction();
1327 * If we are in the TBLOCK_BEGIN it means something screwed up
1328 * right after reading "BEGIN TRANSACTION" so we enter the
1329 * abort state. Eventually an "END TRANSACTION" will fix
1333 s->blockState = TBLOCK_ABORT;
1335 /* CleanupTransaction happens when we exit TBLOCK_ABORT */
1339 * This is the case when are somewhere in a transaction block
1340 * which aborted so we abort the transaction and set the ABORT
1341 * state. Eventually an "END TRANSACTION" will fix things and
1342 * restore us to a normal state.
1344 case TBLOCK_INPROGRESS:
1345 s->blockState = TBLOCK_ABORT;
1347 /* CleanupTransaction happens when we exit TBLOCK_ABORT */
1351 * Here, the system was fouled up just after the user wanted
1352 * to end the transaction block so we abort the transaction
1353 * and put us back into the default state.
1356 s->blockState = TBLOCK_DEFAULT;
1358 CleanupTransaction();
1362 * Here, we are already in an aborted transaction state and
1363 * are waiting for an "END TRANSACTION" to come along and lo
1364 * and behold, we abort again! So we just remain in the abort
1371 * Here we were in an aborted transaction block which just
1372 * processed the "END TRANSACTION" command but somehow aborted
1373 * again.. since we must have done the abort processing, we
1374 * clean up and return to the default state.
1376 case TBLOCK_ENDABORT:
1377 CleanupTransaction();
1378 s->blockState = TBLOCK_DEFAULT;
1383 /* ----------------------------------------------------------------
1384 * transaction block support
1385 * ----------------------------------------------------------------
1387 /* --------------------------------
1388 * BeginTransactionBlock
1389 * --------------------------------
1392 BeginTransactionBlock(void)
1394 TransactionState s = CurrentTransactionState;
1397 * check the current transaction state
1399 if (s->blockState != TBLOCK_DEFAULT)
1400 elog(WARNING, "BEGIN: already a transaction in progress");
1403 * set the current transaction block state information appropriately
1404 * during begin processing
1406 s->blockState = TBLOCK_BEGIN;
1409 * do begin processing
1413 * done with begin processing, set block state to inprogress
1415 s->blockState = TBLOCK_INPROGRESS;
1418 /* --------------------------------
1419 * EndTransactionBlock
1420 * --------------------------------
1423 EndTransactionBlock(void)
1425 TransactionState s = CurrentTransactionState;
1428 * check the current transaction state
1430 if (s->blockState == TBLOCK_INPROGRESS)
1433 * here we are in a transaction block which should commit when we
1434 * get to the upcoming CommitTransactionCommand() so we set the
1435 * state to "END". CommitTransactionCommand() will recognize this
1436 * and commit the transaction and return us to the default state
1438 s->blockState = TBLOCK_END;
1442 if (s->blockState == TBLOCK_ABORT)
1445 * here, we are in a transaction block which aborted and since the
1446 * AbortTransaction() was already done, we do whatever is needed
1447 * and change to the special "END ABORT" state. The upcoming
1448 * CommitTransactionCommand() will recognise this and then put us
1449 * back in the default state.
1451 s->blockState = TBLOCK_ENDABORT;
1456 * here, the user issued COMMIT when not inside a transaction. Issue a
1457 * WARNING and go to abort state. The upcoming call to
1458 * CommitTransactionCommand() will then put us back into the default
1461 elog(WARNING, "COMMIT: no transaction in progress");
1463 s->blockState = TBLOCK_ENDABORT;
1466 /* --------------------------------
1467 * AbortTransactionBlock
1468 * --------------------------------
1472 AbortTransactionBlock(void)
1474 TransactionState s = CurrentTransactionState;
1477 * check the current transaction state
1479 if (s->blockState == TBLOCK_INPROGRESS)
1482 * here we were inside a transaction block something screwed up
1483 * inside the system so we enter the abort state, do the abort
1484 * processing and then return. We remain in the abort state until
1485 * we see an END TRANSACTION command.
1487 s->blockState = TBLOCK_ABORT;
1493 * here, the user issued ABORT when not inside a transaction. Issue a
1494 * WARNING and go to abort state. The upcoming call to
1495 * CommitTransactionCommand() will then put us back into the default
1498 elog(WARNING, "ROLLBACK: no transaction in progress");
1500 s->blockState = TBLOCK_ENDABORT;
1504 /* --------------------------------
1505 * UserAbortTransactionBlock
1506 * --------------------------------
1509 UserAbortTransactionBlock(void)
1511 TransactionState s = CurrentTransactionState;
1514 * if the transaction has already been automatically aborted with an
1515 * error, and the user subsequently types 'abort', allow it. (the
1516 * behavior is the same as if they had typed 'end'.)
1518 if (s->blockState == TBLOCK_ABORT)
1520 s->blockState = TBLOCK_ENDABORT;
1524 if (s->blockState == TBLOCK_INPROGRESS)
1527 * here we were inside a transaction block and we got an abort
1528 * command from the user, so we move to the abort state, do the
1529 * abort processing and then change to the ENDABORT state so we
1530 * will end up in the default state after the upcoming
1531 * CommitTransactionCommand().
1533 s->blockState = TBLOCK_ABORT;
1535 s->blockState = TBLOCK_ENDABORT;
1540 * here, the user issued ABORT when not inside a transaction. Issue a
1541 * WARNING and go to abort state. The upcoming call to
1542 * CommitTransactionCommand() will then put us back into the default
1545 elog(WARNING, "ROLLBACK: no transaction in progress");
1547 s->blockState = TBLOCK_ENDABORT;
1550 /* --------------------------------
1551 * AbortOutOfAnyTransaction
1553 * This routine is provided for error recovery purposes. It aborts any
1554 * active transaction or transaction block, leaving the system in a known
1556 * --------------------------------
1559 AbortOutOfAnyTransaction(void)
1561 TransactionState s = CurrentTransactionState;
1564 * Get out of any low-level transaction
1569 case TRANS_INPROGRESS:
1571 /* In a transaction, so clean up */
1573 CleanupTransaction();
1576 /* AbortTransaction already done, still need Cleanup */
1577 CleanupTransaction();
1580 /* Not in a transaction, do nothing */
1585 * Now reset the high-level state
1587 s->blockState = TBLOCK_DEFAULT;
1591 IsTransactionBlock(void)
1593 TransactionState s = CurrentTransactionState;
1595 if (s->blockState == TBLOCK_INPROGRESS
1596 || s->blockState == TBLOCK_ABORT
1597 || s->blockState == TBLOCK_ENDABORT)
1604 xact_redo(XLogRecPtr lsn, XLogRecord *record)
1606 uint8 info = record->xl_info & ~XLR_INFO_MASK;
1608 if (info == XLOG_XACT_COMMIT)
1610 TransactionIdCommit(record->xl_xid);
1611 /* SHOULD REMOVE FILES OF ALL DROPPED RELATIONS */
1613 else if (info == XLOG_XACT_ABORT)
1615 TransactionIdAbort(record->xl_xid);
1616 /* SHOULD REMOVE FILES OF ALL FAILED-TO-BE-CREATED RELATIONS */
1619 elog(PANIC, "xact_redo: unknown op code %u", info);
1623 xact_undo(XLogRecPtr lsn, XLogRecord *record)
1625 uint8 info = record->xl_info & ~XLR_INFO_MASK;
1627 if (info == XLOG_XACT_COMMIT) /* shouldn't be called by XLOG */
1628 elog(PANIC, "xact_undo: can't undo committed xaction");
1629 else if (info != XLOG_XACT_ABORT)
1630 elog(PANIC, "xact_redo: unknown op code %u", info);
1634 xact_desc(char *buf, uint8 xl_info, char *rec)
1636 uint8 info = xl_info & ~XLR_INFO_MASK;
1638 if (info == XLOG_XACT_COMMIT)
1640 xl_xact_commit *xlrec = (xl_xact_commit *) rec;
1641 struct tm *tm = localtime(&xlrec->xtime);
1643 sprintf(buf + strlen(buf), "commit: %04u-%02u-%02u %02u:%02u:%02u",
1644 tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday,
1645 tm->tm_hour, tm->tm_min, tm->tm_sec);
1647 else if (info == XLOG_XACT_ABORT)
1649 xl_xact_abort *xlrec = (xl_xact_abort *) rec;
1650 struct tm *tm = localtime(&xlrec->xtime);
1652 sprintf(buf + strlen(buf), "abort: %04u-%02u-%02u %02u:%02u:%02u",
1653 tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday,
1654 tm->tm_hour, tm->tm_min, tm->tm_sec);
1657 strcat(buf, "UNKNOWN");
1661 XactPushRollback(void (*func) (void *), void *data)
1664 if (_RollbackFunc != NULL)
1665 elog(PANIC, "XactPushRollback: already installed");
1668 _RollbackFunc = func;
1669 _RollbackData = data;
1673 XactPopRollback(void)
1675 _RollbackFunc = NULL;