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.120 2002/04/01 03:34:25 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 * ----------------------------------------------------------------
246 /* --------------------------------
247 * TransactionFlushEnabled()
248 * SetTransactionFlushEnabled()
250 * These are used to test and set the "TransactionFlushState"
251 * varable. If this variable is true (the default), then
252 * the system will flush all dirty buffers to disk at the end
253 * of each transaction. If false then we are assuming the
254 * buffer pool resides in stable main memory, in which case we
255 * only do writes as necessary.
256 * --------------------------------
258 static int TransactionFlushState = 1;
261 TransactionFlushEnabled(void)
263 return TransactionFlushState;
267 SetTransactionFlushEnabled(bool state)
269 TransactionFlushState = (state == true);
275 /* --------------------------------
278 * This returns true if we are currently running a query
279 * within an executing transaction.
280 * --------------------------------
283 IsTransactionState(void)
285 TransactionState s = CurrentTransactionState;
293 case TRANS_INPROGRESS:
302 * Shouldn't get here, but lint is not happy with this...
307 /* --------------------------------
308 * IsAbortedTransactionBlockState
310 * This returns true if we are currently running a query
311 * within an aborted transaction block.
312 * --------------------------------
315 IsAbortedTransactionBlockState(void)
317 TransactionState s = CurrentTransactionState;
319 if (s->blockState == TBLOCK_ABORT)
326 /* --------------------------------
327 * GetCurrentTransactionId
328 * --------------------------------
331 GetCurrentTransactionId(void)
333 TransactionState s = CurrentTransactionState;
335 return s->transactionIdData;
339 /* --------------------------------
340 * GetCurrentCommandId
341 * --------------------------------
344 GetCurrentCommandId(void)
346 TransactionState s = CurrentTransactionState;
352 GetScanCommandId(void)
354 TransactionState s = CurrentTransactionState;
356 return s->scanCommandId;
360 /* --------------------------------
361 * GetCurrentTransactionStartTime
362 * --------------------------------
365 GetCurrentTransactionStartTime(void)
367 TransactionState s = CurrentTransactionState;
373 /* --------------------------------
374 * GetCurrentTransactionStartTimeUsec
375 * --------------------------------
378 GetCurrentTransactionStartTimeUsec(int *msec)
380 TransactionState s = CurrentTransactionState;
382 *msec = s->startTimeUsec;
388 /* --------------------------------
389 * TransactionIdIsCurrentTransactionId
390 * --------------------------------
393 TransactionIdIsCurrentTransactionId(TransactionId xid)
395 TransactionState s = CurrentTransactionState;
400 return TransactionIdEquals(xid, s->transactionIdData);
404 /* --------------------------------
405 * CommandIdIsCurrentCommandId
406 * --------------------------------
409 CommandIdIsCurrentCommandId(CommandId cid)
411 TransactionState s = CurrentTransactionState;
416 return (cid == s->commandId) ? true : false;
420 CommandIdGEScanCommandId(CommandId cid)
422 TransactionState s = CurrentTransactionState;
427 return (cid >= s->scanCommandId) ? true : false;
431 /* --------------------------------
432 * CommandCounterIncrement
433 * --------------------------------
436 CommandCounterIncrement(void)
438 CurrentTransactionStateData.commandId += 1;
439 if (CurrentTransactionStateData.commandId == FirstCommandId)
440 elog(ERROR, "You may only have 2^32-1 commands per transaction");
442 CurrentTransactionStateData.scanCommandId = CurrentTransactionStateData.commandId;
445 * make cache changes visible to me. AtCommit_LocalCache() instead of
446 * AtCommit_Cache() is called here.
448 AtCommit_LocalCache();
453 SetScanCommandId(CommandId savedId)
455 CurrentTransactionStateData.scanCommandId = savedId;
458 /* ----------------------------------------------------------------
459 * StartTransaction stuff
460 * ----------------------------------------------------------------
463 /* --------------------------------
465 * --------------------------------
470 AcceptInvalidationMessages();
473 /* --------------------------------
475 * --------------------------------
481 * at present, it is unknown to me what belongs here -cim 3/18/90
483 * There isn't anything to do at the start of a xact for locks. -mer
488 /* --------------------------------
490 * --------------------------------
496 * We shouldn't have any transaction contexts already.
498 Assert(TopTransactionContext == NULL);
499 Assert(TransactionCommandContext == NULL);
502 * Create a toplevel context for the transaction.
504 TopTransactionContext =
505 AllocSetContextCreate(TopMemoryContext,
506 "TopTransactionContext",
507 ALLOCSET_DEFAULT_MINSIZE,
508 ALLOCSET_DEFAULT_INITSIZE,
509 ALLOCSET_DEFAULT_MAXSIZE);
512 * Create a statement-level context and make it active.
514 TransactionCommandContext =
515 AllocSetContextCreate(TopTransactionContext,
516 "TransactionCommandContext",
517 ALLOCSET_DEFAULT_MINSIZE,
518 ALLOCSET_DEFAULT_INITSIZE,
519 ALLOCSET_DEFAULT_MAXSIZE);
520 MemoryContextSwitchTo(TransactionCommandContext);
524 /* ----------------------------------------------------------------
525 * CommitTransaction stuff
526 * ----------------------------------------------------------------
529 /* --------------------------------
530 * RecordTransactionCommit
532 * Note: the two calls to BufferManagerFlush() exist to ensure
533 * that data pages are written before log pages. These
534 * explicit calls should be replaced by a more efficient
535 * ordered page write scheme in the buffer manager
537 * --------------------------------
540 RecordTransactionCommit(void)
545 leak = BufferPoolCheckLeak();
547 xid = GetCurrentTransactionId();
550 * We only need to log the commit in xlog and clog if the transaction made
551 * any transaction-controlled XLOG entries. (Otherwise, its XID appears
552 * nowhere in permanent storage, so no one will ever care if it
553 * committed.) However, we must flush XLOG to disk if we made any XLOG
554 * entries, whether in or out of transaction control. For example, if we
555 * reported a nextval() result to the client, this ensures that any XLOG
556 * record generated by nextval will hit the disk before we report the
557 * transaction committed.
559 if (MyXactMadeXLogEntry)
565 START_CRIT_SECTION();
567 if (MyLastRecPtr.xrecoff != 0)
569 /* Need to emit a commit record */
571 xl_xact_commit xlrec;
573 xlrec.xtime = time(NULL);
574 rdata.buffer = InvalidBuffer;
575 rdata.data = (char *) (&xlrec);
576 rdata.len = SizeOfXactCommit;
580 * XXX SHOULD SAVE ARRAY OF RELFILENODE-s TO DROP
582 recptr = XLogInsert(RM_XACT_ID, XLOG_XACT_COMMIT, &rdata);
586 /* Just flush through last record written by me */
587 recptr = ProcLastRecEnd;
591 * Sleep before flush! So we can flush more than one commit
592 * records per single fsync. (The idea is some other backend may
593 * do the XLogFlush while we're sleeping. This needs work still,
594 * because on most Unixen, the minimum select() delay is 10msec or
595 * more, which is way too long.)
597 * We do not sleep if enableFsync is not turned on, nor if there are
598 * fewer than CommitSiblings other backends with active
601 if (CommitDelay > 0 && enableFsync &&
602 CountActiveBackends() >= CommitSiblings)
604 struct timeval delay;
607 delay.tv_usec = CommitDelay;
608 (void) select(0, NULL, NULL, NULL, &delay);
613 /* Mark the transaction committed in clog, if needed */
614 if (MyLastRecPtr.xrecoff != 0)
615 TransactionIdCommit(xid);
620 /* Break the chain of back-links in the XLOG records I output */
621 MyLastRecPtr.xrecoff = 0;
622 MyXactMadeXLogEntry = false;
624 /* Show myself as out of the transaction in PROC array */
625 MyProc->logRec.xrecoff = 0;
628 ResetBufferPool(true);
632 /* --------------------------------
634 * --------------------------------
640 * Make catalog changes visible to all backends.
642 AtEOXactInvalidationMessages(true);
645 /* --------------------------------
646 * AtCommit_LocalCache
647 * --------------------------------
650 AtCommit_LocalCache(void)
653 * Make catalog changes visible to me for the next command.
655 CommandEndInvalidationMessages(true);
658 /* --------------------------------
660 * --------------------------------
666 * XXX What if ProcReleaseLocks fails? (race condition?)
668 * Then you're up a creek! -mer 5/24/92
670 ProcReleaseLocks(true);
673 /* --------------------------------
675 * --------------------------------
678 AtCommit_Memory(void)
681 * Now that we're "out" of a transaction, have the system allocate
682 * things in the top memory context instead of per-transaction
685 MemoryContextSwitchTo(TopMemoryContext);
688 * Release all transaction-local memory.
690 Assert(TopTransactionContext != NULL);
691 MemoryContextDelete(TopTransactionContext);
692 TopTransactionContext = NULL;
693 TransactionCommandContext = NULL;
696 /* ----------------------------------------------------------------
697 * AbortTransaction stuff
698 * ----------------------------------------------------------------
701 /* --------------------------------
702 * RecordTransactionAbort
703 * --------------------------------
706 RecordTransactionAbort(void)
708 TransactionId xid = GetCurrentTransactionId();
711 * We only need to log the abort in xlog and clog if the transaction made
712 * any transaction-controlled XLOG entries. (Otherwise, its XID appears
713 * nowhere in permanent storage, so no one will ever care if it
714 * committed.) We do not flush XLOG to disk in any case, since the
715 * default assumption after a crash would be that we aborted, anyway.
717 * Extra check here is to catch case that we aborted partway through
718 * RecordTransactionCommit ...
720 if (MyLastRecPtr.xrecoff != 0 && !TransactionIdDidCommit(xid))
726 xlrec.xtime = time(NULL);
727 rdata.buffer = InvalidBuffer;
728 rdata.data = (char *) (&xlrec);
729 rdata.len = SizeOfXactAbort;
732 START_CRIT_SECTION();
735 * SHOULD SAVE ARRAY OF RELFILENODE-s TO DROP
737 recptr = XLogInsert(RM_XACT_ID, XLOG_XACT_ABORT, &rdata);
739 /* Mark the transaction aborted in clog */
740 TransactionIdAbort(xid);
745 /* Break the chain of back-links in the XLOG records I output */
746 MyLastRecPtr.xrecoff = 0;
747 MyXactMadeXLogEntry = false;
749 /* Show myself as out of the transaction in PROC array */
750 MyProc->logRec.xrecoff = 0;
753 * Tell bufmgr and smgr to release resources.
755 ResetBufferPool(false); /* false -> is abort */
758 /* --------------------------------
760 * --------------------------------
765 RelationCacheAbort();
766 AtEOXactInvalidationMessages(false);
769 /* --------------------------------
771 * --------------------------------
777 * XXX What if ProcReleaseLocks() fails? (race condition?)
779 * Then you're up a creek without a paddle! -mer
781 ProcReleaseLocks(false);
785 /* --------------------------------
787 * --------------------------------
793 * Make sure we are in a valid context (not a child of
794 * TransactionCommandContext...). Note that it is possible for this
795 * code to be called when we aren't in a transaction at all; go
796 * directly to TopMemoryContext in that case.
798 if (TransactionCommandContext != NULL)
800 MemoryContextSwitchTo(TransactionCommandContext);
803 * We do not want to destroy transaction contexts yet, but it
804 * should be OK to delete any command-local memory.
806 MemoryContextResetAndDeleteChildren(TransactionCommandContext);
809 MemoryContextSwitchTo(TopMemoryContext);
813 /* ----------------------------------------------------------------
814 * CleanupTransaction stuff
815 * ----------------------------------------------------------------
818 /* --------------------------------
820 * --------------------------------
823 AtCleanup_Memory(void)
826 * Now that we're "out" of a transaction, have the system allocate
827 * things in the top memory context instead of per-transaction
830 MemoryContextSwitchTo(TopMemoryContext);
833 * Release all transaction-local memory.
835 if (TopTransactionContext != NULL)
836 MemoryContextDelete(TopTransactionContext);
837 TopTransactionContext = NULL;
838 TransactionCommandContext = NULL;
842 /* ----------------------------------------------------------------
844 * ----------------------------------------------------------------
847 /* --------------------------------
850 * --------------------------------
853 StartTransaction(void)
855 TransactionState s = CurrentTransactionState;
858 XactIsoLevel = DefaultXactIsoLevel;
861 * Check the current transaction state. If the transaction system is
862 * switched off, or if we're already in a transaction, do nothing.
863 * We're already in a transaction when the monitor sends a null
864 * command to the backend to flush the comm channel. This is a hacky
865 * fix to a communications problem, and we keep having to deal with it
866 * here. We should fix the comm channel code. mao 080891
868 if (s->state == TRANS_INPROGRESS)
872 * set the current transaction state information appropriately during
875 s->state = TRANS_START;
877 SetReindexProcessing(false);
880 * generate a new transaction id
882 s->transactionIdData = GetNewTransactionId();
884 XactLockTableInsert(s->transactionIdData);
887 * initialize current transaction state fields
889 s->commandId = FirstCommandId;
890 s->scanCommandId = FirstCommandId;
892 s->startTime = GetCurrentAbsoluteTime();
894 s->startTime = GetCurrentAbsoluteTimeUsec(&(s->startTimeUsec));
897 * initialize the various transaction subsystems
904 * Tell the trigger manager to we're starting a transaction
906 DeferredTriggerBeginXact();
909 * done with start processing, set current transaction state to "in
912 s->state = TRANS_INPROGRESS;
918 * Tell me if we are currently in progress
922 CurrentXactInProgress(void)
924 return CurrentTransactionState->state == TRANS_INPROGRESS;
928 /* --------------------------------
931 * --------------------------------
934 CommitTransaction(void)
936 TransactionState s = CurrentTransactionState;
939 * check the current transaction state
941 if (s->state != TRANS_INPROGRESS)
942 elog(WARNING, "CommitTransaction and not in in-progress state");
945 * Tell the trigger manager that this transaction is about to be
946 * committed. He'll invoke all trigger deferred until XACT before we
947 * really start on committing the transaction.
949 DeferredTriggerEndXact();
951 /* Prevent cancel/die interrupt while cleaning up */
955 * set the current transaction state information appropriately during
956 * the abort processing
958 s->state = TRANS_COMMIT;
961 * do commit processing
964 /* handle commit for large objects [ PA, 7/17/98 ] */
967 /* NOTIFY commit must also come before lower-level cleanup */
973 /* Here is where we really truly commit. */
974 RecordTransactionCommit();
977 * Let others know about no transaction in progress by me. Note that
978 * this must be done _before_ releasing locks we hold and _after_
979 * RecordTransactionCommit.
981 * LWLockAcquire(SInvalLock) is required: UPDATE with xid 0 is blocked by
982 * xid 1' UPDATE, xid 1 is doing commit while xid 2 gets snapshot - if
983 * xid 2' GetSnapshotData sees xid 1 as running then it must see xid 0
984 * as running as well or it will see two tuple versions - one deleted
985 * by xid 1 and one inserted by xid 0. See notes in GetSnapshotData.
987 if (MyProc != (PROC *) NULL)
989 /* Lock SInvalLock because that's what GetSnapshotData uses. */
990 LWLockAcquire(SInvalLock, LW_EXCLUSIVE);
991 MyProc->xid = InvalidTransactionId;
992 MyProc->xmin = InvalidTransactionId;
993 LWLockRelease(SInvalLock);
997 * This is all post-commit cleanup. Note that if an error is raised
998 * here, it's too late to abort the transaction. This should be just
999 * noncritical resource releasing.
1002 RelationPurgeLocalRelation(true);
1003 smgrDoPendingDeletes(true);
1012 AtEOXact_CatCache(true);
1016 SharedBufferChanged = false; /* safest place to do it */
1018 /* Count transaction commit in statistics collector */
1019 pgstat_count_xact_commit();
1022 * done with commit processing, set current transaction state back to
1025 s->state = TRANS_DEFAULT;
1027 RESUME_INTERRUPTS();
1030 /* --------------------------------
1033 * --------------------------------
1036 AbortTransaction(void)
1038 TransactionState s = CurrentTransactionState;
1040 /* Prevent cancel/die interrupt while cleaning up */
1044 * Release any LW locks we might be holding as quickly as possible.
1045 * (Regular locks, however, must be held till we finish aborting.)
1046 * Releasing LW locks is critical since we might try to grab them
1047 * again while cleaning up!
1051 /* Clean up buffer I/O and buffer context locks, too */
1056 * Also clean up any open wait for lock, since the lock manager will
1057 * choke if we try to wait for another lock before doing this.
1062 * check the current transaction state
1064 if (s->state != TRANS_INPROGRESS)
1065 elog(WARNING, "AbortTransaction and not in in-progress state");
1068 * set the current transaction state information appropriately during
1069 * the abort processing
1071 s->state = TRANS_ABORT;
1074 * Reset user id which might have been changed transiently
1076 SetUserId(GetSessionUserId());
1079 * do abort processing
1081 DeferredTriggerAbortXact();
1082 lo_commit(false); /* 'false' means it's abort */
1087 /* Advertise the fact that we aborted in pg_clog. */
1088 RecordTransactionAbort();
1091 * Let others know about no transaction in progress by me. Note that
1092 * this must be done _before_ releasing locks we hold and _after_
1093 * RecordTransactionAbort.
1095 if (MyProc != (PROC *) NULL)
1097 /* Lock SInvalLock because that's what GetSnapshotData uses. */
1098 LWLockAcquire(SInvalLock, LW_EXCLUSIVE);
1099 MyProc->xid = InvalidTransactionId;
1100 MyProc->xmin = InvalidTransactionId;
1101 LWLockRelease(SInvalLock);
1104 RelationPurgeLocalRelation(false);
1105 smgrDoPendingDeletes(false);
1113 AtEOXact_CatCache(false);
1118 SharedBufferChanged = false; /* safest place to do it */
1120 /* Count transaction abort in statistics collector */
1121 pgstat_count_xact_rollback();
1124 * State remains TRANS_ABORT until CleanupTransaction().
1126 RESUME_INTERRUPTS();
1129 /* --------------------------------
1130 * CleanupTransaction
1132 * --------------------------------
1135 CleanupTransaction(void)
1137 TransactionState s = CurrentTransactionState;
1140 * State should still be TRANS_ABORT from AbortTransaction().
1142 if (s->state != TRANS_ABORT)
1143 elog(FATAL, "CleanupTransaction and not in abort state");
1146 * do abort cleanup processing
1151 * done with abort processing, set current transaction state back to
1154 s->state = TRANS_DEFAULT;
1157 /* --------------------------------
1158 * StartTransactionCommand
1159 * --------------------------------
1162 StartTransactionCommand(void)
1164 TransactionState s = CurrentTransactionState;
1166 switch (s->blockState)
1169 * if we aren't in a transaction block, we just do our usual
1170 * start transaction.
1172 case TBLOCK_DEFAULT:
1177 * We should never experience this -- if we do it means the
1178 * BEGIN state was not changed in the previous
1179 * CommitTransactionCommand(). If we get it, we print a
1180 * warning and change to the in-progress state.
1183 elog(WARNING, "StartTransactionCommand: unexpected TBLOCK_BEGIN");
1184 s->blockState = TBLOCK_INPROGRESS;
1188 * This is the case when are somewhere in a transaction block
1189 * and about to start a new command. For now we do nothing
1190 * but someday we may do command-local resource
1193 case TBLOCK_INPROGRESS:
1197 * As with BEGIN, we should never experience this if we do it
1198 * means the END state was not changed in the previous
1199 * CommitTransactionCommand(). If we get it, we print a
1200 * warning, commit the transaction, start a new transaction
1201 * and change to the default state.
1204 elog(WARNING, "StartTransactionCommand: unexpected TBLOCK_END");
1205 s->blockState = TBLOCK_DEFAULT;
1206 CommitTransaction();
1211 * Here we are in the middle of a transaction block but one of
1212 * the commands caused an abort so we do nothing but remain in
1213 * the abort state. Eventually we will get to the "END
1214 * TRANSACTION" which will set things straight.
1220 * This means we somehow aborted and the last call to
1221 * CommitTransactionCommand() didn't clear the state so we
1222 * remain in the ENDABORT state and maybe next time we get to
1223 * CommitTransactionCommand() the state will get reset to
1226 case TBLOCK_ENDABORT:
1227 elog(WARNING, "StartTransactionCommand: unexpected TBLOCK_ENDABORT");
1232 * We must switch to TransactionCommandContext before returning. This
1233 * is already done if we called StartTransaction, otherwise not.
1235 Assert(TransactionCommandContext != NULL);
1236 MemoryContextSwitchTo(TransactionCommandContext);
1239 /* --------------------------------
1240 * CommitTransactionCommand
1241 * --------------------------------
1244 CommitTransactionCommand(void)
1246 TransactionState s = CurrentTransactionState;
1248 switch (s->blockState)
1251 * if we aren't in a transaction block, we just do our usual
1252 * transaction commit
1254 case TBLOCK_DEFAULT:
1255 CommitTransaction();
1259 * This is the case right after we get a "BEGIN TRANSACTION"
1260 * command, but the user hasn't done anything else yet, so we
1261 * change to the "transaction block in progress" state and
1265 s->blockState = TBLOCK_INPROGRESS;
1269 * This is the case when we have finished executing a command
1270 * someplace within a transaction block. We increment the
1271 * command counter and return. Someday we may free resources
1272 * local to the command.
1274 * That someday is today, at least for memory allocated in
1275 * TransactionCommandContext. - vadim 03/25/97
1277 case TBLOCK_INPROGRESS:
1278 CommandCounterIncrement();
1279 MemoryContextResetAndDeleteChildren(TransactionCommandContext);
1283 * This is the case when we just got the "END TRANSACTION"
1284 * statement, so we commit the transaction and go back to the
1288 CommitTransaction();
1289 s->blockState = TBLOCK_DEFAULT;
1293 * Here we are in the middle of a transaction block but one of
1294 * the commands caused an abort so we do nothing but remain in
1295 * the abort state. Eventually we will get to the "END
1296 * TRANSACTION" which will set things straight.
1302 * Here we were in an aborted transaction block which just
1303 * processed the "END TRANSACTION" command from the user, so
1304 * clean up and return to the default state.
1306 case TBLOCK_ENDABORT:
1307 CleanupTransaction();
1308 s->blockState = TBLOCK_DEFAULT;
1313 /* --------------------------------
1314 * AbortCurrentTransaction
1315 * --------------------------------
1318 AbortCurrentTransaction(void)
1320 TransactionState s = CurrentTransactionState;
1322 switch (s->blockState)
1325 * if we aren't in a transaction block, we just do the basic
1326 * abort & cleanup transaction.
1328 case TBLOCK_DEFAULT:
1330 CleanupTransaction();
1334 * If we are in the TBLOCK_BEGIN it means something screwed up
1335 * right after reading "BEGIN TRANSACTION" so we enter the
1336 * abort state. Eventually an "END TRANSACTION" will fix
1340 s->blockState = TBLOCK_ABORT;
1342 /* CleanupTransaction happens when we exit TBLOCK_ABORT */
1346 * This is the case when are somewhere in a transaction block
1347 * which aborted so we abort the transaction and set the ABORT
1348 * state. Eventually an "END TRANSACTION" will fix things and
1349 * restore us to a normal state.
1351 case TBLOCK_INPROGRESS:
1352 s->blockState = TBLOCK_ABORT;
1354 /* CleanupTransaction happens when we exit TBLOCK_ABORT */
1358 * Here, the system was fouled up just after the user wanted
1359 * to end the transaction block so we abort the transaction
1360 * and put us back into the default state.
1363 s->blockState = TBLOCK_DEFAULT;
1365 CleanupTransaction();
1369 * Here, we are already in an aborted transaction state and
1370 * are waiting for an "END TRANSACTION" to come along and lo
1371 * and behold, we abort again! So we just remain in the abort
1378 * Here we were in an aborted transaction block which just
1379 * processed the "END TRANSACTION" command but somehow aborted
1380 * again.. since we must have done the abort processing, we
1381 * clean up and return to the default state.
1383 case TBLOCK_ENDABORT:
1384 CleanupTransaction();
1385 s->blockState = TBLOCK_DEFAULT;
1390 /* ----------------------------------------------------------------
1391 * transaction block support
1392 * ----------------------------------------------------------------
1394 /* --------------------------------
1395 * BeginTransactionBlock
1396 * --------------------------------
1399 BeginTransactionBlock(void)
1401 TransactionState s = CurrentTransactionState;
1404 * check the current transaction state
1406 if (s->blockState != TBLOCK_DEFAULT)
1407 elog(WARNING, "BEGIN: already a transaction in progress");
1410 * set the current transaction block state information appropriately
1411 * during begin processing
1413 s->blockState = TBLOCK_BEGIN;
1416 * do begin processing
1420 * done with begin processing, set block state to inprogress
1422 s->blockState = TBLOCK_INPROGRESS;
1425 /* --------------------------------
1426 * EndTransactionBlock
1427 * --------------------------------
1430 EndTransactionBlock(void)
1432 TransactionState s = CurrentTransactionState;
1435 * check the current transaction state
1437 if (s->blockState == TBLOCK_INPROGRESS)
1440 * here we are in a transaction block which should commit when we
1441 * get to the upcoming CommitTransactionCommand() so we set the
1442 * state to "END". CommitTransactionCommand() will recognize this
1443 * and commit the transaction and return us to the default state
1445 s->blockState = TBLOCK_END;
1449 if (s->blockState == TBLOCK_ABORT)
1452 * here, we are in a transaction block which aborted and since the
1453 * AbortTransaction() was already done, we do whatever is needed
1454 * and change to the special "END ABORT" state. The upcoming
1455 * CommitTransactionCommand() will recognise this and then put us
1456 * back in the default state.
1458 s->blockState = TBLOCK_ENDABORT;
1463 * here, the user issued COMMIT when not inside a transaction. Issue a
1464 * WARNING and go to abort state. The upcoming call to
1465 * CommitTransactionCommand() will then put us back into the default
1468 elog(WARNING, "COMMIT: no transaction in progress");
1470 s->blockState = TBLOCK_ENDABORT;
1473 /* --------------------------------
1474 * AbortTransactionBlock
1475 * --------------------------------
1479 AbortTransactionBlock(void)
1481 TransactionState s = CurrentTransactionState;
1484 * check the current transaction state
1486 if (s->blockState == TBLOCK_INPROGRESS)
1489 * here we were inside a transaction block something screwed up
1490 * inside the system so we enter the abort state, do the abort
1491 * processing and then return. We remain in the abort state until
1492 * we see an END TRANSACTION command.
1494 s->blockState = TBLOCK_ABORT;
1500 * here, the user issued ABORT when not inside a transaction. Issue a
1501 * WARNING and go to abort state. The upcoming call to
1502 * CommitTransactionCommand() will then put us back into the default
1505 elog(WARNING, "ROLLBACK: no transaction in progress");
1507 s->blockState = TBLOCK_ENDABORT;
1511 /* --------------------------------
1512 * UserAbortTransactionBlock
1513 * --------------------------------
1516 UserAbortTransactionBlock(void)
1518 TransactionState s = CurrentTransactionState;
1521 * if the transaction has already been automatically aborted with an
1522 * error, and the user subsequently types 'abort', allow it. (the
1523 * behavior is the same as if they had typed 'end'.)
1525 if (s->blockState == TBLOCK_ABORT)
1527 s->blockState = TBLOCK_ENDABORT;
1531 if (s->blockState == TBLOCK_INPROGRESS)
1534 * here we were inside a transaction block and we got an abort
1535 * command from the user, so we move to the abort state, do the
1536 * abort processing and then change to the ENDABORT state so we
1537 * will end up in the default state after the upcoming
1538 * CommitTransactionCommand().
1540 s->blockState = TBLOCK_ABORT;
1542 s->blockState = TBLOCK_ENDABORT;
1547 * here, the user issued ABORT when not inside a transaction. Issue a
1548 * WARNING and go to abort state. The upcoming call to
1549 * CommitTransactionCommand() will then put us back into the default
1552 elog(WARNING, "ROLLBACK: no transaction in progress");
1554 s->blockState = TBLOCK_ENDABORT;
1557 /* --------------------------------
1558 * AbortOutOfAnyTransaction
1560 * This routine is provided for error recovery purposes. It aborts any
1561 * active transaction or transaction block, leaving the system in a known
1563 * --------------------------------
1566 AbortOutOfAnyTransaction(void)
1568 TransactionState s = CurrentTransactionState;
1571 * Get out of any low-level transaction
1576 case TRANS_INPROGRESS:
1578 /* In a transaction, so clean up */
1580 CleanupTransaction();
1583 /* AbortTransaction already done, still need Cleanup */
1584 CleanupTransaction();
1587 /* Not in a transaction, do nothing */
1592 * Now reset the high-level state
1594 s->blockState = TBLOCK_DEFAULT;
1598 IsTransactionBlock(void)
1600 TransactionState s = CurrentTransactionState;
1602 if (s->blockState == TBLOCK_INPROGRESS
1603 || s->blockState == TBLOCK_ABORT
1604 || s->blockState == TBLOCK_ENDABORT)
1611 xact_redo(XLogRecPtr lsn, XLogRecord *record)
1613 uint8 info = record->xl_info & ~XLR_INFO_MASK;
1615 if (info == XLOG_XACT_COMMIT)
1617 TransactionIdCommit(record->xl_xid);
1618 /* SHOULD REMOVE FILES OF ALL DROPPED RELATIONS */
1620 else if (info == XLOG_XACT_ABORT)
1622 TransactionIdAbort(record->xl_xid);
1623 /* SHOULD REMOVE FILES OF ALL FAILED-TO-BE-CREATED RELATIONS */
1626 elog(PANIC, "xact_redo: unknown op code %u", info);
1630 xact_undo(XLogRecPtr lsn, XLogRecord *record)
1632 uint8 info = record->xl_info & ~XLR_INFO_MASK;
1634 if (info == XLOG_XACT_COMMIT) /* shouldn't be called by XLOG */
1635 elog(PANIC, "xact_undo: can't undo committed xaction");
1636 else if (info != XLOG_XACT_ABORT)
1637 elog(PANIC, "xact_redo: unknown op code %u", info);
1641 xact_desc(char *buf, uint8 xl_info, char *rec)
1643 uint8 info = xl_info & ~XLR_INFO_MASK;
1645 if (info == XLOG_XACT_COMMIT)
1647 xl_xact_commit *xlrec = (xl_xact_commit *) rec;
1648 struct tm *tm = localtime(&xlrec->xtime);
1650 sprintf(buf + strlen(buf), "commit: %04u-%02u-%02u %02u:%02u:%02u",
1651 tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday,
1652 tm->tm_hour, tm->tm_min, tm->tm_sec);
1654 else if (info == XLOG_XACT_ABORT)
1656 xl_xact_abort *xlrec = (xl_xact_abort *) rec;
1657 struct tm *tm = localtime(&xlrec->xtime);
1659 sprintf(buf + strlen(buf), "abort: %04u-%02u-%02u %02u:%02u:%02u",
1660 tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday,
1661 tm->tm_hour, tm->tm_min, tm->tm_sec);
1664 strcat(buf, "UNKNOWN");
1668 XactPushRollback(void (*func) (void *), void *data)
1671 if (_RollbackFunc != NULL)
1672 elog(PANIC, "XactPushRollback: already installed");
1675 _RollbackFunc = func;
1676 _RollbackData = data;
1680 XactPopRollback(void)
1682 _RollbackFunc = NULL;