Age Owner Branch data TLA Line data Source code
1 : : /*-------------------------------------------------------------------------
2 : : *
3 : : * xact.c
4 : : * top level transaction system support routines
5 : : *
6 : : * See src/backend/access/transam/README for more information.
7 : : *
8 : : * Portions Copyright (c) 1996-2026, PostgreSQL Global Development Group
9 : : * Portions Copyright (c) 1994, Regents of the University of California
10 : : *
11 : : *
12 : : * IDENTIFICATION
13 : : * src/backend/access/transam/xact.c
14 : : *
15 : : *-------------------------------------------------------------------------
16 : : */
17 : :
18 : : #include "postgres.h"
19 : :
20 : : #include <time.h>
21 : : #include <unistd.h>
22 : :
23 : : #include "access/commit_ts.h"
24 : : #include "access/multixact.h"
25 : : #include "access/parallel.h"
26 : : #include "access/subtrans.h"
27 : : #include "access/transam.h"
28 : : #include "access/twophase.h"
29 : : #include "access/xact.h"
30 : : #include "access/xlog.h"
31 : : #include "access/xloginsert.h"
32 : : #include "access/xlogrecovery.h"
33 : : #include "access/xlogutils.h"
34 : : #include "access/xlogwait.h"
35 : : #include "catalog/index.h"
36 : : #include "catalog/namespace.h"
37 : : #include "catalog/pg_enum.h"
38 : : #include "catalog/storage.h"
39 : : #include "commands/async.h"
40 : : #include "commands/tablecmds.h"
41 : : #include "commands/trigger.h"
42 : : #include "common/pg_prng.h"
43 : : #include "executor/spi.h"
44 : : #include "libpq/be-fsstubs.h"
45 : : #include "libpq/pqsignal.h"
46 : : #include "miscadmin.h"
47 : : #include "pg_trace.h"
48 : : #include "pgstat.h"
49 : : #include "replication/logical.h"
50 : : #include "replication/logicallauncher.h"
51 : : #include "replication/logicalworker.h"
52 : : #include "replication/origin.h"
53 : : #include "replication/snapbuild.h"
54 : : #include "replication/syncrep.h"
55 : : #include "storage/aio_subsys.h"
56 : : #include "storage/condition_variable.h"
57 : : #include "storage/fd.h"
58 : : #include "storage/lmgr.h"
59 : : #include "storage/md.h"
60 : : #include "storage/predicate.h"
61 : : #include "storage/proc.h"
62 : : #include "storage/procarray.h"
63 : : #include "storage/sinvaladt.h"
64 : : #include "storage/smgr.h"
65 : : #include "utils/builtins.h"
66 : : #include "utils/combocid.h"
67 : : #include "utils/guc.h"
68 : : #include "utils/injection_point.h"
69 : : #include "utils/inval.h"
70 : : #include "utils/memutils.h"
71 : : #include "utils/relmapper.h"
72 : : #include "utils/snapmgr.h"
73 : : #include "utils/timeout.h"
74 : : #include "utils/timestamp.h"
75 : : #include "utils/typcache.h"
76 : : #include "utils/wait_event.h"
77 : :
78 : : /*
79 : : * User-tweakable parameters
80 : : */
81 : : int DefaultXactIsoLevel = XACT_READ_COMMITTED;
82 : : int XactIsoLevel = XACT_READ_COMMITTED;
83 : :
84 : : bool DefaultXactReadOnly = false;
85 : : bool XactReadOnly;
86 : :
87 : : bool DefaultXactDeferrable = false;
88 : : bool XactDeferrable;
89 : :
90 : : int synchronous_commit = SYNCHRONOUS_COMMIT_ON;
91 : :
92 : : /*
93 : : * CheckXidAlive is a xid value pointing to a possibly ongoing (sub)
94 : : * transaction. Currently, it is used in logical decoding. It's possible
95 : : * that such transactions can get aborted while the decoding is ongoing in
96 : : * which case we skip decoding that particular transaction. To ensure that we
97 : : * check whether the CheckXidAlive is aborted after fetching the tuple from
98 : : * system tables. We also ensure that during logical decoding we never
99 : : * directly access the tableam or heap APIs because we are checking for the
100 : : * concurrent aborts only in systable_* APIs.
101 : : */
102 : : TransactionId CheckXidAlive = InvalidTransactionId;
103 : : bool bsysscan = false;
104 : :
105 : : /*
106 : : * When running as a parallel worker, we place only a single
107 : : * TransactionStateData on the parallel worker's state stack, and the XID
108 : : * reflected there will be that of the *innermost* currently-active
109 : : * subtransaction in the backend that initiated parallelism. However,
110 : : * GetTopTransactionId() and TransactionIdIsCurrentTransactionId()
111 : : * need to return the same answers in the parallel worker as they would have
112 : : * in the user backend, so we need some additional bookkeeping.
113 : : *
114 : : * XactTopFullTransactionId stores the XID of our toplevel transaction, which
115 : : * will be the same as TopTransactionStateData.fullTransactionId in an
116 : : * ordinary backend; but in a parallel backend, which does not have the entire
117 : : * transaction state, it will instead be copied from the backend that started
118 : : * the parallel operation.
119 : : *
120 : : * nParallelCurrentXids will be 0 and ParallelCurrentXids NULL in an ordinary
121 : : * backend, but in a parallel backend, nParallelCurrentXids will contain the
122 : : * number of XIDs that need to be considered current, and ParallelCurrentXids
123 : : * will contain the XIDs themselves. This includes all XIDs that were current
124 : : * or sub-committed in the parent at the time the parallel operation began.
125 : : * The XIDs are stored sorted in numerical order (not logical order) to make
126 : : * lookups as fast as possible.
127 : : */
128 : : static FullTransactionId XactTopFullTransactionId = {InvalidTransactionId};
129 : : static int nParallelCurrentXids = 0;
130 : : static TransactionId *ParallelCurrentXids;
131 : :
132 : : /*
133 : : * Miscellaneous flag bits to record events which occur on the top level
134 : : * transaction. These flags are only persisted in MyXactFlags and are intended
135 : : * so we remember to do certain things later on in the transaction. This is
136 : : * globally accessible, so can be set from anywhere in the code that requires
137 : : * recording flags.
138 : : */
139 : : int MyXactFlags;
140 : :
141 : : /*
142 : : * transaction states - transaction state from server perspective
143 : : */
144 : : typedef enum TransState
145 : : {
146 : : TRANS_DEFAULT, /* idle */
147 : : TRANS_START, /* transaction starting */
148 : : TRANS_INPROGRESS, /* inside a valid transaction */
149 : : TRANS_COMMIT, /* commit in progress */
150 : : TRANS_ABORT, /* abort in progress */
151 : : TRANS_PREPARE, /* prepare in progress */
152 : : } TransState;
153 : :
154 : : /*
155 : : * transaction block states - transaction state of client queries
156 : : *
157 : : * Note: the subtransaction states are used only for non-topmost
158 : : * transactions; the others appear only in the topmost transaction.
159 : : */
160 : : typedef enum TBlockState
161 : : {
162 : : /* not-in-transaction-block states */
163 : : TBLOCK_DEFAULT, /* idle */
164 : : TBLOCK_STARTED, /* running single-query transaction */
165 : :
166 : : /* transaction block states */
167 : : TBLOCK_BEGIN, /* starting transaction block */
168 : : TBLOCK_INPROGRESS, /* live transaction */
169 : : TBLOCK_IMPLICIT_INPROGRESS, /* live transaction after implicit BEGIN */
170 : : TBLOCK_PARALLEL_INPROGRESS, /* live transaction inside parallel worker */
171 : : TBLOCK_END, /* COMMIT received */
172 : : TBLOCK_ABORT, /* failed xact, awaiting ROLLBACK */
173 : : TBLOCK_ABORT_END, /* failed xact, ROLLBACK received */
174 : : TBLOCK_ABORT_PENDING, /* live xact, ROLLBACK received */
175 : : TBLOCK_PREPARE, /* live xact, PREPARE received */
176 : :
177 : : /* subtransaction states */
178 : : TBLOCK_SUBBEGIN, /* starting a subtransaction */
179 : : TBLOCK_SUBINPROGRESS, /* live subtransaction */
180 : : TBLOCK_SUBRELEASE, /* RELEASE received */
181 : : TBLOCK_SUBCOMMIT, /* COMMIT received while TBLOCK_SUBINPROGRESS */
182 : : TBLOCK_SUBABORT, /* failed subxact, awaiting ROLLBACK */
183 : : TBLOCK_SUBABORT_END, /* failed subxact, ROLLBACK received */
184 : : TBLOCK_SUBABORT_PENDING, /* live subxact, ROLLBACK received */
185 : : TBLOCK_SUBRESTART, /* live subxact, ROLLBACK TO received */
186 : : TBLOCK_SUBABORT_RESTART, /* failed subxact, ROLLBACK TO received */
187 : : } TBlockState;
188 : :
189 : : /*
190 : : * transaction state structure
191 : : *
192 : : * Note: parallelModeLevel counts the number of unmatched EnterParallelMode
193 : : * calls done at this transaction level. parallelChildXact is true if any
194 : : * upper transaction level has nonzero parallelModeLevel.
195 : : */
196 : : typedef struct TransactionStateData
197 : : {
198 : : FullTransactionId fullTransactionId; /* my FullTransactionId */
199 : : SubTransactionId subTransactionId; /* my subxact ID */
200 : : char *name; /* savepoint name, if any */
201 : : int savepointLevel; /* savepoint level */
202 : : TransState state; /* low-level state */
203 : : TBlockState blockState; /* high-level state */
204 : : int nestingLevel; /* transaction nesting depth */
205 : : int gucNestLevel; /* GUC context nesting depth */
206 : : MemoryContext curTransactionContext; /* my xact-lifetime context */
207 : : ResourceOwner curTransactionOwner; /* my query resources */
208 : : MemoryContext priorContext; /* CurrentMemoryContext before xact started */
209 : : TransactionId *childXids; /* subcommitted child XIDs, in XID order */
210 : : int nChildXids; /* # of subcommitted child XIDs */
211 : : int maxChildXids; /* allocated size of childXids[] */
212 : : Oid prevUser; /* previous CurrentUserId setting */
213 : : int prevSecContext; /* previous SecurityRestrictionContext */
214 : : bool prevXactReadOnly; /* entry-time xact r/o state */
215 : : bool startedInRecovery; /* did we start in recovery? */
216 : : bool didLogXid; /* has xid been included in WAL record? */
217 : : int parallelModeLevel; /* Enter/ExitParallelMode counter */
218 : : bool parallelChildXact; /* is any parent transaction parallel? */
219 : : bool chain; /* start a new block after this one */
220 : : bool topXidLogged; /* for a subxact: is top-level XID logged? */
221 : : struct TransactionStateData *parent; /* back link to parent */
222 : : } TransactionStateData;
223 : :
224 : : typedef TransactionStateData *TransactionState;
225 : :
226 : : /*
227 : : * Serialized representation used to transmit transaction state to parallel
228 : : * workers through shared memory.
229 : : */
230 : : typedef struct SerializedTransactionState
231 : : {
232 : : int xactIsoLevel;
233 : : bool xactDeferrable;
234 : : FullTransactionId topFullTransactionId;
235 : : FullTransactionId currentFullTransactionId;
236 : : CommandId currentCommandId;
237 : : int nParallelCurrentXids;
238 : : pg_attribute_counted_by(nParallelCurrentXids) TransactionId parallelCurrentXids[FLEXIBLE_ARRAY_MEMBER];
239 : : } SerializedTransactionState;
240 : :
241 : : /* The size of SerializedTransactionState, not including the final array. */
242 : : #define SerializedTransactionStateHeaderSize \
243 : : offsetof(SerializedTransactionState, parallelCurrentXids)
244 : :
245 : : /*
246 : : * CurrentTransactionState always points to the current transaction state
247 : : * block. It will point to TopTransactionStateData when not in a
248 : : * transaction at all, or when in a top-level transaction.
249 : : */
250 : : static TransactionStateData TopTransactionStateData = {
251 : : .state = TRANS_DEFAULT,
252 : : .blockState = TBLOCK_DEFAULT,
253 : : .topXidLogged = false,
254 : : };
255 : :
256 : : /*
257 : : * unreportedXids holds XIDs of all subtransactions that have not yet been
258 : : * reported in an XLOG_XACT_ASSIGNMENT record.
259 : : */
260 : : static int nUnreportedXids;
261 : : static TransactionId unreportedXids[PGPROC_MAX_CACHED_SUBXIDS];
262 : :
263 : : static TransactionState CurrentTransactionState = &TopTransactionStateData;
264 : :
265 : : /*
266 : : * The subtransaction ID and command ID assignment counters are global
267 : : * to a whole transaction, so we do not keep them in the state stack.
268 : : */
269 : : static SubTransactionId currentSubTransactionId;
270 : : static CommandId currentCommandId;
271 : : static bool currentCommandIdUsed;
272 : :
273 : : /*
274 : : * xactStartTimestamp is the value of transaction_timestamp().
275 : : * stmtStartTimestamp is the value of statement_timestamp().
276 : : * xactStopTimestamp is the time at which we log a commit / abort WAL record,
277 : : * or if that was skipped, the time of the first subsequent
278 : : * GetCurrentTransactionStopTimestamp() call.
279 : : *
280 : : * These do not change as we enter and exit subtransactions, so we don't
281 : : * keep them inside the TransactionState stack.
282 : : */
283 : : static TimestampTz xactStartTimestamp;
284 : : static TimestampTz stmtStartTimestamp;
285 : : static TimestampTz xactStopTimestamp;
286 : :
287 : : /*
288 : : * GID to be used for preparing the current transaction. This is also
289 : : * global to a whole transaction, so we don't keep it in the state stack.
290 : : */
291 : : static char *prepareGID;
292 : :
293 : : /*
294 : : * Some commands want to force synchronous commit.
295 : : */
296 : : static bool forceSyncCommit = false;
297 : :
298 : : /* Flag for logging statements in a transaction. */
299 : : bool xact_is_sampled = false;
300 : :
301 : : /*
302 : : * Private context for transaction-abort work --- we reserve space for this
303 : : * at startup to ensure that AbortTransaction and AbortSubTransaction can work
304 : : * when we've run out of memory.
305 : : */
306 : : static MemoryContext TransactionAbortContext = NULL;
307 : :
308 : : /*
309 : : * List of add-on start- and end-of-xact callbacks
310 : : */
311 : : typedef struct XactCallbackItem
312 : : {
313 : : struct XactCallbackItem *next;
314 : : XactCallback callback;
315 : : void *arg;
316 : : } XactCallbackItem;
317 : :
318 : : static XactCallbackItem *Xact_callbacks = NULL;
319 : :
320 : : /*
321 : : * List of add-on start- and end-of-subxact callbacks
322 : : */
323 : : typedef struct SubXactCallbackItem
324 : : {
325 : : struct SubXactCallbackItem *next;
326 : : SubXactCallback callback;
327 : : void *arg;
328 : : } SubXactCallbackItem;
329 : :
330 : : static SubXactCallbackItem *SubXact_callbacks = NULL;
331 : :
332 : :
333 : : /* local function prototypes */
334 : : static void AssignTransactionId(TransactionState s);
335 : : static void AbortTransaction(void);
336 : : static void AtAbort_Memory(void);
337 : : static void AtCleanup_Memory(void);
338 : : static void AtAbort_ResourceOwner(void);
339 : : static void AtCCI_LocalCache(void);
340 : : static void AtCommit_Memory(void);
341 : : static void AtStart_Cache(void);
342 : : static void AtStart_Memory(void);
343 : : static void AtStart_ResourceOwner(void);
344 : : static void CallXactCallbacks(XactEvent event);
345 : : static void CallSubXactCallbacks(SubXactEvent event,
346 : : SubTransactionId mySubid,
347 : : SubTransactionId parentSubid);
348 : : static void CleanupTransaction(void);
349 : : static void CheckTransactionBlock(bool isTopLevel, bool throwError,
350 : : const char *stmtType);
351 : : static void CommitTransaction(void);
352 : : static TransactionId RecordTransactionAbort(bool isSubXact);
353 : : static void StartTransaction(void);
354 : :
355 : : static bool CommitTransactionCommandInternal(void);
356 : : static bool AbortCurrentTransactionInternal(void);
357 : :
358 : : static void StartSubTransaction(void);
359 : : static void CommitSubTransaction(void);
360 : : static void AbortSubTransaction(void);
361 : : static void CleanupSubTransaction(void);
362 : : static void PushTransaction(void);
363 : : static void PopTransaction(void);
364 : :
365 : : static void AtSubAbort_Memory(void);
366 : : static void AtSubCleanup_Memory(void);
367 : : static void AtSubAbort_ResourceOwner(void);
368 : : static void AtSubCommit_Memory(void);
369 : : static void AtSubStart_Memory(void);
370 : : static void AtSubStart_ResourceOwner(void);
371 : :
372 : : static void ShowTransactionState(const char *str);
373 : : static void ShowTransactionStateRec(const char *str, TransactionState s);
374 : : static const char *BlockStateAsString(TBlockState blockState);
375 : : static const char *TransStateAsString(TransState state);
376 : :
377 : :
378 : : /* ----------------------------------------------------------------
379 : : * transaction state accessors
380 : : * ----------------------------------------------------------------
381 : : */
382 : :
383 : : /*
384 : : * IsTransactionState
385 : : *
386 : : * This returns true if we are inside a valid transaction; that is,
387 : : * it is safe to initiate database access, take heavyweight locks, etc.
388 : : */
389 : : bool
10975 bruce@momjian.us 390 :CBC 201974610 : IsTransactionState(void)
391 : : {
10674 392 : 201974610 : TransactionState s = CurrentTransactionState;
393 : :
394 : : /*
395 : : * TRANS_DEFAULT and TRANS_ABORT are obviously unsafe states. However, we
396 : : * also reject the startup/shutdown states TRANS_START, TRANS_COMMIT,
397 : : * TRANS_PREPARE since it might be too soon or too late within those
398 : : * transition states to do anything interesting. Hence, the only "valid"
399 : : * state is TRANS_INPROGRESS.
400 : : */
7114 tgl@sss.pgh.pa.us 401 : 201974610 : return (s->state == TRANS_INPROGRESS);
402 : : }
403 : :
404 : : /*
405 : : * IsAbortedTransactionBlockState
406 : : *
407 : : * This returns true if we are within an aborted transaction block.
408 : : */
409 : : bool
9531 410 : 977826 : IsAbortedTransactionBlockState(void)
411 : : {
10674 bruce@momjian.us 412 : 977826 : TransactionState s = CurrentTransactionState;
413 : :
8126 414 [ + + ]: 977826 : if (s->blockState == TBLOCK_ABORT ||
8185 tgl@sss.pgh.pa.us 415 [ + + ]: 975754 : s->blockState == TBLOCK_SUBABORT)
10674 bruce@momjian.us 416 : 2624 : return true;
417 : :
418 : 975202 : return false;
419 : : }
420 : :
421 : :
422 : : /*
423 : : * GetTopTransactionId
424 : : *
425 : : * This will return the XID of the main transaction, assigning one if
426 : : * it's not yet set. Be careful to call this only inside a valid xact.
427 : : */
428 : : TransactionId
8185 tgl@sss.pgh.pa.us 429 : 35452 : GetTopTransactionId(void)
430 : : {
2802 tmunro@postgresql.or 431 [ + + ]: 35452 : if (!FullTransactionIdIsValid(XactTopFullTransactionId))
7024 tgl@sss.pgh.pa.us 432 : 595 : AssignTransactionId(&TopTransactionStateData);
2802 tmunro@postgresql.or 433 : 35452 : return XidFromFullTransactionId(XactTopFullTransactionId);
434 : : }
435 : :
436 : : /*
437 : : * GetTopTransactionIdIfAny
438 : : *
439 : : * This will return the XID of the main transaction, if one is assigned.
440 : : * It will return InvalidTransactionId if we are not currently inside a
441 : : * transaction, or inside a transaction that hasn't yet been assigned an XID.
442 : : */
443 : : TransactionId
7024 tgl@sss.pgh.pa.us 444 : 88103349 : GetTopTransactionIdIfAny(void)
445 : : {
2802 tmunro@postgresql.or 446 : 88103349 : return XidFromFullTransactionId(XactTopFullTransactionId);
447 : : }
448 : :
449 : : /*
450 : : * GetCurrentTransactionId
451 : : *
452 : : * This will return the XID of the current transaction (main or sub
453 : : * transaction), assigning one if it's not yet set. Be careful to call this
454 : : * only inside a valid xact.
455 : : */
456 : : TransactionId
9531 tgl@sss.pgh.pa.us 457 : 17394087 : GetCurrentTransactionId(void)
458 : : {
10674 bruce@momjian.us 459 : 17394087 : TransactionState s = CurrentTransactionState;
460 : :
2802 tmunro@postgresql.or 461 [ + + ]: 17394087 : if (!FullTransactionIdIsValid(s->fullTransactionId))
7024 tgl@sss.pgh.pa.us 462 : 183355 : AssignTransactionId(s);
2802 tmunro@postgresql.or 463 : 17394087 : return XidFromFullTransactionId(s->fullTransactionId);
464 : : }
465 : :
466 : : /*
467 : : * GetCurrentTransactionIdIfAny
468 : : *
469 : : * This will return the XID of the current sub xact, if one is assigned.
470 : : * It will return InvalidTransactionId if we are not currently inside a
471 : : * transaction, or inside a transaction that hasn't been assigned an XID yet.
472 : : */
473 : : TransactionId
7024 tgl@sss.pgh.pa.us 474 : 25009301 : GetCurrentTransactionIdIfAny(void)
475 : : {
2802 tmunro@postgresql.or 476 : 25009301 : return XidFromFullTransactionId(CurrentTransactionState->fullTransactionId);
477 : : }
478 : :
479 : : /*
480 : : * GetTopFullTransactionId
481 : : *
482 : : * This will return the FullTransactionId of the main transaction, assigning
483 : : * one if it's not yet set. Be careful to call this only inside a valid xact.
484 : : */
485 : : FullTransactionId
486 : 3400 : GetTopFullTransactionId(void)
487 : : {
488 [ + + ]: 3400 : if (!FullTransactionIdIsValid(XactTopFullTransactionId))
489 : 2116 : AssignTransactionId(&TopTransactionStateData);
490 : 3400 : return XactTopFullTransactionId;
491 : : }
492 : :
493 : : /*
494 : : * GetTopFullTransactionIdIfAny
495 : : *
496 : : * This will return the FullTransactionId of the main transaction, if one is
497 : : * assigned. It will return InvalidFullTransactionId if we are not currently
498 : : * inside a transaction, or inside a transaction that hasn't yet been assigned
499 : : * one.
500 : : */
501 : : FullTransactionId
502 : 16 : GetTopFullTransactionIdIfAny(void)
503 : : {
504 : 16 : return XactTopFullTransactionId;
505 : : }
506 : :
507 : : /*
508 : : * GetCurrentFullTransactionId
509 : : *
510 : : * This will return the FullTransactionId of the current transaction (main or
511 : : * sub transaction), assigning one if it's not yet set. Be careful to call
512 : : * this only inside a valid xact.
513 : : */
514 : : FullTransactionId
515 : 372 : GetCurrentFullTransactionId(void)
516 : : {
517 : 372 : TransactionState s = CurrentTransactionState;
518 : :
519 [ + + ]: 372 : if (!FullTransactionIdIsValid(s->fullTransactionId))
520 : 14 : AssignTransactionId(s);
521 : 372 : return s->fullTransactionId;
522 : : }
523 : :
524 : : /*
525 : : * GetCurrentFullTransactionIdIfAny
526 : : *
527 : : * This will return the FullTransactionId of the current sub xact, if one is
528 : : * assigned. It will return InvalidFullTransactionId if we are not currently
529 : : * inside a transaction, or inside a transaction that hasn't been assigned one
530 : : * yet.
531 : : */
532 : : FullTransactionId
2802 tmunro@postgresql.or 533 :UBC 0 : GetCurrentFullTransactionIdIfAny(void)
534 : : {
535 : 0 : return CurrentTransactionState->fullTransactionId;
536 : : }
537 : :
538 : : /*
539 : : * MarkCurrentTransactionIdLoggedIfAny
540 : : *
541 : : * Remember that the current xid - if it is assigned - now has been wal logged.
542 : : */
543 : : void
4736 rhaas@postgresql.org 544 :CBC 24953691 : MarkCurrentTransactionIdLoggedIfAny(void)
545 : : {
2802 tmunro@postgresql.or 546 [ + + ]: 24953691 : if (FullTransactionIdIsValid(CurrentTransactionState->fullTransactionId))
4736 rhaas@postgresql.org 547 : 24586962 : CurrentTransactionState->didLogXid = true;
548 : 24953691 : }
549 : :
550 : : /*
551 : : * IsSubxactTopXidLogPending
552 : : *
553 : : * This is used to decide whether we need to WAL log the top-level XID for
554 : : * operation in a subtransaction. We require that for logical decoding, see
555 : : * LogicalDecodingProcessRecord.
556 : : *
557 : : * This returns true if effective_wal_level is logical and we are inside
558 : : * a valid subtransaction, for which the assignment was not yet written to
559 : : * any WAL record.
560 : : */
561 : : bool
1852 akapila@postgresql.o 562 : 24962988 : IsSubxactTopXidLogPending(void)
563 : : {
564 : : /* check whether it is already logged */
565 [ + + ]: 24962988 : if (CurrentTransactionState->topXidLogged)
566 : 102151 : return false;
567 : :
568 : : /* effective_wal_level has to be logical */
569 [ + + + + ]: 24860837 : if (!XLogLogicalInfoActive())
570 : 24185410 : return false;
571 : :
572 : : /* we need to be in a transaction state */
573 [ + + ]: 675427 : if (!IsTransactionState())
574 : 4580 : return false;
575 : :
576 : : /* it has to be a subtransaction */
577 [ + + ]: 670847 : if (!IsSubTransaction())
578 : 670375 : return false;
579 : :
580 : : /* the subtransaction has to have a XID assigned */
581 [ + + ]: 472 : if (!TransactionIdIsValid(GetCurrentTransactionIdIfAny()))
582 : 8 : return false;
583 : :
584 : 464 : return true;
585 : : }
586 : :
587 : : /*
588 : : * MarkSubxactTopXidLogged
589 : : *
590 : : * Remember that the top transaction id for the current subtransaction is WAL
591 : : * logged now.
592 : : */
593 : : void
594 : 231 : MarkSubxactTopXidLogged(void)
595 : : {
596 [ - + ]: 231 : Assert(IsSubxactTopXidLogPending());
597 : :
598 : 231 : CurrentTransactionState->topXidLogged = true;
599 : 231 : }
600 : :
601 : : /*
602 : : * GetStableLatestTransactionId
603 : : *
604 : : * Get the transaction's XID if it has one, else read the next-to-be-assigned
605 : : * XID. Once we have a value, return that same value for the remainder of the
606 : : * current transaction. This is meant to provide the reference point for the
607 : : * age(xid) function, but might be useful for other maintenance tasks as well.
608 : : */
609 : : TransactionId
5314 simon@2ndQuadrant.co 610 : 119 : GetStableLatestTransactionId(void)
611 : : {
612 : : static LocalTransactionId lxid = InvalidLocalTransactionId;
613 : : static TransactionId stablexid = InvalidTransactionId;
614 : :
1000 heikki.linnakangas@i 615 [ + + ]: 119 : if (lxid != MyProc->vxid.lxid)
616 : : {
617 : 2 : lxid = MyProc->vxid.lxid;
5313 simon@2ndQuadrant.co 618 : 2 : stablexid = GetTopTransactionIdIfAny();
619 [ + - ]: 2 : if (!TransactionIdIsValid(stablexid))
2112 tmunro@postgresql.or 620 : 2 : stablexid = ReadNextTransactionId();
621 : : }
622 : :
5313 simon@2ndQuadrant.co 623 [ - + ]: 119 : Assert(TransactionIdIsValid(stablexid));
624 : :
5314 625 : 119 : return stablexid;
626 : : }
627 : :
628 : : /*
629 : : * AssignTransactionId
630 : : *
631 : : * Assigns a new permanent FullTransactionId to the given TransactionState.
632 : : * We do not assign XIDs to transactions until/unless this is called.
633 : : * Also, any parent TransactionStates that don't yet have XIDs are assigned
634 : : * one; this maintains the invariant that a child transaction has an XID
635 : : * following its parent's.
636 : : */
637 : : static void
7024 tgl@sss.pgh.pa.us 638 : 187326 : AssignTransactionId(TransactionState s)
639 : : {
6953 bruce@momjian.us 640 : 187326 : bool isSubXact = (s->parent != NULL);
641 : : ResourceOwner currentOwner;
4589 642 : 187326 : bool log_unknown_top = false;
643 : :
644 : : /* Assert that caller didn't screw up */
2802 tmunro@postgresql.or 645 [ - + ]: 187326 : Assert(!FullTransactionIdIsValid(s->fullTransactionId));
8108 tgl@sss.pgh.pa.us 646 [ - + ]: 187326 : Assert(s->state == TRANS_INPROGRESS);
647 : :
648 : : /*
649 : : * Workers synchronize transaction state at the beginning of each parallel
650 : : * operation, so we can't account for new XIDs at this point.
651 : : */
4061 rhaas@postgresql.org 652 [ + - - + ]: 187326 : if (IsInParallelMode() || IsParallelWorker())
975 tgl@sss.pgh.pa.us 653 [ # # ]:UBC 0 : ereport(ERROR,
654 : : (errcode(ERRCODE_INVALID_TRANSACTION_STATE),
655 : : errmsg("cannot assign transaction IDs during a parallel operation")));
656 : :
657 : : /*
658 : : * Ensure parent(s) have XIDs, so that a child always has an XID later
659 : : * than its parent. Mustn't recurse here, or we might get a stack
660 : : * overflow if we're at the bottom of a huge stack of subtransactions none
661 : : * of which have XIDs yet.
662 : : */
2802 tmunro@postgresql.or 663 [ + + + + ]:CBC 187326 : if (isSubXact && !FullTransactionIdIsValid(s->parent->fullTransactionId))
664 : : {
5711 bruce@momjian.us 665 : 653 : TransactionState p = s->parent;
666 : : TransactionState *parents;
667 : 653 : size_t parentOffset = 0;
668 : :
353 michael@paquier.xyz 669 : 653 : parents = palloc_array(TransactionState, s->nestingLevel);
2802 tmunro@postgresql.or 670 [ + + + + ]: 1899 : while (p != NULL && !FullTransactionIdIsValid(p->fullTransactionId))
671 : : {
5972 rhaas@postgresql.org 672 : 1246 : parents[parentOffset++] = p;
673 : 1246 : p = p->parent;
674 : : }
675 : :
676 : : /*
677 : : * This is technically a recursive call, but the recursion will never
678 : : * be more than one layer deep.
679 : : */
680 [ + + ]: 1899 : while (parentOffset != 0)
681 : 1246 : AssignTransactionId(parents[--parentOffset]);
682 : :
683 : 653 : pfree(parents);
684 : : }
685 : :
686 : : /*
687 : : * When effective_wal_level is logical, guarantee that a subtransaction's
688 : : * xid can only be seen in the WAL stream if its toplevel xid has been
689 : : * logged before. If necessary we log an xact_assignment record with fewer
690 : : * than PGPROC_MAX_CACHED_SUBXIDS. Note that it is fine if didLogXid isn't
691 : : * set for a transaction even though it appears in a WAL record, we just
692 : : * might superfluously log something. That can happen when an xid is
693 : : * included somewhere inside a wal record, but not in XLogRecord->xl_xid,
694 : : * like in xl_standby_locks.
695 : : */
4736 696 [ + + + + : 187326 : if (isSubXact && XLogLogicalInfoActive() &&
+ + ]
697 [ + + ]: 313 : !TopTransactionStateData.didLogXid)
698 : 29 : log_unknown_top = true;
699 : :
700 : : /*
701 : : * Generate a new FullTransactionId and record its xid in PGPROC and
702 : : * pg_subtrans.
703 : : *
704 : : * NB: we must make the subtrans entry BEFORE the Xid appears anywhere in
705 : : * shared storage other than PGPROC; because if there's no room for it in
706 : : * PGPROC, the subtrans entry is needed to ensure that other backends see
707 : : * the Xid as "running". See GetNewTransactionId.
708 : : */
2802 tmunro@postgresql.or 709 : 187326 : s->fullTransactionId = GetNewTransactionId(isSubXact);
4230 rhaas@postgresql.org 710 [ + + ]: 187326 : if (!isSubXact)
2802 tmunro@postgresql.or 711 : 170815 : XactTopFullTransactionId = s->fullTransactionId;
712 : :
7024 tgl@sss.pgh.pa.us 713 [ + + ]: 187326 : if (isSubXact)
2802 tmunro@postgresql.or 714 : 16511 : SubTransSetParent(XidFromFullTransactionId(s->fullTransactionId),
715 : 16511 : XidFromFullTransactionId(s->parent->fullTransactionId));
716 : :
717 : : /*
718 : : * If it's a top-level transaction, the predicate locking system needs to
719 : : * be told about it too.
720 : : */
5685 tgl@sss.pgh.pa.us 721 [ + + ]: 187326 : if (!isSubXact)
2802 tmunro@postgresql.or 722 : 170815 : RegisterPredicateLockingXid(XidFromFullTransactionId(s->fullTransactionId));
723 : :
724 : : /*
725 : : * Acquire lock on the transaction XID. (We assume this cannot block.) We
726 : : * have to ensure that the lock is assigned to the transaction's own
727 : : * ResourceOwner.
728 : : */
8108 tgl@sss.pgh.pa.us 729 : 187326 : currentOwner = CurrentResourceOwner;
3335 730 : 187326 : CurrentResourceOwner = s->curTransactionOwner;
731 : :
2802 tmunro@postgresql.or 732 : 187326 : XactLockTableInsert(XidFromFullTransactionId(s->fullTransactionId));
733 : :
8108 tgl@sss.pgh.pa.us 734 : 187326 : CurrentResourceOwner = currentOwner;
735 : :
736 : : /*
737 : : * Every PGPROC_MAX_CACHED_SUBXIDS assigned transaction ids within each
738 : : * top-level transaction we issue a WAL record for the assignment. We
739 : : * include the top-level xid and all the subxids that have not yet been
740 : : * reported using XLOG_XACT_ASSIGNMENT records.
741 : : *
742 : : * This is required to limit the amount of shared memory required in a hot
743 : : * standby server to keep track of in-progress XIDs. See notes for
744 : : * RecordKnownAssignedTransactionIds().
745 : : *
746 : : * We don't keep track of the immediate parent of each subxid, only the
747 : : * top-level transaction that each subxact belongs to. This is correct in
748 : : * recovery only because aborted subtransactions are separately WAL
749 : : * logged.
750 : : *
751 : : * This is correct even for the case where several levels above us didn't
752 : : * have an xid assigned as we recursed up to them beforehand.
753 : : */
6188 simon@2ndQuadrant.co 754 [ + + + + ]: 187326 : if (isSubXact && XLogStandbyInfoActive())
755 : : {
2802 tmunro@postgresql.or 756 : 16252 : unreportedXids[nUnreportedXids] = XidFromFullTransactionId(s->fullTransactionId);
6188 simon@2ndQuadrant.co 757 : 16252 : nUnreportedXids++;
758 : :
759 : : /*
760 : : * ensure this test matches similar one in
761 : : * RecoverPreparedTransactions()
762 : : */
4736 rhaas@postgresql.org 763 [ + + + + ]: 16252 : if (nUnreportedXids >= PGPROC_MAX_CACHED_SUBXIDS ||
764 : : log_unknown_top)
765 : : {
766 : : xl_xact_assignment xlrec;
767 : :
768 : : /*
769 : : * xtop is always set by now because we recurse up transaction
770 : : * stack to the highest unassigned xid and then come back down
771 : : */
6188 simon@2ndQuadrant.co 772 : 255 : xlrec.xtop = GetTopTransactionId();
773 [ - + ]: 255 : Assert(TransactionIdIsValid(xlrec.xtop));
774 : 255 : xlrec.nsubxacts = nUnreportedXids;
775 : :
4391 heikki.linnakangas@i 776 : 255 : XLogBeginInsert();
655 peter@eisentraut.org 777 : 255 : XLogRegisterData(&xlrec, MinSizeOfXactAssignment);
778 : 255 : XLogRegisterData(unreportedXids,
779 : : nUnreportedXids * sizeof(TransactionId));
780 : :
4391 heikki.linnakangas@i 781 : 255 : (void) XLogInsert(RM_XACT_ID, XLOG_XACT_ASSIGNMENT);
782 : :
6188 simon@2ndQuadrant.co 783 : 255 : nUnreportedXids = 0;
784 : : /* mark top, not current xact as having been logged */
4736 rhaas@postgresql.org 785 : 255 : TopTransactionStateData.didLogXid = true;
786 : : }
787 : : }
6188 simon@2ndQuadrant.co 788 : 187326 : }
789 : :
790 : : /*
791 : : * GetCurrentSubTransactionId
792 : : */
793 : : SubTransactionId
8108 tgl@sss.pgh.pa.us 794 : 2093211 : GetCurrentSubTransactionId(void)
795 : : {
796 : 2093211 : TransactionState s = CurrentTransactionState;
797 : :
798 : 2093211 : return s->subTransactionId;
799 : : }
800 : :
801 : : /*
802 : : * SubTransactionIsActive
803 : : *
804 : : * Test if the specified subxact ID is still active. Note caller is
805 : : * responsible for checking whether this ID is relevant to the current xact.
806 : : */
807 : : bool
5018 tgl@sss.pgh.pa.us 808 :UBC 0 : SubTransactionIsActive(SubTransactionId subxid)
809 : : {
810 : : TransactionState s;
811 : :
812 [ # # ]: 0 : for (s = CurrentTransactionState; s != NULL; s = s->parent)
813 : : {
814 [ # # ]: 0 : if (s->state == TRANS_ABORT)
815 : 0 : continue;
816 [ # # ]: 0 : if (s->subTransactionId == subxid)
817 : 0 : return true;
818 : : }
819 : 0 : return false;
820 : : }
821 : :
822 : :
823 : : /*
824 : : * GetCurrentCommandId
825 : : *
826 : : * "used" must be true if the caller intends to use the command ID to mark
827 : : * inserted/updated/deleted tuples. false means the ID is being fetched
828 : : * for read-only purposes (ie, as a snapshot validity cutoff). See
829 : : * CommandCounterIncrement() for discussion.
830 : : */
831 : : CommandId
6938 tgl@sss.pgh.pa.us 832 :CBC 7698895 : GetCurrentCommandId(bool used)
833 : : {
834 : : /* this is global to a transaction, not subtransaction-local */
835 [ + + ]: 7698895 : if (used)
836 : : {
837 : : /*
838 : : * Forbid setting currentCommandIdUsed in a parallel worker, because
839 : : * we have no provision for communicating this back to the leader. We
840 : : * could relax this restriction when currentCommandIdUsed was already
841 : : * true at the start of the parallel operation.
842 : : */
975 843 [ - + ]: 4418196 : if (IsParallelWorker())
975 tgl@sss.pgh.pa.us 844 [ # # ]:UBC 0 : ereport(ERROR,
845 : : (errcode(ERRCODE_INVALID_TRANSACTION_STATE),
846 : : errmsg("cannot modify data in a parallel worker")));
847 : :
6938 tgl@sss.pgh.pa.us 848 :CBC 4418196 : currentCommandIdUsed = true;
849 : : }
8108 850 : 7698895 : return currentCommandId;
851 : : }
852 : :
853 : : /*
854 : : * SetParallelStartTimestamps
855 : : *
856 : : * In a parallel worker, we should inherit the parent transaction's
857 : : * timestamps rather than setting our own. The parallel worker
858 : : * infrastructure must call this to provide those values before
859 : : * calling StartTransaction() or SetCurrentStatementStartTimestamp().
860 : : */
861 : : void
2975 862 : 2050 : SetParallelStartTimestamps(TimestampTz xact_ts, TimestampTz stmt_ts)
863 : : {
864 [ - + ]: 2050 : Assert(IsParallelWorker());
865 : 2050 : xactStartTimestamp = xact_ts;
866 : 2050 : stmtStartTimestamp = stmt_ts;
867 : 2050 : }
868 : :
869 : : /*
870 : : * GetCurrentTransactionStartTimestamp
871 : : */
872 : : TimestampTz
7822 873 : 45308 : GetCurrentTransactionStartTimestamp(void)
874 : : {
875 : 45308 : return xactStartTimestamp;
876 : : }
877 : :
878 : : /*
879 : : * GetCurrentStatementStartTimestamp
880 : : */
881 : : TimestampTz
7522 bruce@momjian.us 882 : 1451021 : GetCurrentStatementStartTimestamp(void)
883 : : {
884 : 1451021 : return stmtStartTimestamp;
885 : : }
886 : :
887 : : /*
888 : : * GetCurrentTransactionStopTimestamp
889 : : *
890 : : * If the transaction stop time hasn't already been set, which can happen if
891 : : * we decided we don't need to log an XLOG record, set xactStopTimestamp.
892 : : */
893 : : TimestampTz
7152 tgl@sss.pgh.pa.us 894 : 1381212 : GetCurrentTransactionStopTimestamp(void)
895 : : {
1506 andres@anarazel.de 896 : 1381212 : TransactionState s PG_USED_FOR_ASSERTS_ONLY = CurrentTransactionState;
897 : :
898 : : /* should only be called after commit / abort processing */
899 [ + + + + : 1381212 : Assert(s->state == TRANS_DEFAULT ||
- + - - ]
900 : : s->state == TRANS_COMMIT ||
901 : : s->state == TRANS_ABORT ||
902 : : s->state == TRANS_PREPARE);
903 : :
904 [ + + ]: 1381212 : if (xactStopTimestamp == 0)
905 : 385053 : xactStopTimestamp = GetCurrentTimestamp();
906 : :
907 : 1381212 : return xactStopTimestamp;
908 : : }
909 : :
910 : : /*
911 : : * SetCurrentStatementStartTimestamp
912 : : *
913 : : * In a parallel worker, this should already have been provided by a call
914 : : * to SetParallelStartTimestamps().
915 : : */
916 : : void
7522 bruce@momjian.us 917 : 673181 : SetCurrentStatementStartTimestamp(void)
918 : : {
2975 tgl@sss.pgh.pa.us 919 [ + + ]: 673181 : if (!IsParallelWorker())
920 : 671131 : stmtStartTimestamp = GetCurrentTimestamp();
921 : : else
922 [ - + ]: 2050 : Assert(stmtStartTimestamp != 0);
7522 bruce@momjian.us 923 : 673181 : }
924 : :
925 : : /*
926 : : * GetCurrentTransactionNestLevel
927 : : *
928 : : * Note: this will return zero when not inside any transaction, one when
929 : : * inside a top-level transaction, etc.
930 : : */
931 : : int
8185 tgl@sss.pgh.pa.us 932 : 26333813 : GetCurrentTransactionNestLevel(void)
933 : : {
934 : 26333813 : TransactionState s = CurrentTransactionState;
935 : :
936 : 26333813 : return s->nestingLevel;
937 : : }
938 : :
939 : :
940 : : /*
941 : : * TransactionIdIsCurrentTransactionId
942 : : */
943 : : bool
11099 scrappy@hub.org 944 : 88284463 : TransactionIdIsCurrentTransactionId(TransactionId xid)
945 : : {
946 : : TransactionState s;
947 : :
948 : : /*
949 : : * We always say that BootstrapTransactionId is "not my transaction ID"
950 : : * even when it is (ie, during bootstrap). Along with the fact that
951 : : * transam.c always treats BootstrapTransactionId as already committed,
952 : : * this causes the heapam_visibility.c routines to see all tuples as
953 : : * committed, which is what we need during bootstrap. (Bootstrap mode
954 : : * only inserts tuples, it never updates or deletes them, so all tuples
955 : : * can be presumed good immediately.)
956 : : *
957 : : * Likewise, InvalidTransactionId and FrozenTransactionId are certainly
958 : : * not my transaction ID, so we can just return "false" immediately for
959 : : * any non-normal XID.
960 : : */
7328 tgl@sss.pgh.pa.us 961 [ + + ]: 88284463 : if (!TransactionIdIsNormal(xid))
10674 bruce@momjian.us 962 : 771023 : return false;
963 : :
2574 tmunro@postgresql.or 964 [ + + ]: 87513440 : if (TransactionIdEquals(xid, GetTopTransactionIdIfAny()))
965 : 63199682 : return true;
966 : :
967 : : /*
968 : : * In parallel workers, the XIDs we must consider as current are stored in
969 : : * ParallelCurrentXids rather than the transaction-state stack. Note that
970 : : * the XIDs in this array are sorted numerically rather than according to
971 : : * transactionIdPrecedes order.
972 : : */
4230 rhaas@postgresql.org 973 [ + + ]: 24313758 : if (nParallelCurrentXids > 0)
974 : : {
975 : : int low,
976 : : high;
977 : :
978 : 4956473 : low = 0;
979 : 4956473 : high = nParallelCurrentXids - 1;
980 [ + + ]: 19527118 : while (low <= high)
981 : : {
982 : : int middle;
983 : : TransactionId probe;
984 : :
985 : 19377847 : middle = low + (high - low) / 2;
986 : 19377847 : probe = ParallelCurrentXids[middle];
987 [ + + ]: 19377847 : if (probe == xid)
988 : 4807202 : return true;
989 [ + + ]: 14570645 : else if (probe < xid)
990 : 14421380 : low = middle + 1;
991 : : else
992 : 149265 : high = middle - 1;
993 : : }
994 : 149271 : return false;
995 : : }
996 : :
997 : : /*
998 : : * We will return true for the Xid of the current subtransaction, any of
999 : : * its subcommitted children, any of its parents, or any of their
1000 : : * previously subcommitted children. However, a transaction being aborted
1001 : : * is no longer "current", even though it may still have an entry on the
1002 : : * state stack.
1003 : : */
8127 tgl@sss.pgh.pa.us 1004 [ + + ]: 38632696 : for (s = CurrentTransactionState; s != NULL; s = s->parent)
1005 : : {
1006 : : int low,
1007 : : high;
1008 : :
1009 [ - + ]: 19442709 : if (s->state == TRANS_ABORT)
8127 tgl@sss.pgh.pa.us 1010 :UBC 0 : continue;
2802 tmunro@postgresql.or 1011 [ + + ]:CBC 19442709 : if (!FullTransactionIdIsValid(s->fullTransactionId))
8108 tgl@sss.pgh.pa.us 1012 : 6332345 : continue; /* it can't have any child XIDs either */
2802 tmunro@postgresql.or 1013 [ + + ]: 13110364 : if (TransactionIdEquals(xid, XidFromFullTransactionId(s->fullTransactionId)))
8185 tgl@sss.pgh.pa.us 1014 : 164238 : return true;
1015 : : /* As the childXids array is ordered, we can use binary search */
6830 1016 : 12946126 : low = 0;
1017 : 12946126 : high = s->nChildXids - 1;
1018 [ + + ]: 12947021 : while (low <= high)
1019 : : {
1020 : : int middle;
1021 : : TransactionId probe;
1022 : :
1023 : 3955 : middle = low + (high - low) / 2;
1024 : 3955 : probe = s->childXids[middle];
1025 [ + + ]: 3955 : if (TransactionIdEquals(probe, xid))
8185 1026 : 3060 : return true;
6830 1027 [ + + ]: 895 : else if (TransactionIdPrecedes(probe, xid))
1028 : 803 : low = middle + 1;
1029 : : else
1030 : 92 : high = middle - 1;
1031 : : }
1032 : : }
1033 : :
8185 1034 : 19189987 : return false;
1035 : : }
1036 : :
1037 : : /*
1038 : : * TransactionStartedDuringRecovery
1039 : : *
1040 : : * Returns true if the current transaction started while recovery was still
1041 : : * in progress. Recovery might have ended since so RecoveryInProgress() might
1042 : : * return false already.
1043 : : */
1044 : : bool
6188 simon@2ndQuadrant.co 1045 : 9694424 : TransactionStartedDuringRecovery(void)
1046 : : {
1047 : 9694424 : return CurrentTransactionState->startedInRecovery;
1048 : : }
1049 : :
1050 : : /*
1051 : : * GetTopReadOnlyTransactionNestLevel
1052 : : *
1053 : : * Note: this will return zero when not inside any transaction or when neither
1054 : : * a top-level transaction nor subtransactions are read-only, one when the
1055 : : * top-level transaction is read-only, two when one level of subtransaction is
1056 : : * read-only, etc.
1057 : : *
1058 : : * Note: subtransactions of the topmost read-only transaction are also
1059 : : * read-only, because they inherit read-only mode from the transaction, and
1060 : : * thus can't change to read-write mode (see check_transaction_read_only).
1061 : : */
1062 : : int
237 efujita@postgresql.o 1063 : 9 : GetTopReadOnlyTransactionNestLevel(void)
1064 : : {
1065 : 9 : TransactionState s = CurrentTransactionState;
1066 : :
1067 [ - + ]: 9 : if (!XactReadOnly)
237 efujita@postgresql.o 1068 :UBC 0 : return 0;
237 efujita@postgresql.o 1069 [ + + ]:CBC 10 : while (s->nestingLevel > 1)
1070 : : {
1071 [ + + ]: 4 : if (!s->prevXactReadOnly)
1072 : 3 : return s->nestingLevel;
1073 : 1 : s = s->parent;
1074 : : }
1075 : 6 : return s->nestingLevel;
1076 : : }
1077 : :
1078 : : /*
1079 : : * EnterParallelMode
1080 : : */
1081 : : void
4230 rhaas@postgresql.org 1082 : 4748 : EnterParallelMode(void)
1083 : : {
1084 : 4748 : TransactionState s = CurrentTransactionState;
1085 : :
1086 [ - + ]: 4748 : Assert(s->parallelModeLevel >= 0);
1087 : :
1088 : 4748 : ++s->parallelModeLevel;
1089 : 4748 : }
1090 : :
1091 : : /*
1092 : : * ExitParallelMode
1093 : : */
1094 : : void
1095 : 2687 : ExitParallelMode(void)
1096 : : {
1097 : 2687 : TransactionState s = CurrentTransactionState;
1098 : :
1099 [ - + ]: 2687 : Assert(s->parallelModeLevel > 0);
975 tgl@sss.pgh.pa.us 1100 [ + + + - : 2687 : Assert(s->parallelModeLevel > 1 || s->parallelChildXact ||
- + ]
1101 : : !ParallelContextActive());
1102 : :
4230 rhaas@postgresql.org 1103 : 2687 : --s->parallelModeLevel;
1104 : 2687 : }
1105 : :
1106 : : /*
1107 : : * IsInParallelMode
1108 : : *
1109 : : * Are we in a parallel operation, as either the leader or a worker? Check
1110 : : * this to prohibit operations that change backend-local state expected to
1111 : : * match across all workers. Mere caches usually don't require such a
1112 : : * restriction. State modified in a strict push/pop fashion, such as the
1113 : : * active snapshot stack, is often fine.
1114 : : *
1115 : : * We say we are in parallel mode if we are in a subxact of a transaction
1116 : : * that's initiated a parallel operation; for most purposes that context
1117 : : * has all the same restrictions.
1118 : : */
1119 : : bool
1120 : 7630606 : IsInParallelMode(void)
1121 : : {
975 tgl@sss.pgh.pa.us 1122 : 7630606 : TransactionState s = CurrentTransactionState;
1123 : :
1124 [ + + + + ]: 7630606 : return s->parallelModeLevel != 0 || s->parallelChildXact;
1125 : : }
1126 : :
1127 : : /*
1128 : : * CommandCounterIncrement
1129 : : */
1130 : : void
9531 1131 : 2018553 : CommandCounterIncrement(void)
1132 : : {
1133 : : /*
1134 : : * If the current value of the command counter hasn't been "used" to mark
1135 : : * tuples, we need not increment it, since there's no need to distinguish
1136 : : * a read-only command from others. This helps postpone command counter
1137 : : * overflow, and keeps no-op CommandCounterIncrement operations cheap.
1138 : : */
6938 1139 [ + + ]: 2018553 : if (currentCommandIdUsed)
1140 : : {
1141 : : /*
1142 : : * Workers synchronize transaction state at the beginning of each
1143 : : * parallel operation, so we can't account for new commands after that
1144 : : * point.
1145 : : */
4061 rhaas@postgresql.org 1146 [ + - - + ]: 747947 : if (IsInParallelMode() || IsParallelWorker())
975 tgl@sss.pgh.pa.us 1147 [ # # ]:UBC 0 : ereport(ERROR,
1148 : : (errcode(ERRCODE_INVALID_TRANSACTION_STATE),
1149 : : errmsg("cannot start commands during a parallel operation")));
1150 : :
6938 tgl@sss.pgh.pa.us 1151 :CBC 747947 : currentCommandId += 1;
4828 rhaas@postgresql.org 1152 [ - + ]: 747947 : if (currentCommandId == InvalidCommandId)
1153 : : {
6938 tgl@sss.pgh.pa.us 1154 :UBC 0 : currentCommandId -= 1;
1155 [ # # ]: 0 : ereport(ERROR,
1156 : : (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
1157 : : errmsg("cannot have more than 2^32-2 commands in a transaction")));
1158 : : }
6938 tgl@sss.pgh.pa.us 1159 :CBC 747947 : currentCommandIdUsed = false;
1160 : :
1161 : : /* Propagate new command ID into static snapshots */
6774 alvherre@alvh.no-ip. 1162 : 747947 : SnapshotSetCommandId(currentCommandId);
1163 : :
1164 : : /*
1165 : : * Make any catalog changes done by the just-completed command visible
1166 : : * in the local syscache. We obviously don't need to do this after a
1167 : : * read-only command. (But see hacks in inval.c to make real sure we
1168 : : * don't think a command that queued inval messages was read-only.)
1169 : : */
6138 tgl@sss.pgh.pa.us 1170 : 747947 : AtCCI_LocalCache();
1171 : : }
11099 scrappy@hub.org 1172 : 2018549 : }
1173 : :
1174 : : /*
1175 : : * ForceSyncCommit
1176 : : *
1177 : : * Interface routine to allow commands to force a synchronous commit of the
1178 : : * current top-level transaction. Currently, two-phase commit does not
1179 : : * persist and restore this variable. So long as all callers use
1180 : : * PreventInTransactionBlock(), that omission has no consequences.
1181 : : */
1182 : : void
7059 tgl@sss.pgh.pa.us 1183 : 624 : ForceSyncCommit(void)
1184 : : {
1185 : 624 : forceSyncCommit = true;
1186 : 624 : }
1187 : :
1188 : :
1189 : : /* ----------------------------------------------------------------
1190 : : * StartTransaction stuff
1191 : : * ----------------------------------------------------------------
1192 : : */
1193 : :
1194 : : /*
1195 : : * AtStart_Cache
1196 : : */
1197 : : static void
9531 1198 : 442075 : AtStart_Cache(void)
1199 : : {
9293 1200 : 442075 : AcceptInvalidationMessages();
11099 scrappy@hub.org 1201 : 442075 : }
1202 : :
1203 : : /*
1204 : : * AtStart_Memory
1205 : : */
1206 : : static void
9531 tgl@sss.pgh.pa.us 1207 : 442075 : AtStart_Memory(void)
1208 : : {
8185 1209 : 442075 : TransactionState s = CurrentTransactionState;
1210 : :
1211 : : /*
1212 : : * Remember the memory context that was active prior to transaction start.
1213 : : */
880 1214 : 442075 : s->priorContext = CurrentMemoryContext;
1215 : :
1216 : : /*
1217 : : * If this is the first time through, create a private context for
1218 : : * AbortTransaction to work in. By reserving some space now, we can
1219 : : * insulate AbortTransaction from out-of-memory scenarios. Like
1220 : : * ErrorContext, we set it up with slow growth rate and a nonzero minimum
1221 : : * size, so that space will be reserved immediately.
1222 : : */
7310 1223 [ + + ]: 442075 : if (TransactionAbortContext == NULL)
1224 : 20251 : TransactionAbortContext =
2969 1225 : 20251 : AllocSetContextCreate(TopMemoryContext,
1226 : : "TransactionAbortContext",
1227 : : 32 * 1024,
1228 : : 32 * 1024,
1229 : : 32 * 1024);
1230 : :
1231 : : /*
1232 : : * Likewise, if this is the first time through, create a top-level context
1233 : : * for transaction-local data. This context will be reset at transaction
1234 : : * end, and then re-used in later transactions.
1235 : : */
880 1236 [ + + ]: 442075 : if (TopTransactionContext == NULL)
1237 : 20251 : TopTransactionContext =
1238 : 20251 : AllocSetContextCreate(TopMemoryContext,
1239 : : "TopTransactionContext",
1240 : : ALLOCSET_DEFAULT_SIZES);
1241 : :
1242 : : /*
1243 : : * In a top-level transaction, CurTransactionContext is the same as
1244 : : * TopTransactionContext.
1245 : : */
8185 1246 : 442075 : CurTransactionContext = TopTransactionContext;
1247 : 442075 : s->curTransactionContext = CurTransactionContext;
1248 : :
1249 : : /* Make the CurTransactionContext active. */
1250 : 442075 : MemoryContextSwitchTo(CurTransactionContext);
11099 scrappy@hub.org 1251 : 442075 : }
1252 : :
1253 : : /*
1254 : : * AtStart_ResourceOwner
1255 : : */
1256 : : static void
8169 tgl@sss.pgh.pa.us 1257 : 442075 : AtStart_ResourceOwner(void)
1258 : : {
1259 : 442075 : TransactionState s = CurrentTransactionState;
1260 : :
1261 : : /*
1262 : : * We shouldn't have a transaction resource owner already.
1263 : : */
1264 [ - + ]: 442075 : Assert(TopTransactionResourceOwner == NULL);
1265 : :
1266 : : /*
1267 : : * Create a toplevel resource owner for the transaction.
1268 : : */
1269 : 442075 : s->curTransactionOwner = ResourceOwnerCreate(NULL, "TopTransaction");
1270 : :
1271 : 442075 : TopTransactionResourceOwner = s->curTransactionOwner;
1272 : 442075 : CurTransactionResourceOwner = s->curTransactionOwner;
1273 : 442075 : CurrentResourceOwner = s->curTransactionOwner;
1274 : 442075 : }
1275 : :
1276 : : /* ----------------------------------------------------------------
1277 : : * StartSubTransaction stuff
1278 : : * ----------------------------------------------------------------
1279 : : */
1280 : :
1281 : : /*
1282 : : * AtSubStart_Memory
1283 : : */
1284 : : static void
8185 1285 : 23131 : AtSubStart_Memory(void)
1286 : : {
1287 : 23131 : TransactionState s = CurrentTransactionState;
1288 : :
1289 [ - + ]: 23131 : Assert(CurTransactionContext != NULL);
1290 : :
1291 : : /*
1292 : : * Remember the context that was active prior to subtransaction start.
1293 : : */
880 1294 : 23131 : s->priorContext = CurrentMemoryContext;
1295 : :
1296 : : /*
1297 : : * Create a CurTransactionContext, which will be used to hold data that
1298 : : * survives subtransaction commit but disappears on subtransaction abort.
1299 : : * We make it a child of the immediate parent's CurTransactionContext.
1300 : : */
8185 1301 : 23131 : CurTransactionContext = AllocSetContextCreate(CurTransactionContext,
1302 : : "CurTransactionContext",
1303 : : ALLOCSET_DEFAULT_SIZES);
1304 : 23131 : s->curTransactionContext = CurTransactionContext;
1305 : :
1306 : : /* Make the CurTransactionContext active. */
1307 : 23131 : MemoryContextSwitchTo(CurTransactionContext);
1308 : 23131 : }
1309 : :
1310 : : /*
1311 : : * AtSubStart_ResourceOwner
1312 : : */
1313 : : static void
8169 1314 : 23131 : AtSubStart_ResourceOwner(void)
1315 : : {
1316 : 23131 : TransactionState s = CurrentTransactionState;
1317 : :
1318 [ - + ]: 23131 : Assert(s->parent != NULL);
1319 : :
1320 : : /*
1321 : : * Create a resource owner for the subtransaction. We make it a child of
1322 : : * the immediate parent's resource owner.
1323 : : */
1324 : 23131 : s->curTransactionOwner =
1325 : 23131 : ResourceOwnerCreate(s->parent->curTransactionOwner,
1326 : : "SubTransaction");
1327 : :
1328 : 23131 : CurTransactionResourceOwner = s->curTransactionOwner;
1329 : 23131 : CurrentResourceOwner = s->curTransactionOwner;
1330 : 23131 : }
1331 : :
1332 : : /* ----------------------------------------------------------------
1333 : : * CommitTransaction stuff
1334 : : * ----------------------------------------------------------------
1335 : : */
1336 : :
1337 : : /*
1338 : : * RecordTransactionCommit
1339 : : *
1340 : : * Returns latest XID among xact and its children, or InvalidTransactionId
1341 : : * if the xact has no XID. (We compute that here just because it's easier.)
1342 : : *
1343 : : * If you change this function, see RecordTransactionCommitPrepared also.
1344 : : */
1345 : : static TransactionId
6137 1346 : 402568 : RecordTransactionCommit(void)
1347 : : {
7024 1348 : 402568 : TransactionId xid = GetTopTransactionIdIfAny();
6953 bruce@momjian.us 1349 : 402568 : bool markXidCommitted = TransactionIdIsValid(xid);
7021 tgl@sss.pgh.pa.us 1350 : 402568 : TransactionId latestXid = InvalidTransactionId;
1351 : : int nrels;
1352 : : RelFileLocator *rels;
1353 : : int nchildren;
1354 : : TransactionId *children;
1697 andres@anarazel.de 1355 : 402568 : int ndroppedstats = 0;
1356 : 402568 : xl_xact_stats_item *droppedstats = NULL;
5951 rhaas@postgresql.org 1357 : 402568 : int nmsgs = 0;
6188 simon@2ndQuadrant.co 1358 : 402568 : SharedInvalidationMessage *invalMessages = NULL;
5951 rhaas@postgresql.org 1359 : 402568 : bool RelcacheInitFileInval = false;
1360 : : bool wrote_xlog;
1361 : :
1362 : : /*
1363 : : * Log pending invalidations for logical decoding of in-progress
1364 : : * transactions. Normally for DDLs, we log this at each command end,
1365 : : * however, for certain cases where we directly update the system table
1366 : : * without a transaction block, the invalidations are not logged till this
1367 : : * time.
1368 : : */
2319 akapila@postgresql.o 1369 [ + + + + ]: 402568 : if (XLogLogicalInfoActive())
1370 : 16307 : LogLogicalInvalidations();
1371 : :
1372 : : /* Get data needed for commit record */
5951 rhaas@postgresql.org 1373 : 402568 : nrels = smgrGetPendingDeletes(true, &rels);
8169 tgl@sss.pgh.pa.us 1374 : 402568 : nchildren = xactGetCommittedChildren(&children);
1697 andres@anarazel.de 1375 : 402568 : ndroppedstats = pgstat_get_transactional_drops(true, &droppedstats);
5951 rhaas@postgresql.org 1376 [ + + ]: 402568 : if (XLogStandbyInfoActive())
1377 : 337144 : nmsgs = xactGetCommittedInvalidationMessages(&invalMessages,
1378 : : &RelcacheInitFileInval);
5270 heikki.linnakangas@i 1379 : 402568 : wrote_xlog = (XactLastRecEnd != 0);
1380 : :
1381 : : /* Load the injection point before entering the critical section */
65 alvherre@kurilemu.de 1382 : 402568 : INJECTION_POINT_LOAD("commit-before-clog-update");
1383 : :
1384 : : /*
1385 : : * If we haven't been assigned an XID yet, we neither can, nor do we want
1386 : : * to write a COMMIT record.
1387 : : */
7024 tgl@sss.pgh.pa.us 1388 [ + + ]: 402568 : if (!markXidCommitted)
1389 : : {
1390 : : /*
1391 : : * We expect that every RelationDropStorage is followed by a catalog
1392 : : * update, and hence XID assignment, so we shouldn't get here with any
1393 : : * pending deletes. Same is true for dropping stats.
1394 : : *
1395 : : * Use a real test not just an Assert to check this, since it's a bit
1396 : : * fragile.
1397 : : */
1697 andres@anarazel.de 1398 [ + - - + ]: 241116 : if (nrels != 0 || ndroppedstats != 0)
7024 tgl@sss.pgh.pa.us 1399 [ # # ]:UBC 0 : elog(ERROR, "cannot commit a transaction that deleted files but has no xid");
1400 : :
1401 : : /* Can't have child XIDs either; AssignTransactionId enforces this */
7024 tgl@sss.pgh.pa.us 1402 [ - + ]:CBC 241116 : Assert(nchildren == 0);
1403 : :
1404 : : /*
1405 : : * Transactions without an assigned xid can contain invalidation
1406 : : * messages. While inplace updates do this, this is not known to be
1407 : : * necessary; see comment at inplace CacheInvalidateHeapTuple().
1408 : : * Extensions might still rely on this capability, and standbys may
1409 : : * need to process those invals. We can't emit a commit record
1410 : : * without an xid, and we don't want to force assigning an xid,
1411 : : * because that'd be problematic for e.g. vacuum. Hence we emit a
1412 : : * bespoke record for the invalidations. We don't want to use that in
1413 : : * case a commit record is emitted, so they happen synchronously with
1414 : : * commits (besides not wanting to emit more WAL records).
1415 : : *
1416 : : * XXX Every known use of this capability is a defect. Since an XID
1417 : : * isn't controlling visibility of the change that prompted invals,
1418 : : * other sessions need the inval even if this transactions aborts.
1419 : : *
1420 : : * ON COMMIT DELETE ROWS does a nontransactional index_build(), which
1421 : : * queues a relcache inval, including in transactions without an xid
1422 : : * that had read the (empty) table. Standbys don't need any ON COMMIT
1423 : : * DELETE ROWS invals, but we've not done the work to withhold them.
1424 : : */
3871 andres@anarazel.de 1425 [ + + ]: 241116 : if (nmsgs != 0)
1426 : : {
1427 : 11757 : LogStandbyInvalidations(nmsgs, invalMessages,
1428 : : RelcacheInitFileInval);
3824 rhaas@postgresql.org 1429 : 11757 : wrote_xlog = true; /* not strictly necessary */
1430 : : }
1431 : :
1432 : : /*
1433 : : * If we didn't create XLOG entries, we're done here; otherwise we
1434 : : * should trigger flushing those entries the same as a commit record
1435 : : * would. This will primarily happen for HOT pruning and the like; we
1436 : : * want these to be flushed to disk in due time.
1437 : : */
5822 1438 [ + + ]: 241116 : if (!wrote_xlog)
7024 tgl@sss.pgh.pa.us 1439 : 211987 : goto cleanup;
1440 : : }
1441 : : else
1442 : : {
1443 : : bool replorigin;
1444 : :
1445 : : /*
1446 : : * Are we using the replication origins feature? Or, in other words,
1447 : : * are we replaying remote actions?
1448 : : */
304 msawada@postgresql.o 1449 [ + + ]: 162571 : replorigin = (replorigin_xact_state.origin != InvalidReplOriginId &&
1450 [ + - ]: 1119 : replorigin_xact_state.origin != DoNotReplicateId);
1451 : :
1452 : : /*
1453 : : * Mark ourselves as within our "commit critical section". This
1454 : : * forces any concurrent checkpoint to wait until we've updated
1455 : : * pg_xact. Without this, it is possible for the checkpoint to set
1456 : : * REDO after the XLOG record but fail to flush the pg_xact update to
1457 : : * disk, leading to loss of the transaction commit if the system
1458 : : * crashes a little later.
1459 : : *
1460 : : * Note: we could, but don't bother to, set this flag in
1461 : : * RecordTransactionAbort. That's because loss of a transaction abort
1462 : : * is noncritical; the presumption would be that it aborted, anyway.
1463 : : *
1464 : : * It's safe to change the delayChkptFlags flag of our own backend
1465 : : * without holding the ProcArrayLock, since we're the only one
1466 : : * modifying it. This makes checkpoint's determination of which xacts
1467 : : * are delaying the checkpoint a bit fuzzy, but it doesn't matter.
1468 : : *
1469 : : * Note, it is important to get the commit timestamp after marking the
1470 : : * transaction in the commit critical section. See
1471 : : * RecordTransactionCommitPrepared.
1472 : : */
493 akapila@postgresql.o 1473 [ - + ]: 161452 : Assert((MyProc->delayChkptFlags & DELAY_CHKPT_IN_COMMIT) == 0);
7024 tgl@sss.pgh.pa.us 1474 : 161452 : START_CRIT_SECTION();
493 akapila@postgresql.o 1475 : 161452 : MyProc->delayChkptFlags |= DELAY_CHKPT_IN_COMMIT;
1476 : :
1477 [ - + ]: 161452 : Assert(xactStopTimestamp == 0);
1478 : :
1479 : : /*
1480 : : * Ensures the DELAY_CHKPT_IN_COMMIT flag write is globally visible
1481 : : * before commit time is written.
1482 : : */
1483 : 161452 : pg_write_barrier();
1484 : :
1485 : : /*
1486 : : * Insert the commit XLOG record.
1487 : : */
1506 andres@anarazel.de 1488 : 161452 : XactLogCommitRecord(GetCurrentTransactionStopTimestamp(),
1489 : : nchildren, children, nrels, rels,
1490 : : ndroppedstats, droppedstats,
1491 : : nmsgs, invalMessages,
1492 : : RelcacheInitFileInval,
1493 : : MyXactFlags,
1494 : : InvalidTransactionId, NULL /* plain commit */ );
1495 : :
4078 alvherre@alvh.no-ip. 1496 [ + + ]: 161452 : if (replorigin)
1497 : : /* Move LSNs forward for this replication origin */
304 msawada@postgresql.o 1498 : 1119 : replorigin_session_advance(replorigin_xact_state.origin_lsn,
1499 : : XactLastRecEnd);
1500 : :
1501 : : /*
1502 : : * Record commit timestamp. The value comes from plain commit
1503 : : * timestamp if there's no replication origin; otherwise, the
1504 : : * timestamp was already set in replorigin_xact_state.origin_timestamp
1505 : : * by replication.
1506 : : *
1507 : : * We don't need to WAL-log anything here, as the commit record
1508 : : * written above already contains the data.
1509 : : */
1510 : :
1511 [ + + + + ]: 161452 : if (!replorigin || replorigin_xact_state.origin_timestamp == 0)
1512 : 160444 : replorigin_xact_state.origin_timestamp = GetCurrentTransactionStopTimestamp();
1513 : :
4378 alvherre@alvh.no-ip. 1514 : 161452 : TransactionTreeSetCommitTsData(xid, nchildren, children,
1515 : : replorigin_xact_state.origin_timestamp,
304 msawada@postgresql.o 1516 : 161452 : replorigin_xact_state.origin);
1517 : : }
1518 : :
1519 : : /*
1520 : : * Check if we want to commit asynchronously. We can allow the XLOG flush
1521 : : * to happen asynchronously if synchronous_commit=off, or if the current
1522 : : * transaction has not performed any WAL-logged operation or didn't assign
1523 : : * an xid. The transaction can end up not writing any WAL, even if it has
1524 : : * an xid, if it only wrote to temporary and/or unlogged tables. It can
1525 : : * end up having written WAL without an xid if it did HOT pruning. In
1526 : : * case of a crash, the loss of such a transaction will be irrelevant;
1527 : : * temp tables will be lost anyway, unlogged tables will be truncated and
1528 : : * HOT pruning will be done again later. (Given the foregoing, you might
1529 : : * think that it would be unnecessary to emit the XLOG record at all in
1530 : : * this case, but we don't currently try to do that. It would certainly
1531 : : * cause problems at least in Hot Standby mode, where the
1532 : : * KnownAssignedXids machinery requires tracking every XID assignment. It
1533 : : * might be OK to skip it only when wal_level < replica, but for now we
1534 : : * don't.)
1535 : : *
1536 : : * However, if we're doing cleanup of any non-temp rels or committing any
1537 : : * command that wanted to force sync commit, then we must flush XLOG
1538 : : * immediately. (We must not allow asynchronous commit if there are any
1539 : : * non-temp tables to be deleted, because we might delete the files before
1540 : : * the COMMIT record is flushed to disk. We do allow asynchronous commit
1541 : : * if all to-be-deleted tables are temporary though, since they are lost
1542 : : * anyway if we crash.)
1543 : : */
4293 andres@anarazel.de 1544 [ + + + + ]: 190581 : if ((wrote_xlog && markXidCommitted &&
1545 [ + + + + ]: 190581 : synchronous_commit > SYNCHRONOUS_COMMIT_OFF) ||
5717 rhaas@postgresql.org 1546 [ + + ]: 36548 : forceSyncCommit || nrels > 0)
1547 : : {
7024 tgl@sss.pgh.pa.us 1548 : 154053 : XLogFlush(XactLastRecEnd);
1549 : :
1550 : : /*
1551 : : * The commit record is on disk, but not in CLOG yet. A test can stop
1552 : : * here to see what others make of the transaction meanwhile.
1553 : : */
65 alvherre@kurilemu.de 1554 : 154053 : INJECTION_POINT_CACHED("commit-before-clog-update", NULL);
1555 : :
1556 : : /*
1557 : : * Now we may update the CLOG, if we wrote a COMMIT record above
1558 : : */
7024 tgl@sss.pgh.pa.us 1559 [ + - ]: 154053 : if (markXidCommitted)
6613 alvherre@alvh.no-ip. 1560 : 154053 : TransactionIdCommitTree(xid, nchildren, children);
1561 : : }
1562 : : else
1563 : : {
1564 : : /*
1565 : : * Asynchronous commit case:
1566 : : *
1567 : : * This enables possible committed transaction loss in the case of a
1568 : : * postmaster crash because WAL buffers are left unwritten. Ideally we
1569 : : * could issue the WAL write without the fsync, but some
1570 : : * wal_sync_methods do not allow separate write/fsync.
1571 : : *
1572 : : * Report the latest async commit LSN, so that the WAL writer knows to
1573 : : * flush this commit.
1574 : : */
5966 simon@2ndQuadrant.co 1575 : 36528 : XLogSetAsyncXactLSN(XactLastRecEnd);
1576 : :
1577 : : /*
1578 : : * We must not immediately update the CLOG, since we didn't flush the
1579 : : * XLOG. Instead, we store the LSN up to which the XLOG must be
1580 : : * flushed before the CLOG may be updated.
1581 : : */
7024 tgl@sss.pgh.pa.us 1582 [ + + ]: 36528 : if (markXidCommitted)
6613 alvherre@alvh.no-ip. 1583 : 7399 : TransactionIdAsyncCommitTree(xid, nchildren, children, XactLastRecEnd);
1584 : : }
1585 : :
1586 : : /*
1587 : : * If we entered a commit critical section, leave it now, and let
1588 : : * checkpoints proceed.
1589 : : */
7024 tgl@sss.pgh.pa.us 1590 [ + + ]: 190581 : if (markXidCommitted)
1591 : : {
493 akapila@postgresql.o 1592 : 161452 : MyProc->delayChkptFlags &= ~DELAY_CHKPT_IN_COMMIT;
9451 tgl@sss.pgh.pa.us 1593 [ - + ]: 161452 : END_CRIT_SECTION();
1594 : : }
1595 : :
1596 : : /* Compute latestXid while we have the child XIDs handy */
7021 1597 : 190581 : latestXid = TransactionIdLatest(xid, nchildren, children);
1598 : :
1599 : : /*
1600 : : * Wait for synchronous replication, if required. Similar to the decision
1601 : : * above about using committing asynchronously we only want to wait if
1602 : : * this backend assigned an xid and wrote WAL. No need to wait if an xid
1603 : : * was assigned due to temporary/unlogged tables or due to HOT pruning.
1604 : : *
1605 : : * Note that at this stage we have marked clog, but still show as running
1606 : : * in the procarray and continue to hold locks.
1607 : : */
4293 andres@anarazel.de 1608 [ + + + + ]: 190581 : if (wrote_xlog && markXidCommitted)
3896 rhaas@postgresql.org 1609 : 156687 : SyncRepWaitForLSN(XactLastRecEnd, true);
1610 : :
1611 : : /* remember end of last commit record */
4231 andres@anarazel.de 1612 : 190581 : XactLastCommitEnd = XactLastRecEnd;
1613 : :
1614 : : /* Reset XactLastRecEnd until the next transaction writes something */
5270 heikki.linnakangas@i 1615 : 190581 : XactLastRecEnd = 0;
7024 tgl@sss.pgh.pa.us 1616 : 402568 : cleanup:
1617 : : /* Clean up local data */
7834 1618 [ + + ]: 402568 : if (rels)
1619 : 13047 : pfree(rels);
1697 andres@anarazel.de 1620 [ + + ]: 402568 : if (ndroppedstats)
1621 : 16143 : pfree(droppedstats);
1622 : :
7021 tgl@sss.pgh.pa.us 1623 : 402568 : return latestXid;
1624 : : }
1625 : :
1626 : :
1627 : : /*
1628 : : * AtCCI_LocalCache
1629 : : */
1630 : : static void
6138 1631 : 747947 : AtCCI_LocalCache(void)
1632 : : {
1633 : : /*
1634 : : * Make any pending relation map changes visible. We must do this before
1635 : : * processing local sinval messages, so that the map changes will get
1636 : : * reflected into the relcache when relcache invals are processed.
1637 : : */
1638 : 747947 : AtCCI_RelationMap();
1639 : :
1640 : : /*
1641 : : * Make catalog changes visible to me for the next command.
1642 : : */
8185 1643 : 747947 : CommandEndInvalidationMessages();
9819 inoue@tpf.co.jp 1644 : 747943 : }
1645 : :
1646 : : /*
1647 : : * AtCommit_Memory
1648 : : */
1649 : : static void
9531 tgl@sss.pgh.pa.us 1650 : 404909 : AtCommit_Memory(void)
1651 : : {
880 1652 : 404909 : TransactionState s = CurrentTransactionState;
1653 : :
1654 : : /*
1655 : : * Return to the memory context that was current before we started the
1656 : : * transaction. (In principle, this could not be any of the contexts we
1657 : : * are about to delete. If it somehow is, assertions in mcxt.c will
1658 : : * complain.)
1659 : : */
1660 : 404909 : MemoryContextSwitchTo(s->priorContext);
1661 : :
1662 : : /*
1663 : : * Release all transaction-local memory. TopTransactionContext survives
1664 : : * but becomes empty; any sub-contexts go away.
1665 : : */
9645 1666 [ - + ]: 404909 : Assert(TopTransactionContext != NULL);
880 1667 : 404909 : MemoryContextReset(TopTransactionContext);
1668 : :
1669 : : /*
1670 : : * Clear these pointers as a pro-forma matter. (Notionally, while
1671 : : * TopTransactionContext still exists, it's currently not associated with
1672 : : * this TransactionState struct.)
1673 : : */
8185 1674 : 404909 : CurTransactionContext = NULL;
880 1675 : 404909 : s->curTransactionContext = NULL;
8185 1676 : 404909 : }
1677 : :
1678 : : /* ----------------------------------------------------------------
1679 : : * CommitSubTransaction stuff
1680 : : * ----------------------------------------------------------------
1681 : : */
1682 : :
1683 : : /*
1684 : : * AtSubCommit_Memory
1685 : : */
1686 : : static void
1687 : 17415 : AtSubCommit_Memory(void)
1688 : : {
1689 : 17415 : TransactionState s = CurrentTransactionState;
1690 : :
1691 [ - + ]: 17415 : Assert(s->parent != NULL);
1692 : :
1693 : : /* Return to parent transaction level's memory context. */
1694 : 17415 : CurTransactionContext = s->parent->curTransactionContext;
1695 : 17415 : MemoryContextSwitchTo(CurTransactionContext);
1696 : :
1697 : : /*
1698 : : * Ordinarily we cannot throw away the child's CurTransactionContext,
1699 : : * since the data it contains will be needed at upper commit. However, if
1700 : : * there isn't actually anything in it, we can throw it away. This avoids
1701 : : * a small memory leak in the common case of "trivial" subxacts.
1702 : : */
8108 1703 [ + + ]: 17415 : if (MemoryContextIsEmpty(s->curTransactionContext))
1704 : : {
1705 : 17388 : MemoryContextDelete(s->curTransactionContext);
1706 : 17388 : s->curTransactionContext = NULL;
1707 : : }
8185 1708 : 17415 : }
1709 : :
1710 : : /*
1711 : : * AtSubCommit_childXids
1712 : : *
1713 : : * Pass my own XID and my child XIDs up to my parent as committed children.
1714 : : */
1715 : : static void
1716 : 15470 : AtSubCommit_childXids(void)
1717 : : {
1718 : 15470 : TransactionState s = CurrentTransactionState;
1719 : : int new_nChildXids;
1720 : :
1721 [ - + ]: 15470 : Assert(s->parent != NULL);
1722 : :
1723 : : /*
1724 : : * The parent childXids array will need to hold my XID and all my
1725 : : * childXids, in addition to the XIDs already there.
1726 : : */
6830 1727 : 15470 : new_nChildXids = s->parent->nChildXids + s->nChildXids + 1;
1728 : :
1729 : : /* Allocate or enlarge the parent array if necessary */
1730 [ + + ]: 15470 : if (s->parent->maxChildXids < new_nChildXids)
1731 : : {
1732 : : int new_maxChildXids;
1733 : : TransactionId *new_childXids;
1734 : :
1735 : : /*
1736 : : * Make it 2x what's needed right now, to avoid having to enlarge it
1737 : : * repeatedly. But we can't go above MaxAllocSize. (The latter limit
1738 : : * is what ensures that we don't need to worry about integer overflow
1739 : : * here or in the calculation of new_nChildXids.)
1740 : : */
1741 : 1726 : new_maxChildXids = Min(new_nChildXids * 2,
1742 : : (int) (MaxAllocSize / sizeof(TransactionId)));
1743 : :
1744 [ - + ]: 1726 : if (new_maxChildXids < new_nChildXids)
6830 tgl@sss.pgh.pa.us 1745 [ # # ]:UBC 0 : ereport(ERROR,
1746 : : (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
1747 : : errmsg("maximum number of committed subtransactions (%d) exceeded",
1748 : : (int) (MaxAllocSize / sizeof(TransactionId)))));
1749 : :
1750 : : /*
1751 : : * We keep the child-XID arrays in TopTransactionContext; this avoids
1752 : : * setting up child-transaction contexts for what might be just a few
1753 : : * bytes of grandchild XIDs.
1754 : : */
6830 tgl@sss.pgh.pa.us 1755 [ + + ]:CBC 1726 : if (s->parent->childXids == NULL)
1756 : : new_childXids =
6379 bruce@momjian.us 1757 : 1649 : MemoryContextAlloc(TopTransactionContext,
1758 : : new_maxChildXids * sizeof(TransactionId));
1759 : : else
103 michael@paquier.xyz 1760 :GNC 77 : new_childXids = repalloc_array(s->parent->childXids, TransactionId, new_maxChildXids);
1761 : :
6379 bruce@momjian.us 1762 :CBC 1726 : s->parent->childXids = new_childXids;
6830 tgl@sss.pgh.pa.us 1763 : 1726 : s->parent->maxChildXids = new_maxChildXids;
1764 : : }
1765 : :
1766 : : /*
1767 : : * Copy all my XIDs to parent's array.
1768 : : *
1769 : : * Note: We rely on the fact that the XID of a child always follows that
1770 : : * of its parent. By copying the XID of this subtransaction before the
1771 : : * XIDs of its children, we ensure that the array stays ordered. Likewise,
1772 : : * all XIDs already in the array belong to subtransactions started and
1773 : : * subcommitted before us, so their XIDs must precede ours.
1774 : : */
2802 tmunro@postgresql.or 1775 : 15470 : s->parent->childXids[s->parent->nChildXids] = XidFromFullTransactionId(s->fullTransactionId);
1776 : :
6830 tgl@sss.pgh.pa.us 1777 [ + + ]: 15470 : if (s->nChildXids > 0)
1778 : 1022 : memcpy(&s->parent->childXids[s->parent->nChildXids + 1],
1779 : 1022 : s->childXids,
1780 : 1022 : s->nChildXids * sizeof(TransactionId));
1781 : :
1782 : 15470 : s->parent->nChildXids = new_nChildXids;
1783 : :
1784 : : /* Release child's array to avoid leakage */
1785 [ + + ]: 15470 : if (s->childXids != NULL)
1786 : 1022 : pfree(s->childXids);
1787 : : /* We must reset these to avoid double-free if fail later in commit */
1788 : 15470 : s->childXids = NULL;
1789 : 15470 : s->nChildXids = 0;
1790 : 15470 : s->maxChildXids = 0;
8185 1791 : 15470 : }
1792 : :
1793 : : /* ----------------------------------------------------------------
1794 : : * AbortTransaction stuff
1795 : : * ----------------------------------------------------------------
1796 : : */
1797 : :
1798 : : /*
1799 : : * RecordTransactionAbort
1800 : : *
1801 : : * Returns latest XID among xact and its children, or InvalidTransactionId
1802 : : * if the xact has no XID. (We compute that here just because it's easier.)
1803 : : */
1804 : : static TransactionId
7024 1805 : 42867 : RecordTransactionAbort(bool isSubXact)
1806 : : {
1807 : 42867 : TransactionId xid = GetCurrentTransactionIdIfAny();
1808 : : TransactionId latestXid;
1809 : : int nrels;
1810 : : RelFileLocator *rels;
1697 andres@anarazel.de 1811 : 42867 : int ndroppedstats = 0;
1812 : 42867 : xl_xact_stats_item *droppedstats = NULL;
1813 : : int nchildren;
1814 : : TransactionId *children;
1815 : : TimestampTz xact_time;
1816 : : bool replorigin;
1817 : :
1818 : : /*
1819 : : * If we haven't been assigned an XID, nobody will care whether we aborted
1820 : : * or not. Hence, we're done in that case. It does not matter if we have
1821 : : * rels to delete (note that this routine is not responsible for actually
1822 : : * deleting 'em). We cannot have any child XIDs, either.
1823 : : */
7024 tgl@sss.pgh.pa.us 1824 [ + + ]: 42867 : if (!TransactionIdIsValid(xid))
1825 : : {
1826 : : /* Reset XactLastRecEnd until the next transaction writes something */
1827 [ + + ]: 32770 : if (!isSubXact)
5270 heikki.linnakangas@i 1828 : 28095 : XactLastRecEnd = 0;
7021 tgl@sss.pgh.pa.us 1829 : 32770 : return InvalidTransactionId;
1830 : : }
1831 : :
1832 : : /*
1833 : : * We have a valid XID, so we should write an ABORT record for it.
1834 : : *
1835 : : * We do not flush XLOG to disk here, since the default assumption after a
1836 : : * crash would be that we aborted, anyway. For the same reason, we don't
1837 : : * need to worry about interlocking against checkpoint start.
1838 : : */
1839 : :
1840 : : /*
1841 : : * Check that we haven't aborted halfway through RecordTransactionCommit.
1842 : : */
7024 1843 [ - + ]: 10097 : if (TransactionIdDidCommit(xid))
7024 tgl@sss.pgh.pa.us 1844 [ # # ]:UBC 0 : elog(PANIC, "cannot abort transaction %u, it was already committed",
1845 : : xid);
1846 : :
1847 : : /*
1848 : : * Are we using the replication origins feature? Or, in other words, are
1849 : : * we replaying remote actions?
1850 : : */
304 msawada@postgresql.o 1851 [ + + ]:CBC 10118 : replorigin = (replorigin_xact_state.origin != InvalidReplOriginId &&
1852 [ + - ]: 21 : replorigin_xact_state.origin != DoNotReplicateId);
1853 : :
1854 : : /* Fetch the data we need for the abort record */
5951 rhaas@postgresql.org 1855 : 10097 : nrels = smgrGetPendingDeletes(false, &rels);
7024 tgl@sss.pgh.pa.us 1856 : 10097 : nchildren = xactGetCommittedChildren(&children);
1697 andres@anarazel.de 1857 : 10097 : ndroppedstats = pgstat_get_transactional_drops(false, &droppedstats);
1858 : :
1859 : : /* XXX do we really need a critical section here? */
7024 tgl@sss.pgh.pa.us 1860 : 10097 : START_CRIT_SECTION();
1861 : :
1862 : : /* Write the ABORT record */
1863 [ + + ]: 10097 : if (isSubXact)
4276 andres@anarazel.de 1864 : 1041 : xact_time = GetCurrentTimestamp();
1865 : : else
1866 : : {
1506 1867 : 9056 : xact_time = GetCurrentTransactionStopTimestamp();
1868 : : }
1869 : :
4276 1870 : 10097 : XactLogAbortRecord(xact_time,
1871 : : nchildren, children,
1872 : : nrels, rels,
1873 : : ndroppedstats, droppedstats,
1874 : : MyXactFlags, InvalidTransactionId,
1875 : : NULL);
1876 : :
1419 akapila@postgresql.o 1877 [ + + ]: 10097 : if (replorigin)
1878 : : /* Move LSNs forward for this replication origin */
304 msawada@postgresql.o 1879 : 21 : replorigin_session_advance(replorigin_xact_state.origin_lsn,
1880 : : XactLastRecEnd);
1881 : :
1882 : : /*
1883 : : * Report the latest async abort LSN, so that the WAL writer knows to
1884 : : * flush this abort. There's nothing to be gained by delaying this, since
1885 : : * WALWriter may as well do this when it can. This is important with
1886 : : * streaming replication because if we don't flush WAL regularly we will
1887 : : * find that large aborts leave us with a long backlog for when commits
1888 : : * occur after the abort, increasing our window of data loss should
1889 : : * problems occur at that point.
1890 : : */
6043 simon@2ndQuadrant.co 1891 [ + + ]: 10097 : if (!isSubXact)
5966 1892 : 9056 : XLogSetAsyncXactLSN(XactLastRecEnd);
1893 : :
1894 : : /*
1895 : : * Mark the transaction aborted in clog. This is not absolutely necessary
1896 : : * but we may as well do it while we are here; also, in the subxact case
1897 : : * it is helpful because XactLockTableWait makes use of it to avoid
1898 : : * waiting for already-aborted subtransactions. It is OK to do it without
1899 : : * having flushed the ABORT record to disk, because in event of a crash
1900 : : * we'd be assumed to have aborted anyway.
1901 : : */
6613 alvherre@alvh.no-ip. 1902 : 10097 : TransactionIdAbortTree(xid, nchildren, children);
1903 : :
7024 tgl@sss.pgh.pa.us 1904 [ - + ]: 10097 : END_CRIT_SECTION();
1905 : :
1906 : : /* Compute latestXid while we have the child XIDs handy */
7021 1907 : 10097 : latestXid = TransactionIdLatest(xid, nchildren, children);
1908 : :
1909 : : /*
1910 : : * If we're aborting a subtransaction, we can immediately remove failed
1911 : : * XIDs from PGPROC's cache of running child XIDs. We do that here for
1912 : : * subxacts, because we already have the child XID array at hand. For
1913 : : * main xacts, the equivalent happens just after this function returns.
1914 : : */
7024 1915 [ + + ]: 10097 : if (isSubXact)
7021 1916 : 1041 : XidCacheRemoveRunningXids(xid, nchildren, children, latestXid);
1917 : :
1918 : : /* Reset XactLastRecEnd until the next transaction writes something */
7024 1919 [ + + ]: 10097 : if (!isSubXact)
5270 heikki.linnakangas@i 1920 : 9056 : XactLastRecEnd = 0;
1921 : :
1922 : : /* And clean up local data */
7834 tgl@sss.pgh.pa.us 1923 [ + + ]: 10097 : if (rels)
1924 : 1551 : pfree(rels);
1697 andres@anarazel.de 1925 [ + + ]: 10097 : if (ndroppedstats)
1926 : 2131 : pfree(droppedstats);
1927 : :
1928 : : /*
1929 : : * Test the window where the transaction is aborted in pg_xact but still
1930 : : * present in ProcArray.
1931 : : */
44 heikki.linnakangas@i 1932 : 10097 : INJECTION_POINT("transaction-abort-after-clog", NULL);
1933 : :
7021 tgl@sss.pgh.pa.us 1934 : 10097 : return latestXid;
1935 : : }
1936 : :
1937 : : /*
1938 : : * AtAbort_Memory
1939 : : */
1940 : : static void
9531 1941 : 57995 : AtAbort_Memory(void)
1942 : : {
1943 : : /*
1944 : : * Switch into TransactionAbortContext, which should have some free space
1945 : : * even if nothing else does. We'll work in this context until we've
1946 : : * finished cleaning up.
1947 : : *
1948 : : * It is barely possible to get here when we've not been able to create
1949 : : * TransactionAbortContext yet; if so use TopMemoryContext.
1950 : : */
7310 1951 [ + - ]: 57995 : if (TransactionAbortContext != NULL)
1952 : 57995 : MemoryContextSwitchTo(TransactionAbortContext);
1953 : : else
9645 tgl@sss.pgh.pa.us 1954 :UBC 0 : MemoryContextSwitchTo(TopMemoryContext);
9649 tgl@sss.pgh.pa.us 1955 :CBC 57995 : }
1956 : :
1957 : : /*
1958 : : * AtSubAbort_Memory
1959 : : */
1960 : : static void
8185 1961 : 5716 : AtSubAbort_Memory(void)
1962 : : {
7310 1963 [ - + ]: 5716 : Assert(TransactionAbortContext != NULL);
1964 : :
1965 : 5716 : MemoryContextSwitchTo(TransactionAbortContext);
8185 1966 : 5716 : }
1967 : :
1968 : :
1969 : : /*
1970 : : * AtAbort_ResourceOwner
1971 : : */
1972 : : static void
8090 1973 : 37166 : AtAbort_ResourceOwner(void)
1974 : : {
1975 : : /*
1976 : : * Make sure we have a valid ResourceOwner, if possible (else it will be
1977 : : * NULL, which is OK)
1978 : : */
1979 : 37166 : CurrentResourceOwner = TopTransactionResourceOwner;
1980 : 37166 : }
1981 : :
1982 : : /*
1983 : : * AtSubAbort_ResourceOwner
1984 : : */
1985 : : static void
1986 : 5716 : AtSubAbort_ResourceOwner(void)
1987 : : {
1988 : 5716 : TransactionState s = CurrentTransactionState;
1989 : :
1990 : : /* Make sure we have a valid ResourceOwner */
1991 : 5716 : CurrentResourceOwner = s->curTransactionOwner;
1992 : 5716 : }
1993 : :
1994 : :
1995 : : /*
1996 : : * AtSubAbort_childXids
1997 : : */
1998 : : static void
8108 1999 : 1041 : AtSubAbort_childXids(void)
2000 : : {
2001 : 1041 : TransactionState s = CurrentTransactionState;
2002 : :
2003 : : /*
2004 : : * We keep the child-XID arrays in TopTransactionContext (see
2005 : : * AtSubCommit_childXids). This means we'd better free the array
2006 : : * explicitly at abort to avoid leakage.
2007 : : */
6830 2008 [ + + ]: 1041 : if (s->childXids != NULL)
2009 : 27 : pfree(s->childXids);
2010 : 1041 : s->childXids = NULL;
2011 : 1041 : s->nChildXids = 0;
2012 : 1041 : s->maxChildXids = 0;
2013 : :
2014 : : /*
2015 : : * We could prune the unreportedXids array here. But we don't bother. That
2016 : : * would potentially reduce number of XLOG_XACT_ASSIGNMENT records but it
2017 : : * would likely introduce more CPU time into the more common paths, so we
2018 : : * choose not to do that.
2019 : : */
8108 2020 : 1041 : }
2021 : :
2022 : : /* ----------------------------------------------------------------
2023 : : * CleanupTransaction stuff
2024 : : * ----------------------------------------------------------------
2025 : : */
2026 : :
2027 : : /*
2028 : : * AtCleanup_Memory
2029 : : */
2030 : : static void
9531 2031 : 37166 : AtCleanup_Memory(void)
2032 : : {
880 2033 : 37166 : TransactionState s = CurrentTransactionState;
2034 : :
2035 : : /* Should be at top level */
2036 [ - + ]: 37166 : Assert(s->parent == NULL);
2037 : :
2038 : : /*
2039 : : * Return to the memory context that was current before we started the
2040 : : * transaction. (In principle, this could not be any of the contexts we
2041 : : * are about to delete. If it somehow is, assertions in mcxt.c will
2042 : : * complain.)
2043 : : */
2044 : 37166 : MemoryContextSwitchTo(s->priorContext);
2045 : :
2046 : : /*
2047 : : * Clear the special abort context for next time.
2048 : : */
7310 2049 [ + - ]: 37166 : if (TransactionAbortContext != NULL)
1109 nathan@postgresql.or 2050 : 37166 : MemoryContextReset(TransactionAbortContext);
2051 : :
2052 : : /*
2053 : : * Release all transaction-local memory, the same as in AtCommit_Memory,
2054 : : * except we must cope with the possibility that we didn't get as far as
2055 : : * creating TopTransactionContext.
2056 : : */
9645 tgl@sss.pgh.pa.us 2057 [ + - ]: 37166 : if (TopTransactionContext != NULL)
880 2058 : 37166 : MemoryContextReset(TopTransactionContext);
2059 : :
2060 : : /*
2061 : : * Clear these pointers as a pro-forma matter. (Notionally, while
2062 : : * TopTransactionContext still exists, it's currently not associated with
2063 : : * this TransactionState struct.)
2064 : : */
8185 2065 : 37166 : CurTransactionContext = NULL;
880 2066 : 37166 : s->curTransactionContext = NULL;
11099 scrappy@hub.org 2067 : 37166 : }
2068 : :
2069 : :
2070 : : /* ----------------------------------------------------------------
2071 : : * CleanupSubTransaction stuff
2072 : : * ----------------------------------------------------------------
2073 : : */
2074 : :
2075 : : /*
2076 : : * AtSubCleanup_Memory
2077 : : */
2078 : : static void
8185 tgl@sss.pgh.pa.us 2079 : 5716 : AtSubCleanup_Memory(void)
2080 : : {
2081 : 5716 : TransactionState s = CurrentTransactionState;
2082 : :
2083 [ - + ]: 5716 : Assert(s->parent != NULL);
2084 : :
2085 : : /*
2086 : : * Return to the memory context that was current before we started the
2087 : : * subtransaction. (In principle, this could not be any of the contexts
2088 : : * we are about to delete. If it somehow is, assertions in mcxt.c will
2089 : : * complain.)
2090 : : */
880 2091 : 5716 : MemoryContextSwitchTo(s->priorContext);
2092 : :
2093 : : /* Update CurTransactionContext (might not be same as priorContext) */
8185 2094 : 5716 : CurTransactionContext = s->parent->curTransactionContext;
2095 : :
2096 : : /*
2097 : : * Clear the special abort context for next time.
2098 : : */
7310 2099 [ + - ]: 5716 : if (TransactionAbortContext != NULL)
1109 nathan@postgresql.or 2100 : 5716 : MemoryContextReset(TransactionAbortContext);
2101 : :
2102 : : /*
2103 : : * Delete the subxact local memory contexts. Its CurTransactionContext can
2104 : : * go too (note this also kills CurTransactionContexts from any children
2105 : : * of the subxact).
2106 : : */
8108 tgl@sss.pgh.pa.us 2107 [ + - ]: 5716 : if (s->curTransactionContext)
2108 : 5716 : MemoryContextDelete(s->curTransactionContext);
2109 : 5716 : s->curTransactionContext = NULL;
8185 2110 : 5716 : }
2111 : :
2112 : : /* ----------------------------------------------------------------
2113 : : * interface routines
2114 : : * ----------------------------------------------------------------
2115 : : */
2116 : :
2117 : : /*
2118 : : * StartTransaction
2119 : : */
2120 : : static void
9531 2121 : 442075 : StartTransaction(void)
2122 : : {
2123 : : TransactionState s;
2124 : : VirtualTransactionId vxid;
2125 : :
2126 : : /*
2127 : : * Let's just make sure the state stack is empty
2128 : : */
8108 2129 : 442075 : s = &TopTransactionStateData;
2130 : 442075 : CurrentTransactionState = s;
2131 : :
2802 tmunro@postgresql.or 2132 [ - + ]: 442075 : Assert(!FullTransactionIdIsValid(XactTopFullTransactionId));
2133 : :
2134 : : /* check the current transaction state */
2936 michael@paquier.xyz 2135 [ - + ]: 442075 : Assert(s->state == TRANS_DEFAULT);
2136 : :
2137 : : /*
2138 : : * Set the current transaction state information appropriately during
2139 : : * start processing. Note that once the transaction status is switched
2140 : : * this process cannot fail until the user ID and the security context
2141 : : * flags are fetched below.
2142 : : */
10674 bruce@momjian.us 2143 : 442075 : s->state = TRANS_START;
2802 tmunro@postgresql.or 2144 : 442075 : s->fullTransactionId = InvalidFullTransactionId; /* until assigned */
2145 : :
2146 : : /* Determine if statements are logged in this transaction */
2796 alvherre@alvh.no-ip. 2147 [ - + ]: 442075 : xact_is_sampled = log_xact_sample_rate != 0 &&
2796 alvherre@alvh.no-ip. 2148 [ # # ]:UBC 0 : (log_xact_sample_rate == 1 ||
1826 tgl@sss.pgh.pa.us 2149 [ # # ]: 0 : pg_prng_double(&pg_global_prng_state) <= log_xact_sample_rate);
2150 : :
2151 : : /*
2152 : : * initialize current transaction state fields
2153 : : *
2154 : : * note: prevXactReadOnly is not used at the outermost level
2155 : : */
2936 michael@paquier.xyz 2156 :CBC 442075 : s->nestingLevel = 1;
2157 : 442075 : s->gucNestLevel = 1;
2158 : 442075 : s->childXids = NULL;
2159 : 442075 : s->nChildXids = 0;
2160 : 442075 : s->maxChildXids = 0;
2161 : :
2162 : : /*
2163 : : * Once the current user ID and the security context flags are fetched,
2164 : : * both will be properly reset even if transaction startup fails.
2165 : : */
2166 : 442075 : GetUserIdAndSecContext(&s->prevUser, &s->prevSecContext);
2167 : :
2168 : : /* SecurityRestrictionContext should never be set outside a transaction */
2169 [ - + ]: 442075 : Assert(s->prevSecContext == 0);
2170 : :
2171 : : /*
2172 : : * Make sure we've reset xact state variables
2173 : : *
2174 : : * If recovery is still in progress, mark this transaction as read-only.
2175 : : * We have lower level defences in XLogInsert and elsewhere to stop us
2176 : : * from modifying data during recovery, but this gives the normal
2177 : : * indication to the user that the transaction is read-only.
2178 : : */
6188 simon@2ndQuadrant.co 2179 [ + + ]: 442075 : if (RecoveryInProgress())
2180 : : {
2181 : 2636 : s->startedInRecovery = true;
2182 : 2636 : XactReadOnly = true;
2183 : : }
2184 : : else
2185 : : {
2186 : 439439 : s->startedInRecovery = false;
2187 : 439439 : XactReadOnly = DefaultXactReadOnly;
2188 : : }
5773 heikki.linnakangas@i 2189 : 442075 : XactDeferrable = DefaultXactDeferrable;
8444 tgl@sss.pgh.pa.us 2190 : 442075 : XactIsoLevel = DefaultXactIsoLevel;
7059 2191 : 442075 : forceSyncCommit = false;
3538 simon@2ndQuadrant.co 2192 : 442075 : MyXactFlags = 0;
2193 : :
2194 : : /*
2195 : : * reinitialize within-transaction counters
2196 : : */
8108 tgl@sss.pgh.pa.us 2197 : 442075 : s->subTransactionId = TopSubTransactionId;
2198 : 442075 : currentSubTransactionId = TopSubTransactionId;
2199 : 442075 : currentCommandId = FirstCommandId;
6938 2200 : 442075 : currentCommandIdUsed = false;
2201 : :
2202 : : /*
2203 : : * initialize reported xid accounting
2204 : : */
6188 simon@2ndQuadrant.co 2205 : 442075 : nUnreportedXids = 0;
4736 rhaas@postgresql.org 2206 : 442075 : s->didLogXid = false;
2207 : :
2208 : : /*
2209 : : * must initialize resource-management stuff first
2210 : : */
8169 tgl@sss.pgh.pa.us 2211 : 442075 : AtStart_Memory();
2212 : 442075 : AtStart_ResourceOwner();
2213 : :
2214 : : /*
2215 : : * Assign a new LocalTransactionId, and combine it with the proc number to
2216 : : * form a virtual transaction id.
2217 : : */
1000 heikki.linnakangas@i 2218 : 442075 : vxid.procNumber = MyProcNumber;
7024 tgl@sss.pgh.pa.us 2219 : 442075 : vxid.localTransactionId = GetNextLocalTransactionId();
2220 : :
2221 : : /*
2222 : : * Lock the virtual transaction id before we announce it in the proc array
2223 : : */
2224 : 442075 : VirtualXactLockTableInsert(vxid);
2225 : :
2226 : : /*
2227 : : * Advertise it in the proc array. We assume assignment of
2228 : : * localTransactionId is atomic, and the proc number should be set
2229 : : * already.
2230 : : */
1000 heikki.linnakangas@i 2231 [ - + ]: 442075 : Assert(MyProc->vxid.procNumber == vxid.procNumber);
2232 : 442075 : MyProc->vxid.lxid = vxid.localTransactionId;
2233 : :
2234 : : TRACE_POSTGRESQL_TRANSACTION_START(vxid.localTransactionId);
2235 : :
2236 : : /*
2237 : : * set transaction_timestamp() (a/k/a now()). Normally, we want this to
2238 : : * be the same as the first command's statement_timestamp(), so don't do a
2239 : : * fresh GetCurrentTimestamp() call (which'd be expensive anyway). But
2240 : : * for transactions started inside procedures (i.e., nonatomic SPI
2241 : : * contexts), we do need to advance the timestamp. Also, in a parallel
2242 : : * worker, the timestamp should already have been provided by a call to
2243 : : * SetParallelStartTimestamps().
2244 : : */
2975 tgl@sss.pgh.pa.us 2245 [ + + ]: 442075 : if (!IsParallelWorker())
2246 : : {
2973 2247 [ + + ]: 435927 : if (!SPI_inside_nonatomic_context())
2248 : 433587 : xactStartTimestamp = stmtStartTimestamp;
2249 : : else
2250 : 2340 : xactStartTimestamp = GetCurrentTimestamp();
2251 : : }
2252 : : else
2975 2253 [ - + ]: 6148 : Assert(xactStartTimestamp != 0);
7018 2254 : 442075 : pgstat_report_xact_timestamp(xactStartTimestamp);
2255 : : /* Mark xactStopTimestamp as unset. */
2973 2256 : 442075 : xactStopTimestamp = 0;
2257 : :
2258 : : /*
2259 : : * initialize other subsystems for new transaction
2260 : : */
7026 2261 : 442075 : AtStart_GUC();
10674 bruce@momjian.us 2262 : 442075 : AtStart_Cache();
8114 tgl@sss.pgh.pa.us 2263 : 442075 : AfterTriggerBeginXact();
2264 : :
2265 : : /*
2266 : : * done with start processing, set current transaction state to "in
2267 : : * progress"
2268 : : */
10674 bruce@momjian.us 2269 : 442075 : s->state = TRANS_INPROGRESS;
2270 : :
2271 : : /* Schedule transaction timeout */
1017 akorotkov@postgresql 2272 [ + + ]: 442075 : if (TransactionTimeout > 0)
2273 : 1 : enable_timeout_after(TRANSACTION_TIMEOUT, TransactionTimeout);
2274 : :
8185 tgl@sss.pgh.pa.us 2275 : 442075 : ShowTransactionState("StartTransaction");
11099 scrappy@hub.org 2276 : 442075 : }
2277 : :
2278 : :
2279 : : /*
2280 : : * CommitTransaction
2281 : : *
2282 : : * NB: if you change this routine, better look at PrepareTransaction too!
2283 : : */
2284 : : static void
9531 tgl@sss.pgh.pa.us 2285 : 404916 : CommitTransaction(void)
2286 : : {
10674 bruce@momjian.us 2287 : 404916 : TransactionState s = CurrentTransactionState;
2288 : : TransactionId latestXid;
2289 : : bool is_parallel_worker;
2290 : :
4230 rhaas@postgresql.org 2291 : 404916 : is_parallel_worker = (s->blockState == TBLOCK_PARALLEL_INPROGRESS);
2292 : :
2293 : : /* Enforce parallel mode restrictions during parallel worker commit. */
4061 2294 [ + + ]: 404916 : if (is_parallel_worker)
2295 : 2034 : EnterParallelMode();
2296 : :
8185 tgl@sss.pgh.pa.us 2297 : 404916 : ShowTransactionState("CommitTransaction");
2298 : :
2299 : : /*
2300 : : * check the current transaction state
2301 : : */
10674 bruce@momjian.us 2302 [ - + ]: 404916 : if (s->state != TRANS_INPROGRESS)
8158 tgl@sss.pgh.pa.us 2303 [ # # ]:UBC 0 : elog(WARNING, "CommitTransaction while in %s state",
2304 : : TransStateAsString(s->state));
8185 tgl@sss.pgh.pa.us 2305 [ + - ]:CBC 404916 : Assert(s->parent == NULL);
2306 : :
2307 : : /*
2308 : : * Do pre-commit processing that involves calling user-defined code, such
2309 : : * as triggers. SECURITY_RESTRICTED_OPERATION contexts must not queue an
2310 : : * action that would run here, because that would bypass the sandbox.
2311 : : * Since closing cursors could queue trigger actions, triggers could open
2312 : : * cursors, etc, we have to keep looping until there's nothing left to do.
2313 : : */
2314 : : for (;;)
2315 : : {
2316 : : /*
2317 : : * Fire all currently pending deferred triggers.
2318 : : */
7901 2319 : 412618 : AfterTriggerFireDeferred();
2320 : :
2321 : : /*
2322 : : * Close open portals (converting holdable ones into static portals).
2323 : : * If there weren't any, we are done ... otherwise loop back to check
2324 : : * if they queued deferred triggers. Lather, rinse, repeat.
2325 : : */
5753 2326 [ + + ]: 412469 : if (!PreCommit_Portals(false))
7901 2327 : 404767 : break;
2328 : : }
2329 : :
2330 : : /*
2331 : : * The remaining actions cannot call any user-defined code, so it's safe
2332 : : * to start shutting down within-transaction services. But note that most
2333 : : * of this stuff could still throw an error, which would switch us into
2334 : : * the transaction-abort path.
2335 : : */
2336 : :
2210 noah@leadboat.com 2337 [ + + ]: 404767 : CallXactCallbacks(is_parallel_worker ? XACT_EVENT_PARALLEL_PRE_COMMIT
2338 : : : XACT_EVENT_PRE_COMMIT);
2339 : :
2340 : : /*
2341 : : * If this xact has started any unfinished parallel operation, clean up
2342 : : * its workers, warning about leaked resources. (But we don't actually
2343 : : * reset parallelModeLevel till entering TRANS_COMMIT, a bit below. This
2344 : : * keeps parallel mode restrictions active as long as possible in a
2345 : : * parallel worker.)
2346 : : */
975 tgl@sss.pgh.pa.us 2347 : 404766 : AtEOXact_Parallel(true);
2348 [ + + ]: 404766 : if (is_parallel_worker)
2349 : : {
2350 [ - + ]: 2034 : if (s->parallelModeLevel != 1)
975 tgl@sss.pgh.pa.us 2351 [ # # ]:UBC 0 : elog(WARNING, "parallelModeLevel is %d not 1 at end of parallel worker transaction",
2352 : : s->parallelModeLevel);
2353 : : }
2354 : : else
2355 : : {
975 tgl@sss.pgh.pa.us 2356 [ - + ]:CBC 402732 : if (s->parallelModeLevel != 0)
975 tgl@sss.pgh.pa.us 2357 [ # # ]:UBC 0 : elog(WARNING, "parallelModeLevel is %d not 0 at end of transaction",
2358 : : s->parallelModeLevel);
2359 : : }
2360 : :
2361 : : /* Shut down the deferred-trigger manager */
5753 tgl@sss.pgh.pa.us 2362 :CBC 404766 : AfterTriggerEndXact(true);
2363 : :
2364 : : /*
2365 : : * Let ON COMMIT management do its thing (must happen after closing
2366 : : * cursors, to avoid dangling-reference problems)
2367 : : */
8065 2368 : 404766 : PreCommit_on_commit_actions();
2369 : :
2370 : : /*
2371 : : * Synchronize files that are created and not WAL-logged during this
2372 : : * transaction. This must happen before AtEOXact_RelationMap(), so that we
2373 : : * don't see committed-but-broken files after a crash.
2374 : : */
2429 noah@leadboat.com 2375 : 404762 : smgrDoPendingSyncs(true, is_parallel_worker);
2376 : :
2377 : : /* close large objects before lower-level cleanup */
8158 tgl@sss.pgh.pa.us 2378 : 404762 : AtEOXact_LargeObject(true);
2379 : :
2380 : : /*
2381 : : * Insert notifications sent by NOTIFY commands into the queue. This
2382 : : * should be late in the pre-commit sequence to minimize time spent
2383 : : * holding the notify-insertion lock. However, this could result in
2384 : : * creating a snapshot, so we must do it before serializable cleanup.
2385 : : */
2561 2386 : 404762 : PreCommit_Notify();
2387 : :
2388 : : /*
2389 : : * Mark serializable transaction as complete for predicate locking
2390 : : * purposes. This should be done as late as we can put it and still allow
2391 : : * errors to be raised for failure patterns found at commit. This is not
2392 : : * appropriate in a parallel worker however, because we aren't committing
2393 : : * the leader's transaction and its serializable state will live on.
2394 : : */
2815 tmunro@postgresql.or 2395 [ + + ]: 404762 : if (!is_parallel_worker)
2396 : 402728 : PreCommit_CheckForSerializationFailure();
2397 : :
2398 : : /* Prevent cancel/die interrupt while cleaning up */
8065 tgl@sss.pgh.pa.us 2399 : 404602 : HOLD_INTERRUPTS();
2400 : :
2401 : : /* Commit updates to the relation map --- do this as late as possible */
3032 pg@bowt.ie 2402 : 404602 : AtEOXact_RelationMap(true, is_parallel_worker);
2403 : :
2404 : : /*
2405 : : * set the current transaction state information appropriately during
2406 : : * commit processing
2407 : : */
8065 tgl@sss.pgh.pa.us 2408 : 404602 : s->state = TRANS_COMMIT;
4061 rhaas@postgresql.org 2409 : 404602 : s->parallelModeLevel = 0;
975 tgl@sss.pgh.pa.us 2410 : 404602 : s->parallelChildXact = false; /* should be false already */
2411 : :
2412 : : /* Disable transaction timeout */
1016 akorotkov@postgresql 2413 [ + + ]: 404602 : if (TransactionTimeout > 0)
2414 : 1 : disable_timeout(TRANSACTION_TIMEOUT, false);
2415 : :
4230 rhaas@postgresql.org 2416 [ + + ]: 404602 : if (!is_parallel_worker)
2417 : : {
2418 : : /*
2419 : : * We need to mark our XIDs as committed in pg_xact. This is where we
2420 : : * durably commit.
2421 : : */
2422 : 402568 : latestXid = RecordTransactionCommit();
2423 : : }
2424 : : else
2425 : : {
2426 : : /*
2427 : : * We must not mark our XID committed; the parallel leader is
2428 : : * responsible for that.
2429 : : */
2430 : 2034 : latestXid = InvalidTransactionId;
2431 : :
2432 : : /*
2433 : : * Make sure the leader will know about any WAL we wrote before it
2434 : : * commits.
2435 : : */
2436 : 2034 : ParallelWorkerReportLastRecEnd(XactLastRecEnd);
2437 : : }
2438 : :
2439 : : TRACE_POSTGRESQL_TRANSACTION_COMMIT(MyProc->vxid.lxid);
2440 : :
2441 : : /*
2442 : : * Let others know about no transaction in progress by me. Note that this
2443 : : * must be done _before_ releasing locks we hold and _after_
2444 : : * RecordTransactionCommit.
2445 : : */
7021 tgl@sss.pgh.pa.us 2446 : 404602 : ProcArrayEndTransaction(MyProc, latestXid);
2447 : :
2448 : : /*
2449 : : * This is all post-commit cleanup. Note that if an error is raised here,
2450 : : * it's too late to abort the transaction. This should be just
2451 : : * noncritical resource releasing.
2452 : : *
2453 : : * The ordering of operations is not entirely random. The idea is:
2454 : : * release resources visible to other backends (eg, files, buffer pins);
2455 : : * then release locks; then release backend-local resources. We want to
2456 : : * release locks at the point where any backend waiting for us will see
2457 : : * our transaction as being fully cleaned up.
2458 : : *
2459 : : * Resources that can be associated with individual queries are handled by
2460 : : * the ResourceOwner mechanism. The other calls here are for backend-wide
2461 : : * state.
2462 : : */
2463 : :
4230 rhaas@postgresql.org 2464 : 404602 : CallXactCallbacks(is_parallel_worker ? XACT_EVENT_PARALLEL_COMMIT
2465 : : : XACT_EVENT_COMMIT);
2466 : :
1109 heikki.linnakangas@i 2467 : 404602 : CurrentResourceOwner = NULL;
8169 tgl@sss.pgh.pa.us 2468 : 404602 : ResourceOwnerRelease(TopTransactionResourceOwner,
2469 : : RESOURCE_RELEASE_BEFORE_LOCKS,
2470 : : true, true);
2471 : :
621 andres@anarazel.de 2472 : 404602 : AtEOXact_Aio(true);
2473 : :
2474 : : /* Check we've released all buffer pins */
8078 tgl@sss.pgh.pa.us 2475 : 404602 : AtEOXact_Buffers(true);
2476 : :
2477 : : /* Clean up the relation cache */
7782 2478 : 404602 : AtEOXact_RelationCache(true);
2479 : :
2480 : : /* Clean up the type cache */
765 akorotkov@postgresql 2481 : 404602 : AtEOXact_TypeCache();
2482 : :
2483 : : /*
2484 : : * Make catalog changes visible to all backends. This has to happen after
2485 : : * relcache references are dropped (see comments for
2486 : : * AtEOXact_RelationCache), but before locks are released (if anyone is
2487 : : * waiting for lock on a relation we've modified, we want them to know
2488 : : * about the catalog change before they start using the relation).
2489 : : */
8169 tgl@sss.pgh.pa.us 2490 : 404602 : AtEOXact_Inval(true);
2491 : :
7884 2492 : 404602 : AtEOXact_MultiXact();
2493 : :
8169 2494 : 404602 : ResourceOwnerRelease(TopTransactionResourceOwner,
2495 : : RESOURCE_RELEASE_LOCKS,
2496 : : true, true);
2497 : 404602 : ResourceOwnerRelease(TopTransactionResourceOwner,
2498 : : RESOURCE_RELEASE_AFTER_LOCKS,
2499 : : true, true);
2500 : :
2501 : : /*
2502 : : * Likewise, dropping of files deleted during the transaction is best done
2503 : : * after releasing relcache and buffer pins. (This is not strictly
2504 : : * necessary during commit, since such pins should have been released
2505 : : * already, but this ordering is definitely critical during abort.) Since
2506 : : * this may take many seconds, also delay until after releasing locks.
2507 : : * Other backends will observe the attendant catalog changes and not
2508 : : * attempt to access affected files.
2509 : : */
5280 rhaas@postgresql.org 2510 : 404602 : smgrDoPendingDeletes(true);
2511 : :
2512 : : /*
2513 : : * Send out notification signals to other backends (and do other
2514 : : * post-commit NOTIFY cleanup). This must not happen until after our
2515 : : * transaction is fully done from the viewpoint of other backends.
2516 : : */
6129 tgl@sss.pgh.pa.us 2517 : 404602 : AtCommit_Notify();
2518 : :
2519 : : /*
2520 : : * Everything after this should be purely internal-to-this-backend
2521 : : * cleanup.
2522 : : */
7026 2523 : 404602 : AtEOXact_GUC(true, 1);
8397 mail@joeconway.com 2524 : 404602 : AtEOXact_SPI(true);
2972 tmunro@postgresql.or 2525 : 404602 : AtEOXact_Enum();
8108 tgl@sss.pgh.pa.us 2526 : 404602 : AtEOXact_on_commit_actions(true);
4230 rhaas@postgresql.org 2527 : 404602 : AtEOXact_Namespace(true, is_parallel_worker);
5155 tgl@sss.pgh.pa.us 2528 : 404602 : AtEOXact_SMgr();
3136 2529 : 404602 : AtEOXact_Files(true);
7232 2530 : 404602 : AtEOXact_ComboCid();
7156 2531 : 404602 : AtEOXact_HashTables(true);
152 amitlan@postgresql.o 2532 : 404602 : AtEOXact_RI(true);
2789 akapila@postgresql.o 2533 : 404602 : AtEOXact_PgStat(true, is_parallel_worker);
3523 simon@2ndQuadrant.co 2534 : 404602 : AtEOXact_Snapshot(true, false);
3498 peter_e@gmx.net 2535 : 404602 : AtEOXact_ApplyLauncher(true);
1422 tgl@sss.pgh.pa.us 2536 : 404602 : AtEOXact_LogicalRepWorkers(true);
340 msawada@postgresql.o 2537 : 404602 : AtEOXact_LogicalCtl();
7018 tgl@sss.pgh.pa.us 2538 : 404602 : pgstat_report_xact_timestamp(0);
2539 : :
8169 2540 : 404602 : ResourceOwnerDelete(TopTransactionResourceOwner);
2541 : 404602 : s->curTransactionOwner = NULL;
2542 : 404602 : CurTransactionResourceOwner = NULL;
2543 : 404602 : TopTransactionResourceOwner = NULL;
2544 : :
8803 2545 : 404602 : AtCommit_Memory();
2546 : :
2802 tmunro@postgresql.or 2547 : 404602 : s->fullTransactionId = InvalidFullTransactionId;
8108 tgl@sss.pgh.pa.us 2548 : 404602 : s->subTransactionId = InvalidSubTransactionId;
8185 2549 : 404602 : s->nestingLevel = 0;
7026 2550 : 404602 : s->gucNestLevel = 0;
6830 2551 : 404602 : s->childXids = NULL;
2552 : 404602 : s->nChildXids = 0;
2553 : 404602 : s->maxChildXids = 0;
2554 : :
2802 tmunro@postgresql.or 2555 : 404602 : XactTopFullTransactionId = InvalidFullTransactionId;
4230 rhaas@postgresql.org 2556 : 404602 : nParallelCurrentXids = 0;
2557 : :
2558 : : /*
2559 : : * done with commit processing, set current transaction state back to
2560 : : * default
2561 : : */
10674 bruce@momjian.us 2562 : 404602 : s->state = TRANS_DEFAULT;
2563 : :
9444 tgl@sss.pgh.pa.us 2564 [ - + ]: 404602 : RESUME_INTERRUPTS();
11099 scrappy@hub.org 2565 : 404602 : }
2566 : :
2567 : :
2568 : : /*
2569 : : * PrepareTransaction
2570 : : *
2571 : : * NB: if you change this routine, better look at CommitTransaction too!
2572 : : */
2573 : : static void
7834 tgl@sss.pgh.pa.us 2574 : 372 : PrepareTransaction(void)
2575 : : {
7714 bruce@momjian.us 2576 : 372 : TransactionState s = CurrentTransactionState;
509 michael@paquier.xyz 2577 : 372 : FullTransactionId fxid = GetCurrentFullTransactionId();
2578 : : GlobalTransaction gxact;
2579 : : TimestampTz prepared_at;
2580 : :
4230 rhaas@postgresql.org 2581 [ - + ]: 372 : Assert(!IsInParallelMode());
2582 : :
7834 tgl@sss.pgh.pa.us 2583 : 372 : ShowTransactionState("PrepareTransaction");
2584 : :
2585 : : /*
2586 : : * check the current transaction state
2587 : : */
2588 [ - + ]: 372 : if (s->state != TRANS_INPROGRESS)
7834 tgl@sss.pgh.pa.us 2589 [ # # ]:UBC 0 : elog(WARNING, "PrepareTransaction while in %s state",
2590 : : TransStateAsString(s->state));
7834 tgl@sss.pgh.pa.us 2591 [ + - ]:CBC 372 : Assert(s->parent == NULL);
2592 : :
2593 : : /*
2594 : : * Do pre-commit processing that involves calling user-defined code, such
2595 : : * as triggers. Since closing cursors could queue trigger actions,
2596 : : * triggers could open cursors, etc, we have to keep looping until there's
2597 : : * nothing left to do.
2598 : : */
2599 : : for (;;)
2600 : : {
2601 : : /*
2602 : : * Fire all currently pending deferred triggers.
2603 : : */
2604 : 374 : AfterTriggerFireDeferred();
2605 : :
2606 : : /*
2607 : : * Close open portals (converting holdable ones into static portals).
2608 : : * If there weren't any, we are done ... otherwise loop back to check
2609 : : * if they queued deferred triggers. Lather, rinse, repeat.
2610 : : */
5753 2611 [ + + ]: 374 : if (!PreCommit_Portals(true))
7834 2612 : 372 : break;
2613 : : }
2614 : :
5035 2615 : 372 : CallXactCallbacks(XACT_EVENT_PRE_PREPARE);
2616 : :
2617 : : /*
2618 : : * The remaining actions cannot call any user-defined code, so it's safe
2619 : : * to start shutting down within-transaction services. But note that most
2620 : : * of this stuff could still throw an error, which would switch us into
2621 : : * the transaction-abort path.
2622 : : */
2623 : :
2624 : : /* Shut down the deferred-trigger manager */
5753 2625 : 371 : AfterTriggerEndXact(true);
2626 : :
2627 : : /*
2628 : : * Let ON COMMIT management do its thing (must happen after closing
2629 : : * cursors, to avoid dangling-reference problems)
2630 : : */
7834 2631 : 371 : PreCommit_on_commit_actions();
2632 : :
2633 : : /*
2634 : : * Synchronize files that are created and not WAL-logged during this
2635 : : * transaction. This must happen before EndPrepare(), so that we don't see
2636 : : * committed-but-broken files after a crash and COMMIT PREPARED.
2637 : : */
2429 noah@leadboat.com 2638 : 371 : smgrDoPendingSyncs(true, false);
2639 : :
2640 : : /* close large objects before lower-level cleanup */
7834 tgl@sss.pgh.pa.us 2641 : 371 : AtEOXact_LargeObject(true);
2642 : :
2643 : : /* NOTIFY requires no work at this point */
2644 : :
2645 : : /*
2646 : : * Mark serializable transaction as complete for predicate locking
2647 : : * purposes. This should be done as late as we can put it and still allow
2648 : : * errors to be raised for failure patterns found at commit.
2649 : : */
5773 heikki.linnakangas@i 2650 : 371 : PreCommit_CheckForSerializationFailure();
2651 : :
2652 : : /*
2653 : : * Don't allow PREPARE TRANSACTION if we've accessed a temporary table in
2654 : : * this transaction. Having the prepared xact hold locks on another
2655 : : * backend's temp table seems a bad idea --- for instance it would prevent
2656 : : * the backend from exiting. There are other problems too, such as how to
2657 : : * clean up the source backend's local buffers and ON COMMIT state if the
2658 : : * prepared xact includes a DROP of a temp table.
2659 : : *
2660 : : * Other objects types, like functions, operators or extensions, share the
2661 : : * same restriction as they should not be created, locked or dropped as
2662 : : * this can mess up with this session or even a follow-up session trying
2663 : : * to use the same temporary namespace.
2664 : : *
2665 : : * We must check this after executing any ON COMMIT actions, because they
2666 : : * might still access a temp relation.
2667 : : *
2668 : : * XXX In principle this could be relaxed to allow some useful special
2669 : : * cases, such as a temp table created and dropped all within the
2670 : : * transaction. That seems to require much more bookkeeping though.
2671 : : */
2871 michael@paquier.xyz 2672 [ + + ]: 371 : if ((MyXactFlags & XACT_FLAGS_ACCESSEDTEMPNAMESPACE))
2673 [ + - ]: 44 : ereport(ERROR,
2674 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2675 : : errmsg("cannot PREPARE a transaction that has operated on temporary objects")));
2676 : :
2677 : : /*
2678 : : * Likewise, don't allow PREPARE after pg_export_snapshot. This could be
2679 : : * supported if we added cleanup logic to twophase.c, but for now it
2680 : : * doesn't seem worth the trouble.
2681 : : */
5516 tgl@sss.pgh.pa.us 2682 [ - + ]: 327 : if (XactHasExportedSnapshots())
5516 tgl@sss.pgh.pa.us 2683 [ # # ]:UBC 0 : ereport(ERROR,
2684 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2685 : : errmsg("cannot PREPARE a transaction that has exported snapshots")));
2686 : :
2687 : : /* Prevent cancel/die interrupt while cleaning up */
7834 tgl@sss.pgh.pa.us 2688 :CBC 327 : HOLD_INTERRUPTS();
2689 : :
2690 : : /*
2691 : : * set the current transaction state information appropriately during
2692 : : * prepare processing
2693 : : */
2694 : 327 : s->state = TRANS_PREPARE;
2695 : :
2696 : : /* Disable transaction timeout */
1016 akorotkov@postgresql 2697 [ - + ]: 327 : if (TransactionTimeout > 0)
1016 akorotkov@postgresql 2698 :UBC 0 : disable_timeout(TRANSACTION_TIMEOUT, false);
2699 : :
7822 tgl@sss.pgh.pa.us 2700 :CBC 327 : prepared_at = GetCurrentTimestamp();
2701 : :
2702 : : /*
2703 : : * Reserve the GID for this transaction. This could fail if the requested
2704 : : * GID is invalid or already in use.
2705 : : */
509 michael@paquier.xyz 2706 : 327 : gxact = MarkAsPreparing(fxid, prepareGID, prepared_at,
2707 : : GetUserId(), MyDatabaseId);
7834 tgl@sss.pgh.pa.us 2708 : 309 : prepareGID = NULL;
2709 : :
2710 : : /*
2711 : : * Collect data for the 2PC state file. Note that in general, no actual
2712 : : * state change should happen in the called modules during this step,
2713 : : * since it's still possible to fail before commit, and in that case we
2714 : : * want transaction abort to be able to clean up. (In particular, the
2715 : : * AtPrepare routines may error out if they find cases they cannot
2716 : : * handle.) State cleanup should happen in the PostPrepare routines
2717 : : * below. However, some modules can go ahead and clear state here because
2718 : : * they wouldn't do anything with it during abort anyway.
2719 : : *
2720 : : * Note: because the 2PC state file records will be replayed in the same
2721 : : * order they are made, the order of these calls has to match the order in
2722 : : * which we want things to happen during COMMIT PREPARED or ROLLBACK
2723 : : * PREPARED; in particular, pay attention to whether things should happen
2724 : : * before or after releasing the transaction's locks.
2725 : : */
2726 : 309 : StartPrepare(gxact);
2727 : :
2728 : 309 : AtPrepare_Notify();
2729 : 309 : AtPrepare_Locks();
5773 heikki.linnakangas@i 2730 : 307 : AtPrepare_PredicateLocks();
7125 tgl@sss.pgh.pa.us 2731 : 307 : AtPrepare_PgStat();
6214 heikki.linnakangas@i 2732 : 307 : AtPrepare_MultiXact();
6138 tgl@sss.pgh.pa.us 2733 : 307 : AtPrepare_RelationMap();
2734 : :
2735 : : /*
2736 : : * Here is where we really truly prepare.
2737 : : *
2738 : : * We have to record transaction prepares even if we didn't make any
2739 : : * updates, because the transaction manager might get confused if we lose
2740 : : * a global transaction.
2741 : : */
7834 2742 : 307 : EndPrepare(gxact);
2743 : :
2744 : : /*
2745 : : * Now we clean up backend-internal state and release internal resources.
2746 : : */
2747 : :
2748 : : /* Reset XactLastRecEnd until the next transaction writes something */
5270 heikki.linnakangas@i 2749 : 307 : XactLastRecEnd = 0;
2750 : :
2751 : : /*
2752 : : * Transfer our locks to a dummy PGPROC. This has to be done before
2753 : : * ProcArrayClearTransaction(). Otherwise, a GetLockConflicts() would
2754 : : * conclude "xact already committed or aborted" for our locks.
2755 : : */
509 michael@paquier.xyz 2756 : 307 : PostPrepare_Locks(fxid);
2757 : :
2758 : : /*
2759 : : * Let others know about no transaction in progress by me. This has to be
2760 : : * done *after* the prepared transaction has been marked valid, else
2761 : : * someone may think it is unlocked and recyclable.
2762 : : */
7021 tgl@sss.pgh.pa.us 2763 : 307 : ProcArrayClearTransaction(MyProc);
2764 : :
2765 : : /*
2766 : : * In normal commit-processing, this is all non-critical post-transaction
2767 : : * cleanup. When the transaction is prepared, however, it's important
2768 : : * that the locks and other per-backend resources are transferred to the
2769 : : * prepared transaction's PGPROC entry. Note that if an error is raised
2770 : : * here, it's too late to abort the transaction. XXX: This probably should
2771 : : * be in a critical section, to force a PANIC if any of this fails, but
2772 : : * that cure could be worse than the disease.
2773 : : */
2774 : :
7834 2775 : 307 : CallXactCallbacks(XACT_EVENT_PREPARE);
2776 : :
2777 : 307 : ResourceOwnerRelease(TopTransactionResourceOwner,
2778 : : RESOURCE_RELEASE_BEFORE_LOCKS,
2779 : : true, true);
2780 : :
621 andres@anarazel.de 2781 : 307 : AtEOXact_Aio(true);
2782 : :
2783 : : /* Check we've released all buffer pins */
7834 tgl@sss.pgh.pa.us 2784 : 307 : AtEOXact_Buffers(true);
2785 : :
2786 : : /* Clean up the relation cache */
7782 2787 : 307 : AtEOXact_RelationCache(true);
2788 : :
2789 : : /* Clean up the type cache */
765 akorotkov@postgresql 2790 : 307 : AtEOXact_TypeCache();
2791 : :
2792 : : /* notify doesn't need a postprepare call */
2793 : :
7125 tgl@sss.pgh.pa.us 2794 : 307 : PostPrepare_PgStat();
2795 : :
7834 2796 : 307 : PostPrepare_Inval();
2797 : :
2798 : 307 : PostPrepare_smgr();
2799 : :
509 michael@paquier.xyz 2800 : 307 : PostPrepare_MultiXact(fxid);
2801 : :
2802 : 307 : PostPrepare_PredicateLocks(fxid);
2803 : :
7834 tgl@sss.pgh.pa.us 2804 : 307 : ResourceOwnerRelease(TopTransactionResourceOwner,
2805 : : RESOURCE_RELEASE_LOCKS,
2806 : : true, true);
2807 : 307 : ResourceOwnerRelease(TopTransactionResourceOwner,
2808 : : RESOURCE_RELEASE_AFTER_LOCKS,
2809 : : true, true);
2810 : :
2811 : : /*
2812 : : * Allow another backend to finish the transaction. After
2813 : : * PostPrepare_Twophase(), the transaction is completely detached from our
2814 : : * backend. The rest is just non-critical cleanup of backend-local state.
2815 : : */
4580 heikki.linnakangas@i 2816 : 307 : PostPrepare_Twophase();
2817 : :
2818 : : /* PREPARE acts the same as COMMIT as far as GUC is concerned */
7026 tgl@sss.pgh.pa.us 2819 : 307 : AtEOXact_GUC(true, 1);
7834 2820 : 307 : AtEOXact_SPI(true);
2972 tmunro@postgresql.or 2821 : 307 : AtEOXact_Enum();
7834 tgl@sss.pgh.pa.us 2822 : 307 : AtEOXact_on_commit_actions(true);
4230 rhaas@postgresql.org 2823 : 307 : AtEOXact_Namespace(true, false);
5155 tgl@sss.pgh.pa.us 2824 : 307 : AtEOXact_SMgr();
3136 2825 : 307 : AtEOXact_Files(true);
7232 2826 : 307 : AtEOXact_ComboCid();
7156 2827 : 307 : AtEOXact_HashTables(true);
152 amitlan@postgresql.o 2828 : 307 : AtEOXact_RI(true);
2829 : : /* don't call AtEOXact_PgStat here; we fixed pgstat state above */
3523 simon@2ndQuadrant.co 2830 : 307 : AtEOXact_Snapshot(true, true);
2831 : : /* we treat PREPARE as ROLLBACK so far as waking workers goes */
1422 tgl@sss.pgh.pa.us 2832 : 307 : AtEOXact_ApplyLauncher(false);
2833 : 307 : AtEOXact_LogicalRepWorkers(false);
340 msawada@postgresql.o 2834 : 307 : AtEOXact_LogicalCtl();
4601 tgl@sss.pgh.pa.us 2835 : 307 : pgstat_report_xact_timestamp(0);
2836 : :
7834 2837 : 307 : CurrentResourceOwner = NULL;
2838 : 307 : ResourceOwnerDelete(TopTransactionResourceOwner);
2839 : 307 : s->curTransactionOwner = NULL;
2840 : 307 : CurTransactionResourceOwner = NULL;
2841 : 307 : TopTransactionResourceOwner = NULL;
2842 : :
2843 : 307 : AtCommit_Memory();
2844 : :
2802 tmunro@postgresql.or 2845 : 307 : s->fullTransactionId = InvalidFullTransactionId;
7834 tgl@sss.pgh.pa.us 2846 : 307 : s->subTransactionId = InvalidSubTransactionId;
2847 : 307 : s->nestingLevel = 0;
7026 2848 : 307 : s->gucNestLevel = 0;
6830 2849 : 307 : s->childXids = NULL;
2850 : 307 : s->nChildXids = 0;
2851 : 307 : s->maxChildXids = 0;
2852 : :
2802 tmunro@postgresql.or 2853 : 307 : XactTopFullTransactionId = InvalidFullTransactionId;
4230 rhaas@postgresql.org 2854 : 307 : nParallelCurrentXids = 0;
2855 : :
2856 : : /*
2857 : : * done with 1st phase commit processing, set current transaction state
2858 : : * back to default
2859 : : */
7834 tgl@sss.pgh.pa.us 2860 : 307 : s->state = TRANS_DEFAULT;
2861 : :
2862 [ - + ]: 307 : RESUME_INTERRUPTS();
2863 : 307 : }
2864 : :
2865 : :
2866 : : /*
2867 : : * AbortTransaction
2868 : : */
2869 : : static void
9531 2870 : 37166 : AbortTransaction(void)
2871 : : {
10674 bruce@momjian.us 2872 : 37166 : TransactionState s = CurrentTransactionState;
2873 : : TransactionId latestXid;
2874 : : bool is_parallel_worker;
2875 : :
2876 : : /* Prevent cancel/die interrupt while cleaning up */
9444 tgl@sss.pgh.pa.us 2877 : 37166 : HOLD_INTERRUPTS();
2878 : :
2879 : : /* Disable transaction timeout */
1016 akorotkov@postgresql 2880 [ + + ]: 37166 : if (TransactionTimeout > 0)
2881 : 1 : disable_timeout(TRANSACTION_TIMEOUT, false);
2882 : :
2883 : : /* Make sure we have a valid memory context and resource owner */
7310 tgl@sss.pgh.pa.us 2884 : 37166 : AtAbort_Memory();
2885 : 37166 : AtAbort_ResourceOwner();
2886 : :
2887 : : /*
2888 : : * Release any LW locks we might be holding as quickly as possible.
2889 : : * (Regular locks, however, must be held till we finish aborting.)
2890 : : * Releasing LW locks is critical since we might try to grab them again
2891 : : * while cleaning up!
2892 : : */
9191 2893 : 37166 : LWLockReleaseAll();
2894 : :
2895 : : /*
2896 : : * Cleanup waiting for LSN if any.
2897 : : */
388 akorotkov@postgresql 2898 : 37166 : WaitLSNCleanup();
2899 : :
2900 : : /* Clear wait information and command progress indicator */
3915 rhaas@postgresql.org 2901 : 37166 : pgstat_report_wait_end();
2902 : 37166 : pgstat_progress_end_command();
2903 : :
621 andres@anarazel.de 2904 : 37166 : pgaio_error_cleanup();
2905 : :
2906 : : /* Clean up buffer content locks, too */
9476 tgl@sss.pgh.pa.us 2907 : 37166 : UnlockBuffers();
2908 : :
2909 : : /* Reset WAL record construction state */
4391 heikki.linnakangas@i 2910 : 37166 : XLogResetInsertion();
2911 : :
2912 : : /* Cancel condition variable sleep */
3658 rhaas@postgresql.org 2913 : 37166 : ConditionVariableCancelSleep();
2914 : :
2915 : : /*
2916 : : * Also clean up any open wait for lock, since the lock manager will choke
2917 : : * if we try to wait for another lock before doing this.
2918 : : */
5337 2919 : 37166 : LockErrorCleanup();
2920 : :
2921 : : /*
2922 : : * If any timeout events are still active, make sure the timeout interrupt
2923 : : * is scheduled. This covers possible loss of a timeout interrupt due to
2924 : : * longjmp'ing out of the SIGINT handler (see notes in handle_sig_alarm).
2925 : : * We delay this till after LockErrorCleanup so that we don't uselessly
2926 : : * reschedule lock or deadlock check timeouts.
2927 : : */
4747 tgl@sss.pgh.pa.us 2928 : 37166 : reschedule_timeouts();
2929 : :
2930 : : /*
2931 : : * Re-enable signals, in case we got here by longjmp'ing out of a signal
2932 : : * handler. We do this fairly early in the sequence so that the timeout
2933 : : * infrastructure will be functional if needed while aborting.
2934 : : */
1394 tmunro@postgresql.or 2935 : 37166 : sigprocmask(SIG_SETMASK, &UnBlockSig, NULL);
2936 : :
2937 : : /*
2938 : : * check the current transaction state
2939 : : */
4230 rhaas@postgresql.org 2940 : 37166 : is_parallel_worker = (s->blockState == TBLOCK_PARALLEL_INPROGRESS);
7834 tgl@sss.pgh.pa.us 2941 [ + + - + ]: 37166 : if (s->state != TRANS_INPROGRESS && s->state != TRANS_PREPARE)
8158 tgl@sss.pgh.pa.us 2942 [ # # ]:UBC 0 : elog(WARNING, "AbortTransaction while in %s state",
2943 : : TransStateAsString(s->state));
8185 tgl@sss.pgh.pa.us 2944 [ - + ]:CBC 37166 : Assert(s->parent == NULL);
2945 : :
2946 : : /*
2947 : : * set the current transaction state information appropriately during the
2948 : : * abort processing
2949 : : */
10674 bruce@momjian.us 2950 : 37166 : s->state = TRANS_ABORT;
2951 : :
2952 : : /*
2953 : : * Reset user ID which might have been changed transiently. We need this
2954 : : * to clean up in case control escaped out of a SECURITY DEFINER function
2955 : : * or other local change of CurrentUserId; therefore, the prior value of
2956 : : * SecurityRestrictionContext also needs to be restored.
2957 : : *
2958 : : * (Note: it is not necessary to restore session authorization or role
2959 : : * settings here because those can only be changed via GUC, and GUC will
2960 : : * take care of rolling them back if need be.)
2961 : : */
6198 tgl@sss.pgh.pa.us 2962 : 37166 : SetUserIdAndSecContext(s->prevUser, s->prevSecContext);
2963 : :
2964 : : /* Forget about any active REINDEX. */
2412 2965 : 37166 : ResetReindexState(s->nestingLevel);
2966 : :
2967 : : /* Reset logical streaming state. */
2303 akapila@postgresql.o 2968 : 37166 : ResetLogicalStreamingState();
2969 : :
2970 : : /* Reset snapshot export state. */
1867 michael@paquier.xyz 2971 : 37166 : SnapBuildResetExportedSnapshotState();
2972 : :
2973 : : /*
2974 : : * If this xact has started any unfinished parallel operation, clean up
2975 : : * its workers and exit parallel mode. Don't warn about leaked resources.
2976 : : */
975 tgl@sss.pgh.pa.us 2977 : 37166 : AtEOXact_Parallel(false);
2978 : 37166 : s->parallelModeLevel = 0;
2979 : 37166 : s->parallelChildXact = false; /* should be false already */
2980 : :
2981 : : /*
2982 : : * do abort processing
2983 : : */
6119 bruce@momjian.us 2984 : 37166 : AfterTriggerEndXact(false); /* 'false' means it's abort */
8611 tgl@sss.pgh.pa.us 2985 : 37166 : AtAbort_Portals();
2429 noah@leadboat.com 2986 : 37166 : smgrDoPendingSyncs(false, is_parallel_worker);
6138 tgl@sss.pgh.pa.us 2987 : 37166 : AtEOXact_LargeObject(false);
10280 2988 : 37166 : AtAbort_Notify();
3032 pg@bowt.ie 2989 : 37166 : AtEOXact_RelationMap(false, is_parallel_worker);
4580 heikki.linnakangas@i 2990 : 37166 : AtAbort_Twophase();
2991 : :
2992 : : /*
2993 : : * Advertise the fact that we aborted in pg_xact (assuming that we got as
2994 : : * far as assigning an XID to advertise). But if we're inside a parallel
2995 : : * worker, skip this; the user backend must be the one to write the abort
2996 : : * record.
2997 : : */
4230 rhaas@postgresql.org 2998 [ + + ]: 37166 : if (!is_parallel_worker)
2999 : 37151 : latestXid = RecordTransactionAbort(false);
3000 : : else
3001 : : {
3002 : 15 : latestXid = InvalidTransactionId;
3003 : :
3004 : : /*
3005 : : * Since the parallel leader won't get our value of XactLastRecEnd in
3006 : : * this case, we nudge WAL-writer ourselves in this case. See related
3007 : : * comments in RecordTransactionAbort for why this matters.
3008 : : */
3009 : 15 : XLogSetAsyncXactLSN(XactLastRecEnd);
3010 : : }
3011 : :
3012 : : TRACE_POSTGRESQL_TRANSACTION_ABORT(MyProc->vxid.lxid);
3013 : :
3014 : : /*
3015 : : * Let others know about no transaction in progress by me. Note that this
3016 : : * must be done _before_ releasing locks we hold and _after_
3017 : : * RecordTransactionAbort.
3018 : : */
7021 tgl@sss.pgh.pa.us 3019 : 37166 : ProcArrayEndTransaction(MyProc, latestXid);
3020 : :
3021 : : /*
3022 : : * Post-abort cleanup. See notes in CommitTransaction() concerning
3023 : : * ordering. We can skip all of it if the transaction failed before
3024 : : * creating a resource owner.
3025 : : */
6152 3026 [ + - ]: 37166 : if (TopTransactionResourceOwner != NULL)
3027 : : {
4230 rhaas@postgresql.org 3028 [ + + ]: 37166 : if (is_parallel_worker)
3029 : 15 : CallXactCallbacks(XACT_EVENT_PARALLEL_ABORT);
3030 : : else
3031 : 37151 : CallXactCallbacks(XACT_EVENT_ABORT);
3032 : :
6152 tgl@sss.pgh.pa.us 3033 : 37166 : ResourceOwnerRelease(TopTransactionResourceOwner,
3034 : : RESOURCE_RELEASE_BEFORE_LOCKS,
3035 : : false, true);
621 andres@anarazel.de 3036 : 37166 : AtEOXact_Aio(false);
6152 tgl@sss.pgh.pa.us 3037 : 37166 : AtEOXact_Buffers(false);
3038 : 37166 : AtEOXact_RelationCache(false);
765 akorotkov@postgresql 3039 : 37166 : AtEOXact_TypeCache();
6152 tgl@sss.pgh.pa.us 3040 : 37166 : AtEOXact_Inval(false);
3041 : 37166 : AtEOXact_MultiXact();
3042 : 37166 : ResourceOwnerRelease(TopTransactionResourceOwner,
3043 : : RESOURCE_RELEASE_LOCKS,
3044 : : false, true);
3045 : 37166 : ResourceOwnerRelease(TopTransactionResourceOwner,
3046 : : RESOURCE_RELEASE_AFTER_LOCKS,
3047 : : false, true);
5280 rhaas@postgresql.org 3048 : 37166 : smgrDoPendingDeletes(false);
3049 : :
6152 tgl@sss.pgh.pa.us 3050 : 37166 : AtEOXact_GUC(false, 1);
3051 : 37166 : AtEOXact_SPI(false);
2972 tmunro@postgresql.or 3052 : 37166 : AtEOXact_Enum();
6152 tgl@sss.pgh.pa.us 3053 : 37166 : AtEOXact_on_commit_actions(false);
4230 rhaas@postgresql.org 3054 : 37166 : AtEOXact_Namespace(false, is_parallel_worker);
5155 tgl@sss.pgh.pa.us 3055 : 37166 : AtEOXact_SMgr();
3136 3056 : 37166 : AtEOXact_Files(false);
6152 3057 : 37166 : AtEOXact_ComboCid();
3058 : 37166 : AtEOXact_HashTables(false);
152 amitlan@postgresql.o 3059 : 37166 : AtEOXact_RI(false);
2789 akapila@postgresql.o 3060 : 37166 : AtEOXact_PgStat(false, is_parallel_worker);
3498 peter_e@gmx.net 3061 : 37166 : AtEOXact_ApplyLauncher(false);
1422 tgl@sss.pgh.pa.us 3062 : 37166 : AtEOXact_LogicalRepWorkers(false);
6152 3063 : 37166 : pgstat_report_xact_timestamp(0);
3064 : : }
3065 : :
3066 : : /*
3067 : : * State remains TRANS_ABORT until CleanupTransaction().
3068 : : */
9444 3069 [ - + ]: 37166 : RESUME_INTERRUPTS();
9649 3070 : 37166 : }
3071 : :
3072 : : /*
3073 : : * CleanupTransaction
3074 : : */
3075 : : static void
9531 3076 : 37166 : CleanupTransaction(void)
3077 : : {
9649 3078 : 37166 : TransactionState s = CurrentTransactionState;
3079 : :
3080 : : /*
3081 : : * State should still be TRANS_ABORT from AbortTransaction().
3082 : : */
3083 [ - + ]: 37166 : if (s->state != TRANS_ABORT)
8155 tgl@sss.pgh.pa.us 3084 [ # # ]:UBC 0 : elog(FATAL, "CleanupTransaction: unexpected state %s",
3085 : : TransStateAsString(s->state));
3086 : :
3087 : : /*
3088 : : * do abort cleanup processing
3089 : : */
8611 tgl@sss.pgh.pa.us 3090 :CBC 37166 : AtCleanup_Portals(); /* now safe to release portal memory */
3447 3091 : 37166 : AtEOXact_Snapshot(false, true); /* and release the transaction's snapshots */
3092 : :
8126 bruce@momjian.us 3093 : 37166 : CurrentResourceOwner = NULL; /* and resource owner */
8108 tgl@sss.pgh.pa.us 3094 [ + - ]: 37166 : if (TopTransactionResourceOwner)
3095 : 37166 : ResourceOwnerDelete(TopTransactionResourceOwner);
8169 3096 : 37166 : s->curTransactionOwner = NULL;
3097 : 37166 : CurTransactionResourceOwner = NULL;
3098 : 37166 : TopTransactionResourceOwner = NULL;
3099 : :
8611 3100 : 37166 : AtCleanup_Memory(); /* and transaction memory */
3101 : :
2802 tmunro@postgresql.or 3102 : 37166 : s->fullTransactionId = InvalidFullTransactionId;
8108 tgl@sss.pgh.pa.us 3103 : 37166 : s->subTransactionId = InvalidSubTransactionId;
8185 3104 : 37166 : s->nestingLevel = 0;
7026 3105 : 37166 : s->gucNestLevel = 0;
6830 3106 : 37166 : s->childXids = NULL;
3107 : 37166 : s->nChildXids = 0;
3108 : 37166 : s->maxChildXids = 0;
4230 rhaas@postgresql.org 3109 : 37166 : s->parallelModeLevel = 0;
975 tgl@sss.pgh.pa.us 3110 : 37166 : s->parallelChildXact = false;
3111 : :
2802 tmunro@postgresql.or 3112 : 37166 : XactTopFullTransactionId = InvalidFullTransactionId;
4230 rhaas@postgresql.org 3113 : 37166 : nParallelCurrentXids = 0;
3114 : :
3115 : : /*
3116 : : * Apply any pending XLogLogicalInfo update. This must be done here
3117 : : * rather than in AbortTransaction(), because a failed transaction block
3118 : : * keeps its XID until ROLLBACK, so a barrier absorbed meanwhile is
3119 : : * deferred. Unlike CommitTransaction() and PrepareTransaction(), we are
3120 : : * not necessarily holding interrupts here, so do this after resetting the
3121 : : * top-level XID; otherwise a barrier absorbed in between would be left
3122 : : * pending into the next transaction.
3123 : : */
53 msawada@postgresql.o 3124 : 37166 : AtEOXact_LogicalCtl();
3125 : :
3126 : : /*
3127 : : * done with abort processing, set current transaction state back to
3128 : : * default
3129 : : */
10674 bruce@momjian.us 3130 : 37166 : s->state = TRANS_DEFAULT;
3131 : 37166 : }
3132 : :
3133 : : /*
3134 : : * StartTransactionCommand
3135 : : */
3136 : : void
8599 tgl@sss.pgh.pa.us 3137 : 556341 : StartTransactionCommand(void)
3138 : : {
10674 bruce@momjian.us 3139 : 556341 : TransactionState s = CurrentTransactionState;
3140 : :
3141 [ + + + - : 556341 : switch (s->blockState)
- ]
3142 : : {
3143 : : /*
3144 : : * if we aren't in a transaction block, we just do our usual start
3145 : : * transaction.
3146 : : */
10673 3147 : 439970 : case TBLOCK_DEFAULT:
3148 : 439970 : StartTransaction();
8272 3149 : 439970 : s->blockState = TBLOCK_STARTED;
3150 : 439970 : break;
3151 : :
3152 : : /*
3153 : : * We are somewhere in a transaction block or subtransaction and
3154 : : * about to start a new command. For now we do nothing, but
3155 : : * someday we may do command-local resource initialization. (Note
3156 : : * that any needed CommandCounterIncrement was done by the
3157 : : * previous CommitTransactionCommand.)
3158 : : */
10673 3159 : 115067 : case TBLOCK_INPROGRESS:
3160 : : case TBLOCK_IMPLICIT_INPROGRESS:
3161 : : case TBLOCK_SUBINPROGRESS:
3162 : 115067 : break;
3163 : :
3164 : : /*
3165 : : * Here we are in a failed transaction block (one of the commands
3166 : : * caused an abort) so we do nothing but remain in the abort
3167 : : * state. Eventually we will get a ROLLBACK command which will
3168 : : * get us out of this state. (It is up to other code to ensure
3169 : : * that no commands other than ROLLBACK will be processed in these
3170 : : * states.)
3171 : : */
3172 : 1304 : case TBLOCK_ABORT:
3173 : : case TBLOCK_SUBABORT:
3174 : 1304 : break;
3175 : :
3176 : : /* These cases are invalid. */
8185 tgl@sss.pgh.pa.us 3177 :UBC 0 : case TBLOCK_STARTED:
3178 : : case TBLOCK_BEGIN:
3179 : : case TBLOCK_PARALLEL_INPROGRESS:
3180 : : case TBLOCK_SUBBEGIN:
3181 : : case TBLOCK_END:
3182 : : case TBLOCK_SUBRELEASE:
3183 : : case TBLOCK_SUBCOMMIT:
3184 : : case TBLOCK_ABORT_END:
3185 : : case TBLOCK_SUBABORT_END:
3186 : : case TBLOCK_ABORT_PENDING:
3187 : : case TBLOCK_SUBABORT_PENDING:
3188 : : case TBLOCK_SUBRESTART:
3189 : : case TBLOCK_SUBABORT_RESTART:
3190 : : case TBLOCK_PREPARE:
8108 3191 [ # # ]: 0 : elog(ERROR, "StartTransactionCommand: unexpected state %s",
3192 : : BlockStateAsString(s->blockState));
3193 : : break;
3194 : : }
3195 : :
3196 : : /*
3197 : : * We must switch to CurTransactionContext before returning. This is
3198 : : * already done if we called StartTransaction, otherwise not.
3199 : : */
8185 tgl@sss.pgh.pa.us 3200 [ - + ]:CBC 556341 : Assert(CurTransactionContext != NULL);
3201 : 556341 : MemoryContextSwitchTo(CurTransactionContext);
10674 bruce@momjian.us 3202 : 556341 : }
3203 : :
3204 : :
3205 : : /*
3206 : : * Simple system for saving and restoring transaction characteristics
3207 : : * (isolation level, read only, deferrable). We need this for transaction
3208 : : * chaining, so that we can set the characteristics of the new transaction to
3209 : : * be the same as the previous one. (We need something like this because the
3210 : : * GUC system resets the characteristics at transaction end, so for example
3211 : : * just skipping the reset in StartTransaction() won't work.)
3212 : : */
3213 : : void
1734 tgl@sss.pgh.pa.us 3214 : 558387 : SaveTransactionCharacteristics(SavedTransactionCharacteristics *s)
3215 : : {
3216 : 558387 : s->save_XactIsoLevel = XactIsoLevel;
3217 : 558387 : s->save_XactReadOnly = XactReadOnly;
3218 : 558387 : s->save_XactDeferrable = XactDeferrable;
2806 peter@eisentraut.org 3219 : 558387 : }
3220 : :
3221 : : void
1734 tgl@sss.pgh.pa.us 3222 : 1146 : RestoreTransactionCharacteristics(const SavedTransactionCharacteristics *s)
3223 : : {
3224 : 1146 : XactIsoLevel = s->save_XactIsoLevel;
3225 : 1146 : XactReadOnly = s->save_XactReadOnly;
3226 : 1146 : XactDeferrable = s->save_XactDeferrable;
2806 peter@eisentraut.org 3227 : 1146 : }
3228 : :
3229 : : /*
3230 : : * CommitTransactionCommand -- a wrapper function handling the
3231 : : * loop over subtransactions to avoid a potentially dangerous recursion
3232 : : * in CommitTransactionCommandInternal().
3233 : : */
3234 : : void
8599 tgl@sss.pgh.pa.us 3235 : 521548 : CommitTransactionCommand(void)
3236 : : {
3237 : : /*
3238 : : * Repeatedly call CommitTransactionCommandInternal() until all the work
3239 : : * is done.
3240 : : */
954 akorotkov@postgresql 3241 [ + + ]: 521887 : while (!CommitTransactionCommandInternal())
3242 : : {
3243 : : }
995 3244 : 521169 : }
3245 : :
3246 : : /*
3247 : : * CommitTransactionCommandInternal - a function doing an iteration of work
3248 : : * regarding handling the commit transaction command. In the case of
3249 : : * subtransactions more than one iterations could be required. Returns
3250 : : * true when no more iterations required, false otherwise.
3251 : : */
3252 : : static bool
3253 : 521887 : CommitTransactionCommandInternal(void)
3254 : : {
10674 bruce@momjian.us 3255 : 521887 : TransactionState s = CurrentTransactionState;
3256 : : SavedTransactionCharacteristics savetc;
3257 : :
3258 : : /* Must save in case we need to restore below */
1734 tgl@sss.pgh.pa.us 3259 : 521887 : SaveTransactionCharacteristics(&savetc);
3260 : :
10674 bruce@momjian.us 3261 [ - + + + : 521887 : switch (s->blockState)
+ + + + +
+ + + + +
+ + - ]
3262 : : {
3263 : : /*
3264 : : * These shouldn't happen. TBLOCK_DEFAULT means the previous
3265 : : * StartTransactionCommand didn't set the STARTED state
3266 : : * appropriately, while TBLOCK_PARALLEL_INPROGRESS should be ended
3267 : : * by EndParallelWorkerTransaction(), not this function.
3268 : : */
8272 bruce@momjian.us 3269 :UBC 0 : case TBLOCK_DEFAULT:
3270 : : case TBLOCK_PARALLEL_INPROGRESS:
8159 tgl@sss.pgh.pa.us 3271 [ # # ]: 0 : elog(FATAL, "CommitTransactionCommand: unexpected state %s",
3272 : : BlockStateAsString(s->blockState));
3273 : : break;
3274 : :
3275 : : /*
3276 : : * If we aren't in a transaction block, just do our usual
3277 : : * transaction commit, and return to the idle state.
3278 : : */
8272 bruce@momjian.us 3279 :CBC 393621 : case TBLOCK_STARTED:
8599 tgl@sss.pgh.pa.us 3280 : 393621 : CommitTransaction();
8272 bruce@momjian.us 3281 : 393578 : s->blockState = TBLOCK_DEFAULT;
10673 3282 : 393578 : break;
3283 : :
3284 : : /*
3285 : : * We are completing a "BEGIN TRANSACTION" command, so we change
3286 : : * to the "transaction block in progress" state and return. (We
3287 : : * assume the BEGIN did nothing to the database, so we need no
3288 : : * CommandCounterIncrement.)
3289 : : */
3290 : 12757 : case TBLOCK_BEGIN:
3291 : 12757 : s->blockState = TBLOCK_INPROGRESS;
3292 : 12757 : break;
3293 : :
3294 : : /*
3295 : : * This is the case when we have finished executing a command
3296 : : * someplace within a transaction block. We increment the command
3297 : : * counter and return.
3298 : : */
3299 : 79318 : case TBLOCK_INPROGRESS:
3300 : : case TBLOCK_IMPLICIT_INPROGRESS:
3301 : : case TBLOCK_SUBINPROGRESS:
3302 : 79318 : CommandCounterIncrement();
3303 : 79318 : break;
3304 : :
3305 : : /*
3306 : : * We are completing a "COMMIT" command. Do it and return to the
3307 : : * idle state.
3308 : : */
3309 : 8850 : case TBLOCK_END:
3310 : 8850 : CommitTransaction();
9649 tgl@sss.pgh.pa.us 3311 : 8596 : s->blockState = TBLOCK_DEFAULT;
2806 peter@eisentraut.org 3312 [ + + ]: 8596 : if (s->chain)
3313 : : {
3314 : 8 : StartTransaction();
3315 : 8 : s->blockState = TBLOCK_INPROGRESS;
3316 : 8 : s->chain = false;
1734 tgl@sss.pgh.pa.us 3317 : 8 : RestoreTransactionCharacteristics(&savetc);
3318 : : }
10673 bruce@momjian.us 3319 : 8596 : break;
3320 : :
3321 : : /*
3322 : : * Here we are in the middle of a transaction block but one of the
3323 : : * commands caused an abort so we do nothing but remain in the
3324 : : * abort state. Eventually we will get a ROLLBACK command.
3325 : : */
3326 : 13 : case TBLOCK_ABORT:
3327 : : case TBLOCK_SUBABORT:
3328 : 13 : break;
3329 : :
3330 : : /*
3331 : : * Here we were in an aborted transaction block and we just got
3332 : : * the ROLLBACK command from the user, so clean up the
3333 : : * already-aborted transaction and return to the idle state.
3334 : : */
8108 tgl@sss.pgh.pa.us 3335 : 959 : case TBLOCK_ABORT_END:
9649 3336 : 959 : CleanupTransaction();
10673 bruce@momjian.us 3337 : 959 : s->blockState = TBLOCK_DEFAULT;
2806 peter@eisentraut.org 3338 [ + + ]: 959 : if (s->chain)
3339 : : {
3340 : 16 : StartTransaction();
3341 : 16 : s->blockState = TBLOCK_INPROGRESS;
3342 : 16 : s->chain = false;
1734 tgl@sss.pgh.pa.us 3343 : 16 : RestoreTransactionCharacteristics(&savetc);
3344 : : }
10673 bruce@momjian.us 3345 : 959 : break;
3346 : :
3347 : : /*
3348 : : * Here we were in a perfectly good transaction block but the user
3349 : : * told us to ROLLBACK anyway. We have to abort the transaction
3350 : : * and then clean up.
3351 : : */
8108 tgl@sss.pgh.pa.us 3352 : 1930 : case TBLOCK_ABORT_PENDING:
3353 : 1930 : AbortTransaction();
3354 : 1930 : CleanupTransaction();
3355 : 1930 : s->blockState = TBLOCK_DEFAULT;
2806 peter@eisentraut.org 3356 [ + + ]: 1930 : if (s->chain)
3357 : : {
3358 : 16 : StartTransaction();
3359 : 16 : s->blockState = TBLOCK_INPROGRESS;
3360 : 16 : s->chain = false;
1734 tgl@sss.pgh.pa.us 3361 : 16 : RestoreTransactionCharacteristics(&savetc);
3362 : : }
8159 3363 : 1930 : break;
3364 : :
3365 : : /*
3366 : : * We are completing a "PREPARE TRANSACTION" command. Do it and
3367 : : * return to the idle state.
3368 : : */
7834 3369 : 271 : case TBLOCK_PREPARE:
3370 : 271 : PrepareTransaction();
3371 : 208 : s->blockState = TBLOCK_DEFAULT;
3372 : 208 : break;
3373 : :
3374 : : /*
3375 : : * The user issued a SAVEPOINT inside a transaction block. Start a
3376 : : * subtransaction. (DefineSavepoint already did PushTransaction,
3377 : : * so as to have someplace to put the SUBBEGIN state.)
3378 : : */
8185 3379 : 22567 : case TBLOCK_SUBBEGIN:
3380 : 22567 : StartSubTransaction();
3381 : 22567 : s->blockState = TBLOCK_SUBINPROGRESS;
3382 : 22567 : break;
3383 : :
3384 : : /*
3385 : : * The user issued a RELEASE command, so we end the current
3386 : : * subtransaction and return to the parent transaction. The parent
3387 : : * might be ended too, so repeat till we find an INPROGRESS
3388 : : * transaction or subtransaction.
3389 : : */
5611 simon@2ndQuadrant.co 3390 : 273 : case TBLOCK_SUBRELEASE:
3391 : : do
3392 : : {
5561 3393 : 273 : CommitSubTransaction();
8126 bruce@momjian.us 3394 : 273 : s = CurrentTransactionState; /* changed by pop */
5611 simon@2ndQuadrant.co 3395 [ + + ]: 273 : } while (s->blockState == TBLOCK_SUBRELEASE);
3396 : :
3397 [ + + - + ]: 186 : Assert(s->blockState == TBLOCK_INPROGRESS ||
3398 : : s->blockState == TBLOCK_SUBINPROGRESS);
3399 : 186 : break;
3400 : :
3401 : : /*
3402 : : * The user issued a COMMIT, so we end the current subtransaction
3403 : : * hierarchy and perform final commit. We do this by rolling up
3404 : : * any subtransactions into their parent, which leads to O(N^2)
3405 : : * operations with respect to resource owners - this isn't that
3406 : : * bad until we approach a thousands of savepoints but is
3407 : : * necessary for correctness should after triggers create new
3408 : : * resource owners.
3409 : : */
3410 : 605 : case TBLOCK_SUBCOMMIT:
3411 : : do
3412 : : {
5561 3413 : 605 : CommitSubTransaction();
5611 3414 : 605 : s = CurrentTransactionState; /* changed by pop */
3415 [ + + ]: 605 : } while (s->blockState == TBLOCK_SUBCOMMIT);
3416 : : /* If we had a COMMIT command, finish off the main xact too */
8114 tgl@sss.pgh.pa.us 3417 [ + + ]: 512 : if (s->blockState == TBLOCK_END)
3418 : : {
3419 [ - + ]: 411 : Assert(s->parent == NULL);
3420 : :
3421 : : /*
3422 : : * Save the characteristics again, now that the
3423 : : * subtransactions are committed. A subtransaction may have
3424 : : * switched to read-only, which should not be inherited by the
3425 : : * next AND CHAIN, if any.
3426 : : */
15 michael@paquier.xyz 3427 : 411 : SaveTransactionCharacteristics(&savetc);
8114 tgl@sss.pgh.pa.us 3428 : 411 : CommitTransaction();
3429 : 394 : s->blockState = TBLOCK_DEFAULT;
2108 fujii@postgresql.org 3430 [ + + ]: 394 : if (s->chain)
3431 : : {
3432 : 16 : StartTransaction();
3433 : 16 : s->blockState = TBLOCK_INPROGRESS;
3434 : 16 : s->chain = false;
1734 tgl@sss.pgh.pa.us 3435 : 16 : RestoreTransactionCharacteristics(&savetc);
3436 : : }
3437 : : }
7834 3438 [ + - ]: 101 : else if (s->blockState == TBLOCK_PREPARE)
3439 : : {
3440 [ - + ]: 101 : Assert(s->parent == NULL);
3441 : 101 : PrepareTransaction();
3442 : 99 : s->blockState = TBLOCK_DEFAULT;
3443 : : }
3444 : : else
5611 simon@2ndQuadrant.co 3445 [ # # ]:UBC 0 : elog(ERROR, "CommitTransactionCommand: unexpected state %s",
3446 : : BlockStateAsString(s->blockState));
8185 tgl@sss.pgh.pa.us 3447 :CBC 493 : break;
3448 : :
3449 : : /*
3450 : : * The current already-failed subtransaction is ending due to a
3451 : : * ROLLBACK or ROLLBACK TO command, so pop it and recursively
3452 : : * examine the parent (which could be in any of several states).
3453 : : * As we need to examine the parent, return false to request the
3454 : : * caller to do the next iteration.
3455 : : */
954 akorotkov@postgresql 3456 : 55 : case TBLOCK_SUBABORT_END:
3457 : 55 : CleanupSubTransaction();
3458 : 55 : return false;
3459 : :
3460 : : /*
3461 : : * As above, but it's not dead yet, so abort first.
3462 : : */
3463 : 284 : case TBLOCK_SUBABORT_PENDING:
3464 : 284 : AbortSubTransaction();
3465 : 284 : CleanupSubTransaction();
3466 : 284 : return false;
3467 : :
3468 : : /*
3469 : : * The current subtransaction is the target of a ROLLBACK TO
3470 : : * command. Abort and pop it, then start a new subtransaction
3471 : : * with the same name.
3472 : : */
8108 tgl@sss.pgh.pa.us 3473 : 353 : case TBLOCK_SUBRESTART:
3474 : : {
3475 : : char *name;
3476 : : int savepointLevel;
3477 : :
3478 : : /* save name and keep Cleanup from freeing it */
3479 : 353 : name = s->name;
3480 : 353 : s->name = NULL;
3481 : 353 : savepointLevel = s->savepointLevel;
3482 : :
3483 : 353 : AbortSubTransaction();
3484 : 353 : CleanupSubTransaction();
3485 : :
3486 : 353 : DefineSavepoint(NULL);
3487 : 353 : s = CurrentTransactionState; /* changed by push */
3488 : 353 : s->name = name;
3489 : 353 : s->savepointLevel = savepointLevel;
3490 : :
3491 : : /* This is the same as TBLOCK_SUBBEGIN case */
1492 peter@eisentraut.org 3492 [ - + ]: 353 : Assert(s->blockState == TBLOCK_SUBBEGIN);
8159 tgl@sss.pgh.pa.us 3493 : 353 : StartSubTransaction();
3494 : 353 : s->blockState = TBLOCK_SUBINPROGRESS;
3495 : : }
8185 3496 : 353 : break;
3497 : :
3498 : : /*
3499 : : * Same as above, but the subtransaction had already failed, so we
3500 : : * don't need AbortSubTransaction.
3501 : : */
8108 3502 : 211 : case TBLOCK_SUBABORT_RESTART:
3503 : : {
3504 : : char *name;
3505 : : int savepointLevel;
3506 : :
3507 : : /* save name and keep Cleanup from freeing it */
3508 : 211 : name = s->name;
3509 : 211 : s->name = NULL;
3510 : 211 : savepointLevel = s->savepointLevel;
3511 : :
3512 : 211 : CleanupSubTransaction();
3513 : :
3514 : 211 : DefineSavepoint(NULL);
3515 : 211 : s = CurrentTransactionState; /* changed by push */
3516 : 211 : s->name = name;
3517 : 211 : s->savepointLevel = savepointLevel;
3518 : :
3519 : : /* This is the same as TBLOCK_SUBBEGIN case */
1492 peter@eisentraut.org 3520 [ - + ]: 211 : Assert(s->blockState == TBLOCK_SUBBEGIN);
8108 tgl@sss.pgh.pa.us 3521 : 211 : StartSubTransaction();
3522 : 211 : s->blockState = TBLOCK_SUBINPROGRESS;
3523 : : }
3524 : 211 : break;
3525 : : }
3526 : :
3527 : : /* Done, no more iterations required */
954 akorotkov@postgresql 3528 : 521169 : return true;
3529 : : }
3530 : :
3531 : : /*
3532 : : * AbortCurrentTransaction -- a wrapper function handling the
3533 : : * loop over subtransactions to avoid potentially dangerous recursion in
3534 : : * AbortCurrentTransactionInternal().
3535 : : */
3536 : : void
8185 tgl@sss.pgh.pa.us 3537 : 35977 : AbortCurrentTransaction(void)
3538 : : {
3539 : : /*
3540 : : * Repeatedly call AbortCurrentTransactionInternal() until all the work is
3541 : : * done.
3542 : : */
954 akorotkov@postgresql 3543 [ - + ]: 35977 : while (!AbortCurrentTransactionInternal())
3544 : : {
3545 : : }
995 3546 : 35977 : }
3547 : :
3548 : : /*
3549 : : * AbortCurrentTransactionInternal - a function doing an iteration of work
3550 : : * regarding handling the current transaction abort. In the case of
3551 : : * subtransactions more than one iterations could be required. Returns
3552 : : * true when no more iterations required, false otherwise.
3553 : : */
3554 : : static bool
3555 : 35977 : AbortCurrentTransactionInternal(void)
3556 : : {
8185 tgl@sss.pgh.pa.us 3557 : 35977 : TransactionState s = CurrentTransactionState;
3558 : : SavedTransactionCharacteristics savetc;
3559 : :
3560 : : /* Must save in case we need to restore below */
15 michael@paquier.xyz 3561 : 35977 : SaveTransactionCharacteristics(&savetc);
3562 : :
8185 tgl@sss.pgh.pa.us 3563 [ + + - + : 35977 : switch (s->blockState)
+ + - - +
+ - - - ]
3564 : : {
8272 bruce@momjian.us 3565 : 57 : case TBLOCK_DEFAULT:
7951 tgl@sss.pgh.pa.us 3566 [ - + ]: 57 : if (s->state == TRANS_DEFAULT)
3567 : : {
3568 : : /* we are idle, so nothing to do */
3569 : : }
3570 : : else
3571 : : {
3572 : : /*
3573 : : * We can get here after an error during transaction start
3574 : : * (state will be TRANS_START). Need to clean up the
3575 : : * incompletely started transaction. First, adjust the
3576 : : * low-level state to suppress warning message from
3577 : : * AbortTransaction.
3578 : : */
7951 tgl@sss.pgh.pa.us 3579 [ # # ]:UBC 0 : if (s->state == TRANS_START)
3580 : 0 : s->state = TRANS_INPROGRESS;
3581 : 0 : AbortTransaction();
3582 : 0 : CleanupTransaction();
3583 : : }
8272 bruce@momjian.us 3584 :CBC 57 : break;
3585 : :
3586 : : /*
3587 : : * If we aren't in a transaction block, we just do the basic abort
3588 : : * & cleanup transaction. For this purpose, we treat an implicit
3589 : : * transaction block as if it were a simple statement.
3590 : : */
3591 : 33228 : case TBLOCK_STARTED:
3592 : : case TBLOCK_IMPLICIT_INPROGRESS:
10673 3593 : 33228 : AbortTransaction();
8599 tgl@sss.pgh.pa.us 3594 : 33228 : CleanupTransaction();
8272 bruce@momjian.us 3595 : 33228 : s->blockState = TBLOCK_DEFAULT;
10673 3596 : 33228 : break;
3597 : :
3598 : : /*
3599 : : * If we are in TBLOCK_BEGIN it means something screwed up right
3600 : : * after reading "BEGIN TRANSACTION". We assume that the user
3601 : : * will interpret the error as meaning the BEGIN failed to get him
3602 : : * into a transaction block, so we should abort and return to idle
3603 : : * state.
3604 : : */
10673 bruce@momjian.us 3605 :UBC 0 : case TBLOCK_BEGIN:
3606 : 0 : AbortTransaction();
8108 tgl@sss.pgh.pa.us 3607 : 0 : CleanupTransaction();
3608 : 0 : s->blockState = TBLOCK_DEFAULT;
10673 bruce@momjian.us 3609 : 0 : break;
3610 : :
3611 : : /*
3612 : : * We are somewhere in a transaction block and we've gotten a
3613 : : * failure, so we abort the transaction and set up the persistent
3614 : : * ABORT state. We will stay in ABORT until we get a ROLLBACK.
3615 : : */
10673 bruce@momjian.us 3616 :CBC 978 : case TBLOCK_INPROGRESS:
3617 : : case TBLOCK_PARALLEL_INPROGRESS:
3618 : 978 : AbortTransaction();
3619 : :
3620 : : /*
3621 : : * AbortTransaction() has reset the transaction characteristics;
3622 : : * restore them for AND CHAIN.
3623 : : */
15 michael@paquier.xyz 3624 : 978 : RestoreTransactionCharacteristics(&savetc);
8272 bruce@momjian.us 3625 : 978 : s->blockState = TBLOCK_ABORT;
3626 : : /* CleanupTransaction happens when we exit TBLOCK_ABORT_END */
10673 3627 : 978 : break;
3628 : :
3629 : : /*
3630 : : * Here, we failed while trying to COMMIT. Clean up the
3631 : : * transaction and return to idle state (we do not want to stay in
3632 : : * the transaction).
3633 : : */
3634 : 271 : case TBLOCK_END:
3635 : 271 : AbortTransaction();
9649 tgl@sss.pgh.pa.us 3636 : 271 : CleanupTransaction();
8272 bruce@momjian.us 3637 : 271 : s->blockState = TBLOCK_DEFAULT;
10673 3638 : 271 : break;
3639 : :
3640 : : /*
3641 : : * Here, we are already in an aborted transaction state and are
3642 : : * waiting for a ROLLBACK, but for some reason we failed again! So
3643 : : * we just remain in the abort state.
3644 : : */
3645 : 67 : case TBLOCK_ABORT:
3646 : : case TBLOCK_SUBABORT:
3647 : 67 : break;
3648 : :
3649 : : /*
3650 : : * We are in a failed transaction and we got the ROLLBACK command.
3651 : : * We have already aborted, we just need to cleanup and go to idle
3652 : : * state.
3653 : : */
8108 tgl@sss.pgh.pa.us 3654 :UBC 0 : case TBLOCK_ABORT_END:
9649 3655 : 0 : CleanupTransaction();
10673 bruce@momjian.us 3656 : 0 : s->blockState = TBLOCK_DEFAULT;
3657 : 0 : break;
3658 : :
3659 : : /*
3660 : : * We are in a live transaction and we got a ROLLBACK command.
3661 : : * Abort, cleanup, go to idle state.
3662 : : */
8108 tgl@sss.pgh.pa.us 3663 : 0 : case TBLOCK_ABORT_PENDING:
3664 : 0 : AbortTransaction();
3665 : 0 : CleanupTransaction();
3666 : 0 : s->blockState = TBLOCK_DEFAULT;
8185 3667 : 0 : break;
3668 : :
3669 : : /*
3670 : : * Here, we failed while trying to PREPARE. Clean up the
3671 : : * transaction and return to idle state (we do not want to stay in
3672 : : * the transaction).
3673 : : */
7834 tgl@sss.pgh.pa.us 3674 :CBC 63 : case TBLOCK_PREPARE:
3675 : 63 : AbortTransaction();
3676 : 63 : CleanupTransaction();
3677 : 63 : s->blockState = TBLOCK_DEFAULT;
3678 : 63 : break;
3679 : :
3680 : : /*
3681 : : * We got an error inside a subtransaction. Abort just the
3682 : : * subtransaction, and go to the persistent SUBABORT state until
3683 : : * we get ROLLBACK.
3684 : : */
8185 3685 : 1313 : case TBLOCK_SUBINPROGRESS:
3686 : 1313 : AbortSubTransaction();
3687 : 1313 : s->blockState = TBLOCK_SUBABORT;
3688 : 1313 : break;
3689 : :
3690 : : /*
3691 : : * If we failed while trying to create a subtransaction, clean up
3692 : : * the broken subtransaction and abort the parent. The same
3693 : : * applies if we get a failure while ending a subtransaction. As
3694 : : * we need to abort the parent, return false to request the caller
3695 : : * to do the next iteration.
3696 : : */
954 akorotkov@postgresql 3697 :UBC 0 : case TBLOCK_SUBBEGIN:
3698 : : case TBLOCK_SUBRELEASE:
3699 : : case TBLOCK_SUBCOMMIT:
3700 : : case TBLOCK_SUBABORT_PENDING:
3701 : : case TBLOCK_SUBRESTART:
3702 : 0 : AbortSubTransaction();
3703 : 0 : CleanupSubTransaction();
3704 : 0 : return false;
3705 : :
3706 : : /*
3707 : : * Same as above, except the Abort() was already done.
3708 : : */
3709 : 0 : case TBLOCK_SUBABORT_END:
3710 : : case TBLOCK_SUBABORT_RESTART:
3711 : 0 : CleanupSubTransaction();
3712 : 0 : return false;
3713 : : }
3714 : :
3715 : : /* Done, no more iterations required */
954 akorotkov@postgresql 3716 :CBC 35977 : return true;
3717 : : }
3718 : :
3719 : : /*
3720 : : * PreventInTransactionBlock
3721 : : *
3722 : : * This routine is to be called by statements that must not run inside
3723 : : * a transaction block, typically because they have non-rollback-able
3724 : : * side effects or do internal commits.
3725 : : *
3726 : : * If this routine completes successfully, then the calling statement is
3727 : : * guaranteed that if it completes without error, its results will be
3728 : : * committed immediately.
3729 : : *
3730 : : * If we have already started a transaction block, issue an error; also issue
3731 : : * an error if we appear to be running inside a user-defined function (which
3732 : : * could issue more commands and possibly cause a failure after the statement
3733 : : * completes). Subtransactions are verboten too.
3734 : : *
3735 : : * We must also set XACT_FLAGS_NEEDIMMEDIATECOMMIT in MyXactFlags, to ensure
3736 : : * that postgres.c follows through by committing after the statement is done.
3737 : : *
3738 : : * isTopLevel: passed down from ProcessUtility to determine whether we are
3739 : : * inside a function. (We will always fail if this is false, but it's
3740 : : * convenient to centralize the check here instead of making callers do it.)
3741 : : * stmtType: statement type name, for error messages.
3742 : : */
3743 : : void
3207 peter_e@gmx.net 3744 : 9688 : PreventInTransactionBlock(bool isTopLevel, const char *stmtType)
3745 : : {
3746 : : /*
3747 : : * xact block already started?
3748 : : */
8804 tgl@sss.pgh.pa.us 3749 [ + + ]: 9688 : if (IsTransactionBlock())
8531 3750 [ + - ]: 82 : ereport(ERROR,
3751 : : (errcode(ERRCODE_ACTIVE_SQL_TRANSACTION),
3752 : : /* translator: %s represents an SQL statement name */
3753 : : errmsg("%s cannot run inside a transaction block",
3754 : : stmtType)));
3755 : :
3756 : : /*
3757 : : * subtransaction?
3758 : : */
8185 3759 [ - + ]: 9606 : if (IsSubTransaction())
8185 tgl@sss.pgh.pa.us 3760 [ # # ]:UBC 0 : ereport(ERROR,
3761 : : (errcode(ERRCODE_ACTIVE_SQL_TRANSACTION),
3762 : : /* translator: %s represents an SQL statement name */
3763 : : errmsg("%s cannot run inside a subtransaction",
3764 : : stmtType)));
3765 : :
3766 : : /*
3767 : : * inside a function call?
3768 : : */
7200 tgl@sss.pgh.pa.us 3769 [ + + ]:CBC 9606 : if (!isTopLevel)
8531 3770 [ + - ]: 8 : ereport(ERROR,
3771 : : (errcode(ERRCODE_ACTIVE_SQL_TRANSACTION),
3772 : : /* translator: %s represents an SQL statement name */
3773 : : errmsg("%s cannot be executed from a function or procedure",
3774 : : stmtType)));
3775 : :
3776 : : /* If we got past IsTransactionBlock test, should be in default state */
8272 bruce@momjian.us 3777 [ + + ]: 9598 : if (CurrentTransactionState->blockState != TBLOCK_DEFAULT &&
8225 tgl@sss.pgh.pa.us 3778 [ - + ]: 8484 : CurrentTransactionState->blockState != TBLOCK_STARTED)
8185 tgl@sss.pgh.pa.us 3779 [ # # ]:UBC 0 : elog(FATAL, "cannot prevent transaction chain");
3780 : :
3781 : : /* All okay. Set the flag to make sure the right thing happens later. */
1586 tgl@sss.pgh.pa.us 3782 :CBC 9598 : MyXactFlags |= XACT_FLAGS_NEEDIMMEDIATECOMMIT;
8804 3783 : 9598 : }
3784 : :
3785 : : /*
3786 : : * WarnNoTransactionBlock
3787 : : * RequireTransactionBlock
3788 : : *
3789 : : * These two functions allow for warnings or errors if a command is executed
3790 : : * outside of a transaction block. This is useful for commands that have no
3791 : : * effects that persist past transaction end (and so calling them outside a
3792 : : * transaction block is presumably an error). DECLARE CURSOR is an example.
3793 : : * While top-level transaction control commands (BEGIN/COMMIT/ABORT) and SET
3794 : : * that have no effect issue warnings, all other no-effect commands generate
3795 : : * errors.
3796 : : *
3797 : : * If we appear to be running inside a user-defined function, we do not
3798 : : * issue anything, since the function could issue more commands that make
3799 : : * use of the current statement's results. Likewise subtransactions.
3800 : : * Thus these are inverses for PreventInTransactionBlock.
3801 : : *
3802 : : * isTopLevel: passed down from ProcessUtility to determine whether we are
3803 : : * inside a function.
3804 : : * stmtType: statement type name, for warning or error messages.
3805 : : */
3806 : : void
3207 peter_e@gmx.net 3807 : 1600 : WarnNoTransactionBlock(bool isTopLevel, const char *stmtType)
3808 : : {
3809 : 1600 : CheckTransactionBlock(isTopLevel, false, stmtType);
4751 bruce@momjian.us 3810 : 1600 : }
3811 : :
3812 : : void
3207 peter_e@gmx.net 3813 : 5307 : RequireTransactionBlock(bool isTopLevel, const char *stmtType)
3814 : : {
3815 : 5307 : CheckTransactionBlock(isTopLevel, true, stmtType);
4751 bruce@momjian.us 3816 : 5284 : }
3817 : :
3818 : : /*
3819 : : * This is the implementation of the above two.
3820 : : */
3821 : : static void
3207 peter_e@gmx.net 3822 : 6907 : CheckTransactionBlock(bool isTopLevel, bool throwError, const char *stmtType)
3823 : : {
3824 : : /*
3825 : : * xact block already started?
3826 : : */
8776 tgl@sss.pgh.pa.us 3827 [ + + ]: 6907 : if (IsTransactionBlock())
3828 : 6785 : return;
3829 : :
3830 : : /*
3831 : : * subtransaction?
3832 : : */
8185 3833 [ - + ]: 122 : if (IsSubTransaction())
8185 tgl@sss.pgh.pa.us 3834 :UBC 0 : return;
3835 : :
3836 : : /*
3837 : : * inside a function call?
3838 : : */
7200 tgl@sss.pgh.pa.us 3839 [ + + ]:CBC 122 : if (!isTopLevel)
8776 3840 : 85 : return;
3841 : :
4751 bruce@momjian.us 3842 [ + + + - ]: 37 : ereport(throwError ? ERROR : WARNING,
3843 : : (errcode(ERRCODE_NO_ACTIVE_SQL_TRANSACTION),
3844 : : /* translator: %s represents an SQL statement name */
3845 : : errmsg("%s can only be used in transaction blocks",
3846 : : stmtType)));
3847 : : }
3848 : :
3849 : : /*
3850 : : * IsInTransactionBlock
3851 : : *
3852 : : * This routine is for statements that need to behave differently inside
3853 : : * a transaction block than when running as single commands. ANALYZE is
3854 : : * currently the only example.
3855 : : *
3856 : : * If this routine returns "false", then the calling statement is allowed
3857 : : * to perform internal transaction-commit-and-start cycles; there is not a
3858 : : * risk of messing up any transaction already in progress. (Note that this
3859 : : * is not the identical guarantee provided by PreventInTransactionBlock,
3860 : : * since we will not force a post-statement commit.)
3861 : : *
3862 : : * isTopLevel: passed down from ProcessUtility to determine whether we are
3863 : : * inside a function.
3864 : : */
3865 : : bool
3207 peter_e@gmx.net 3866 : 3494 : IsInTransactionBlock(bool isTopLevel)
3867 : : {
3868 : : /*
3869 : : * Return true on same conditions that would make
3870 : : * PreventInTransactionBlock error out
3871 : : */
8225 tgl@sss.pgh.pa.us 3872 [ + + ]: 3494 : if (IsTransactionBlock())
3873 : 114 : return true;
3874 : :
8185 3875 [ - + ]: 3380 : if (IsSubTransaction())
8185 tgl@sss.pgh.pa.us 3876 :UBC 0 : return true;
3877 : :
7200 tgl@sss.pgh.pa.us 3878 [ + + ]:CBC 3380 : if (!isTopLevel)
8225 3879 : 76 : return true;
3880 : :
3881 [ + - ]: 3304 : if (CurrentTransactionState->blockState != TBLOCK_DEFAULT &&
3882 [ - + ]: 3304 : CurrentTransactionState->blockState != TBLOCK_STARTED)
8225 tgl@sss.pgh.pa.us 3883 :UBC 0 : return true;
3884 : :
8225 tgl@sss.pgh.pa.us 3885 :CBC 3304 : return false;
3886 : : }
3887 : :
3888 : :
3889 : : /*
3890 : : * Register or deregister callback functions for start- and end-of-xact
3891 : : * operations.
3892 : : *
3893 : : * These functions are intended for use by dynamically loaded modules.
3894 : : * For built-in modules we generally just hardwire the appropriate calls
3895 : : * (mainly because it's easier to control the order that way, where needed).
3896 : : *
3897 : : * At transaction end, the callback occurs post-commit or post-abort, so the
3898 : : * callback functions can only do noncritical cleanup.
3899 : : */
3900 : : void
8154 3901 : 2387 : RegisterXactCallback(XactCallback callback, void *arg)
3902 : : {
3903 : : XactCallbackItem *item;
3904 : :
3905 : : item = (XactCallbackItem *)
3906 : 2387 : MemoryContextAlloc(TopMemoryContext, sizeof(XactCallbackItem));
8462 3907 : 2387 : item->callback = callback;
3908 : 2387 : item->arg = arg;
8154 3909 : 2387 : item->next = Xact_callbacks;
3910 : 2387 : Xact_callbacks = item;
8462 3911 : 2387 : }
3912 : :
3913 : : void
8154 tgl@sss.pgh.pa.us 3914 :UBC 0 : UnregisterXactCallback(XactCallback callback, void *arg)
3915 : : {
3916 : : XactCallbackItem *item;
3917 : : XactCallbackItem *prev;
3918 : :
8462 3919 : 0 : prev = NULL;
8154 3920 [ # # ]: 0 : for (item = Xact_callbacks; item; prev = item, item = item->next)
3921 : : {
8462 3922 [ # # # # ]: 0 : if (item->callback == callback && item->arg == arg)
3923 : : {
3924 [ # # ]: 0 : if (prev)
3925 : 0 : prev->next = item->next;
3926 : : else
8154 3927 : 0 : Xact_callbacks = item->next;
8462 3928 : 0 : pfree(item);
3929 : 0 : break;
3930 : : }
3931 : : }
3932 : 0 : }
3933 : :
3934 : : static void
8108 tgl@sss.pgh.pa.us 3935 :CBC 847214 : CallXactCallbacks(XactEvent event)
3936 : : {
3937 : : XactCallbackItem *item;
3938 : : XactCallbackItem *next;
3939 : :
1522 3940 [ + + ]: 1067300 : for (item = Xact_callbacks; item; item = next)
3941 : : {
3942 : : /* allow callbacks to unregister themselves when called */
3943 : 220088 : next = item->next;
3369 peter_e@gmx.net 3944 : 220088 : item->callback(event, item->arg);
3945 : : }
8108 tgl@sss.pgh.pa.us 3946 : 847212 : }
3947 : :
3948 : :
3949 : : /*
3950 : : * Register or deregister callback functions for start- and end-of-subxact
3951 : : * operations.
3952 : : *
3953 : : * Pretty much same as above, but for subtransaction events.
3954 : : *
3955 : : * At subtransaction end, the callback occurs post-subcommit or post-subabort,
3956 : : * so the callback functions can only do noncritical cleanup. At
3957 : : * subtransaction start, the callback is called when the subtransaction has
3958 : : * finished initializing.
3959 : : */
3960 : : void
3961 : 2387 : RegisterSubXactCallback(SubXactCallback callback, void *arg)
3962 : : {
3963 : : SubXactCallbackItem *item;
3964 : :
3965 : : item = (SubXactCallbackItem *)
3966 : 2387 : MemoryContextAlloc(TopMemoryContext, sizeof(SubXactCallbackItem));
3967 : 2387 : item->callback = callback;
3968 : 2387 : item->arg = arg;
3969 : 2387 : item->next = SubXact_callbacks;
3970 : 2387 : SubXact_callbacks = item;
3971 : 2387 : }
3972 : :
3973 : : void
8108 tgl@sss.pgh.pa.us 3974 :UBC 0 : UnregisterSubXactCallback(SubXactCallback callback, void *arg)
3975 : : {
3976 : : SubXactCallbackItem *item;
3977 : : SubXactCallbackItem *prev;
3978 : :
3979 : 0 : prev = NULL;
3980 [ # # ]: 0 : for (item = SubXact_callbacks; item; prev = item, item = item->next)
3981 : : {
3982 [ # # # # ]: 0 : if (item->callback == callback && item->arg == arg)
3983 : : {
3984 [ # # ]: 0 : if (prev)
3985 : 0 : prev->next = item->next;
3986 : : else
3987 : 0 : SubXact_callbacks = item->next;
3988 : 0 : pfree(item);
3989 : 0 : break;
3990 : : }
3991 : : }
3992 : 0 : }
3993 : :
3994 : : static void
8108 tgl@sss.pgh.pa.us 3995 :CBC 63677 : CallSubXactCallbacks(SubXactEvent event,
3996 : : SubTransactionId mySubid,
3997 : : SubTransactionId parentSubid)
3998 : : {
3999 : : SubXactCallbackItem *item;
4000 : : SubXactCallbackItem *next;
4001 : :
1522 4002 [ + + ]: 121212 : for (item = SubXact_callbacks; item; item = next)
4003 : : {
4004 : : /* allow callbacks to unregister themselves when called */
4005 : 57535 : next = item->next;
3369 peter_e@gmx.net 4006 : 57535 : item->callback(event, mySubid, parentSubid, item->arg);
4007 : : }
8462 tgl@sss.pgh.pa.us 4008 : 63677 : }
4009 : :
4010 : :
4011 : : /* ----------------------------------------------------------------
4012 : : * transaction block support
4013 : : * ----------------------------------------------------------------
4014 : : */
4015 : :
4016 : : /*
4017 : : * BeginTransactionBlock
4018 : : * This executes a BEGIN command.
4019 : : */
4020 : : void
10674 bruce@momjian.us 4021 : 12757 : BeginTransactionBlock(void)
4022 : : {
4023 : 12757 : TransactionState s = CurrentTransactionState;
4024 : :
8159 tgl@sss.pgh.pa.us 4025 [ + + - - : 12757 : switch (s->blockState)
- ]
4026 : : {
4027 : : /*
4028 : : * We are not inside a transaction block, so allow one to begin.
4029 : : */
8272 bruce@momjian.us 4030 : 12238 : case TBLOCK_STARTED:
4031 : 12238 : s->blockState = TBLOCK_BEGIN;
4032 : 12238 : break;
4033 : :
4034 : : /*
4035 : : * BEGIN converts an implicit transaction block to a regular one.
4036 : : * (Note that we allow this even if we've already done some
4037 : : * commands, which is a bit odd but matches historical practice.)
4038 : : */
3369 tgl@sss.pgh.pa.us 4039 : 519 : case TBLOCK_IMPLICIT_INPROGRESS:
4040 : 519 : s->blockState = TBLOCK_BEGIN;
4041 : 519 : break;
4042 : :
4043 : : /*
4044 : : * Already a transaction block in progress.
4045 : : */
8272 bruce@momjian.us 4046 :UBC 0 : case TBLOCK_INPROGRESS:
4047 : : case TBLOCK_PARALLEL_INPROGRESS:
4048 : : case TBLOCK_SUBINPROGRESS:
4049 : : case TBLOCK_ABORT:
4050 : : case TBLOCK_SUBABORT:
8159 tgl@sss.pgh.pa.us 4051 [ # # ]: 0 : ereport(WARNING,
4052 : : (errcode(ERRCODE_ACTIVE_SQL_TRANSACTION),
4053 : : errmsg("there is already a transaction in progress")));
8272 bruce@momjian.us 4054 : 0 : break;
4055 : :
4056 : : /* These cases are invalid. */
4057 : 0 : case TBLOCK_DEFAULT:
4058 : : case TBLOCK_BEGIN:
4059 : : case TBLOCK_SUBBEGIN:
4060 : : case TBLOCK_END:
4061 : : case TBLOCK_SUBRELEASE:
4062 : : case TBLOCK_SUBCOMMIT:
4063 : : case TBLOCK_ABORT_END:
4064 : : case TBLOCK_SUBABORT_END:
4065 : : case TBLOCK_ABORT_PENDING:
4066 : : case TBLOCK_SUBABORT_PENDING:
4067 : : case TBLOCK_SUBRESTART:
4068 : : case TBLOCK_SUBABORT_RESTART:
4069 : : case TBLOCK_PREPARE:
8185 tgl@sss.pgh.pa.us 4070 [ # # ]: 0 : elog(FATAL, "BeginTransactionBlock: unexpected state %s",
4071 : : BlockStateAsString(s->blockState));
4072 : : break;
4073 : : }
11099 scrappy@hub.org 4074 :CBC 12757 : }
4075 : :
4076 : : /*
4077 : : * PrepareTransactionBlock
4078 : : * This executes a PREPARE command.
4079 : : *
4080 : : * Since PREPARE may actually do a ROLLBACK, the result indicates what
4081 : : * happened: true for PREPARE, false for ROLLBACK.
4082 : : *
4083 : : * Note that we don't actually do anything here except change blockState.
4084 : : * The real work will be done in the upcoming PrepareTransaction().
4085 : : * We do it this way because it's not convenient to change memory context,
4086 : : * resource owner, etc while executing inside a Portal.
4087 : : */
4088 : : bool
3315 peter_e@gmx.net 4089 : 374 : PrepareTransactionBlock(const char *gid)
4090 : : {
4091 : : TransactionState s;
4092 : : bool result;
4093 : :
4094 : : /* Set up to commit the current transaction */
2806 peter@eisentraut.org 4095 : 374 : result = EndTransactionBlock(false);
4096 : :
4097 : : /* If successful, change outer tblock state to PREPARE */
7834 tgl@sss.pgh.pa.us 4098 [ + + ]: 374 : if (result)
4099 : : {
4100 : 372 : s = CurrentTransactionState;
4101 : :
4102 [ + + ]: 483 : while (s->parent != NULL)
4103 : 111 : s = s->parent;
4104 : :
4105 [ + - ]: 372 : if (s->blockState == TBLOCK_END)
4106 : : {
4107 : : /* Save GID where PrepareTransaction can find it again */
4108 : 372 : prepareGID = MemoryContextStrdup(TopTransactionContext, gid);
4109 : :
4110 : 372 : s->blockState = TBLOCK_PREPARE;
4111 : : }
4112 : : else
4113 : : {
4114 : : /*
4115 : : * ignore case where we are not in a transaction;
4116 : : * EndTransactionBlock already issued a warning.
4117 : : */
3369 tgl@sss.pgh.pa.us 4118 [ # # # # ]:UBC 0 : Assert(s->blockState == TBLOCK_STARTED ||
4119 : : s->blockState == TBLOCK_IMPLICIT_INPROGRESS);
4120 : : /* Don't send back a PREPARE result tag... */
7834 4121 : 0 : result = false;
4122 : : }
4123 : : }
4124 : :
7834 tgl@sss.pgh.pa.us 4125 :CBC 374 : return result;
4126 : : }
4127 : :
4128 : : /*
4129 : : * EndTransactionBlock
4130 : : * This executes a COMMIT command.
4131 : : *
4132 : : * Since COMMIT may actually do a ROLLBACK, the result indicates what
4133 : : * happened: true for COMMIT, false for ROLLBACK.
4134 : : *
4135 : : * Note that we don't actually do anything here except change blockState.
4136 : : * The real work will be done in the upcoming CommitTransactionCommand().
4137 : : * We do it this way because it's not convenient to change memory context,
4138 : : * resource owner, etc while executing inside a Portal.
4139 : : */
4140 : : bool
2806 peter@eisentraut.org 4141 : 10155 : EndTransactionBlock(bool chain)
4142 : : {
10674 bruce@momjian.us 4143 : 10155 : TransactionState s = CurrentTransactionState;
8159 tgl@sss.pgh.pa.us 4144 : 10155 : bool result = false;
4145 : :
4146 [ + + + + : 10155 : switch (s->blockState)
+ + - -
- ]
4147 : : {
4148 : : /*
4149 : : * We are in a transaction block, so tell CommitTransactionCommand
4150 : : * to COMMIT.
4151 : : */
8272 bruce@momjian.us 4152 : 9105 : case TBLOCK_INPROGRESS:
8159 tgl@sss.pgh.pa.us 4153 : 9105 : s->blockState = TBLOCK_END;
4154 : 9105 : result = true;
8185 4155 : 9105 : break;
4156 : :
4157 : : /*
4158 : : * We are in an implicit transaction block. If AND CHAIN was
4159 : : * specified, error. Otherwise commit, but issue a warning
4160 : : * because there was no explicit BEGIN before this.
4161 : : */
3369 4162 : 32 : case TBLOCK_IMPLICIT_INPROGRESS:
2638 peter@eisentraut.org 4163 [ + + ]: 32 : if (chain)
4164 [ + - ]: 16 : ereport(ERROR,
4165 : : (errcode(ERRCODE_NO_ACTIVE_SQL_TRANSACTION),
4166 : : /* translator: %s represents an SQL statement name */
4167 : : errmsg("%s can only be used in transaction blocks",
4168 : : "COMMIT AND CHAIN")));
4169 : : else
4170 [ + - ]: 16 : ereport(WARNING,
4171 : : (errcode(ERRCODE_NO_ACTIVE_SQL_TRANSACTION),
4172 : : errmsg("there is no transaction in progress")));
3369 tgl@sss.pgh.pa.us 4173 : 16 : s->blockState = TBLOCK_END;
4174 : 16 : result = true;
4175 : 16 : break;
4176 : :
4177 : : /*
4178 : : * We are in a failed transaction block. Tell
4179 : : * CommitTransactionCommand it's time to exit the block.
4180 : : */
8272 bruce@momjian.us 4181 : 448 : case TBLOCK_ABORT:
8108 tgl@sss.pgh.pa.us 4182 : 448 : s->blockState = TBLOCK_ABORT_END;
8272 bruce@momjian.us 4183 : 448 : break;
4184 : :
4185 : : /*
4186 : : * We are in a live subtransaction block. Set up to subcommit all
4187 : : * open subtransactions and then commit the main transaction.
4188 : : */
8114 tgl@sss.pgh.pa.us 4189 : 512 : case TBLOCK_SUBINPROGRESS:
4190 [ + + ]: 1117 : while (s->parent != NULL)
4191 : : {
8108 4192 [ + - ]: 605 : if (s->blockState == TBLOCK_SUBINPROGRESS)
5611 simon@2ndQuadrant.co 4193 : 605 : s->blockState = TBLOCK_SUBCOMMIT;
4194 : : else
8108 tgl@sss.pgh.pa.us 4195 [ # # ]:UBC 0 : elog(FATAL, "EndTransactionBlock: unexpected state %s",
4196 : : BlockStateAsString(s->blockState));
8114 tgl@sss.pgh.pa.us 4197 :CBC 605 : s = s->parent;
4198 : : }
8108 4199 [ + - ]: 512 : if (s->blockState == TBLOCK_INPROGRESS)
4200 : 512 : s->blockState = TBLOCK_END;
4201 : : else
8108 tgl@sss.pgh.pa.us 4202 [ # # ]:UBC 0 : elog(FATAL, "EndTransactionBlock: unexpected state %s",
4203 : : BlockStateAsString(s->blockState));
8114 tgl@sss.pgh.pa.us 4204 :CBC 512 : result = true;
4205 : 512 : break;
4206 : :
4207 : : /*
4208 : : * Here we are inside an aborted subtransaction. Treat the COMMIT
4209 : : * as ROLLBACK: set up to abort everything and exit the main
4210 : : * transaction.
4211 : : */
8185 4212 : 42 : case TBLOCK_SUBABORT:
8108 4213 [ + + ]: 84 : while (s->parent != NULL)
4214 : : {
4215 [ - + ]: 42 : if (s->blockState == TBLOCK_SUBINPROGRESS)
8108 tgl@sss.pgh.pa.us 4216 :UBC 0 : s->blockState = TBLOCK_SUBABORT_PENDING;
8108 tgl@sss.pgh.pa.us 4217 [ + - ]:CBC 42 : else if (s->blockState == TBLOCK_SUBABORT)
4218 : 42 : s->blockState = TBLOCK_SUBABORT_END;
4219 : : else
8108 tgl@sss.pgh.pa.us 4220 [ # # ]:UBC 0 : elog(FATAL, "EndTransactionBlock: unexpected state %s",
4221 : : BlockStateAsString(s->blockState));
8108 tgl@sss.pgh.pa.us 4222 :CBC 42 : s = s->parent;
4223 : : }
4224 [ + - ]: 42 : if (s->blockState == TBLOCK_INPROGRESS)
4225 : 42 : s->blockState = TBLOCK_ABORT_PENDING;
8108 tgl@sss.pgh.pa.us 4226 [ # # ]:UBC 0 : else if (s->blockState == TBLOCK_ABORT)
4227 : 0 : s->blockState = TBLOCK_ABORT_END;
4228 : : else
4229 [ # # ]: 0 : elog(FATAL, "EndTransactionBlock: unexpected state %s",
4230 : : BlockStateAsString(s->blockState));
8185 tgl@sss.pgh.pa.us 4231 :CBC 42 : break;
4232 : :
4233 : : /*
4234 : : * The user issued COMMIT when not inside a transaction. For
4235 : : * COMMIT without CHAIN, issue a WARNING, staying in
4236 : : * TBLOCK_STARTED state. The upcoming call to
4237 : : * CommitTransactionCommand() will then close the transaction and
4238 : : * put us back into the default state. For COMMIT AND CHAIN,
4239 : : * error.
4240 : : */
8108 4241 : 16 : case TBLOCK_STARTED:
2638 peter@eisentraut.org 4242 [ + + ]: 16 : if (chain)
4243 [ + - ]: 4 : ereport(ERROR,
4244 : : (errcode(ERRCODE_NO_ACTIVE_SQL_TRANSACTION),
4245 : : /* translator: %s represents an SQL statement name */
4246 : : errmsg("%s can only be used in transaction blocks",
4247 : : "COMMIT AND CHAIN")));
4248 : : else
4249 [ + - ]: 12 : ereport(WARNING,
4250 : : (errcode(ERRCODE_NO_ACTIVE_SQL_TRANSACTION),
4251 : : errmsg("there is no transaction in progress")));
8064 tgl@sss.pgh.pa.us 4252 : 12 : result = true;
8272 bruce@momjian.us 4253 : 12 : break;
4254 : :
4255 : : /*
4256 : : * The user issued a COMMIT that somehow ran inside a parallel
4257 : : * worker. We can't cope with that.
4258 : : */
4230 rhaas@postgresql.org 4259 :UBC 0 : case TBLOCK_PARALLEL_INPROGRESS:
4260 [ # # ]: 0 : ereport(FATAL,
4261 : : (errcode(ERRCODE_INVALID_TRANSACTION_STATE),
4262 : : errmsg("cannot commit during a parallel operation")));
4263 : : break;
4264 : :
4265 : : /* These cases are invalid. */
8272 bruce@momjian.us 4266 : 0 : case TBLOCK_DEFAULT:
4267 : : case TBLOCK_BEGIN:
4268 : : case TBLOCK_SUBBEGIN:
4269 : : case TBLOCK_END:
4270 : : case TBLOCK_SUBRELEASE:
4271 : : case TBLOCK_SUBCOMMIT:
4272 : : case TBLOCK_ABORT_END:
4273 : : case TBLOCK_SUBABORT_END:
4274 : : case TBLOCK_ABORT_PENDING:
4275 : : case TBLOCK_SUBABORT_PENDING:
4276 : : case TBLOCK_SUBRESTART:
4277 : : case TBLOCK_SUBABORT_RESTART:
4278 : : case TBLOCK_PREPARE:
8185 tgl@sss.pgh.pa.us 4279 [ # # ]: 0 : elog(FATAL, "EndTransactionBlock: unexpected state %s",
4280 : : BlockStateAsString(s->blockState));
4281 : : break;
4282 : : }
4283 : :
2806 peter@eisentraut.org 4284 [ + + + + :CBC 10135 : Assert(s->blockState == TBLOCK_STARTED ||
+ + - + ]
4285 : : s->blockState == TBLOCK_END ||
4286 : : s->blockState == TBLOCK_ABORT_END ||
4287 : : s->blockState == TBLOCK_ABORT_PENDING);
4288 : :
4289 : 10135 : s->chain = chain;
4290 : :
8159 tgl@sss.pgh.pa.us 4291 : 10135 : return result;
4292 : : }
4293 : :
4294 : : /*
4295 : : * UserAbortTransactionBlock
4296 : : * This executes a ROLLBACK command.
4297 : : *
4298 : : * As above, we don't actually do anything here except change blockState.
4299 : : */
4300 : : void
2806 peter@eisentraut.org 4301 : 2419 : UserAbortTransactionBlock(bool chain)
4302 : : {
10674 bruce@momjian.us 4303 : 2419 : TransactionState s = CurrentTransactionState;
4304 : :
8159 tgl@sss.pgh.pa.us 4305 [ + + + + : 2419 : switch (s->blockState)
- - - ]
4306 : : {
4307 : : /*
4308 : : * We are inside a transaction block and we got a ROLLBACK command
4309 : : * from the user, so tell CommitTransactionCommand to abort and
4310 : : * exit the transaction block.
4311 : : */
8108 4312 : 1762 : case TBLOCK_INPROGRESS:
4313 : 1762 : s->blockState = TBLOCK_ABORT_PENDING;
8185 4314 : 1762 : break;
4315 : :
4316 : : /*
4317 : : * We are inside a failed transaction block and we got a ROLLBACK
4318 : : * command from the user. Abort processing is already done, so
4319 : : * CommitTransactionCommand just has to cleanup and go back to
4320 : : * idle state.
4321 : : */
8108 4322 : 511 : case TBLOCK_ABORT:
4323 : 511 : s->blockState = TBLOCK_ABORT_END;
8185 4324 : 511 : break;
4325 : :
4326 : : /*
4327 : : * We are inside a subtransaction. Mark everything up to top
4328 : : * level as exitable.
4329 : : */
4330 : 95 : case TBLOCK_SUBINPROGRESS:
4331 : : case TBLOCK_SUBABORT:
8108 4332 [ + + ]: 354 : while (s->parent != NULL)
4333 : : {
4334 [ + + ]: 259 : if (s->blockState == TBLOCK_SUBINPROGRESS)
4335 : 246 : s->blockState = TBLOCK_SUBABORT_PENDING;
4336 [ + - ]: 13 : else if (s->blockState == TBLOCK_SUBABORT)
4337 : 13 : s->blockState = TBLOCK_SUBABORT_END;
4338 : : else
8108 tgl@sss.pgh.pa.us 4339 [ # # ]:UBC 0 : elog(FATAL, "UserAbortTransactionBlock: unexpected state %s",
4340 : : BlockStateAsString(s->blockState));
8108 tgl@sss.pgh.pa.us 4341 :CBC 259 : s = s->parent;
4342 : : }
4343 [ + - ]: 95 : if (s->blockState == TBLOCK_INPROGRESS)
4344 : 95 : s->blockState = TBLOCK_ABORT_PENDING;
8108 tgl@sss.pgh.pa.us 4345 [ # # ]:UBC 0 : else if (s->blockState == TBLOCK_ABORT)
4346 : 0 : s->blockState = TBLOCK_ABORT_END;
4347 : : else
4348 [ # # ]: 0 : elog(FATAL, "UserAbortTransactionBlock: unexpected state %s",
4349 : : BlockStateAsString(s->blockState));
8185 tgl@sss.pgh.pa.us 4350 :CBC 95 : break;
4351 : :
4352 : : /*
4353 : : * The user issued ABORT when not inside a transaction. For
4354 : : * ROLLBACK without CHAIN, issue a WARNING and go to abort state.
4355 : : * The upcoming call to CommitTransactionCommand() will then put
4356 : : * us back into the default state. For ROLLBACK AND CHAIN, error.
4357 : : *
4358 : : * We do the same thing with ABORT inside an implicit transaction,
4359 : : * although in this case we might be rolling back actual database
4360 : : * state changes. (It's debatable whether we should issue a
4361 : : * WARNING in this case, but we have done so historically.)
4362 : : */
4363 : 51 : case TBLOCK_STARTED:
4364 : : case TBLOCK_IMPLICIT_INPROGRESS:
2638 peter@eisentraut.org 4365 [ + + ]: 51 : if (chain)
4366 [ + - ]: 20 : ereport(ERROR,
4367 : : (errcode(ERRCODE_NO_ACTIVE_SQL_TRANSACTION),
4368 : : /* translator: %s represents an SQL statement name */
4369 : : errmsg("%s can only be used in transaction blocks",
4370 : : "ROLLBACK AND CHAIN")));
4371 : : else
4372 [ + - ]: 31 : ereport(WARNING,
4373 : : (errcode(ERRCODE_NO_ACTIVE_SQL_TRANSACTION),
4374 : : errmsg("there is no transaction in progress")));
8108 tgl@sss.pgh.pa.us 4375 : 31 : s->blockState = TBLOCK_ABORT_PENDING;
8185 4376 : 31 : break;
4377 : :
4378 : : /*
4379 : : * The user issued an ABORT that somehow ran inside a parallel
4380 : : * worker. We can't cope with that.
4381 : : */
4230 rhaas@postgresql.org 4382 :UBC 0 : case TBLOCK_PARALLEL_INPROGRESS:
4383 [ # # ]: 0 : ereport(FATAL,
4384 : : (errcode(ERRCODE_INVALID_TRANSACTION_STATE),
4385 : : errmsg("cannot abort during a parallel operation")));
4386 : : break;
4387 : :
4388 : : /* These cases are invalid. */
8185 tgl@sss.pgh.pa.us 4389 : 0 : case TBLOCK_DEFAULT:
4390 : : case TBLOCK_BEGIN:
4391 : : case TBLOCK_SUBBEGIN:
4392 : : case TBLOCK_END:
4393 : : case TBLOCK_SUBRELEASE:
4394 : : case TBLOCK_SUBCOMMIT:
4395 : : case TBLOCK_ABORT_END:
4396 : : case TBLOCK_SUBABORT_END:
4397 : : case TBLOCK_ABORT_PENDING:
4398 : : case TBLOCK_SUBABORT_PENDING:
4399 : : case TBLOCK_SUBRESTART:
4400 : : case TBLOCK_SUBABORT_RESTART:
4401 : : case TBLOCK_PREPARE:
4402 [ # # ]: 0 : elog(FATAL, "UserAbortTransactionBlock: unexpected state %s",
4403 : : BlockStateAsString(s->blockState));
4404 : : break;
4405 : : }
4406 : :
2806 peter@eisentraut.org 4407 [ + + - + ]:CBC 2399 : Assert(s->blockState == TBLOCK_ABORT_END ||
4408 : : s->blockState == TBLOCK_ABORT_PENDING);
4409 : :
4410 : 2399 : s->chain = chain;
8159 tgl@sss.pgh.pa.us 4411 : 2399 : }
4412 : :
4413 : : /*
4414 : : * BeginImplicitTransactionBlock
4415 : : * Start an implicit transaction block if we're not already in one.
4416 : : *
4417 : : * Unlike BeginTransactionBlock, this is called directly from the main loop
4418 : : * in postgres.c, not within a Portal. So we can just change blockState
4419 : : * without a lot of ceremony. We do not expect caller to do
4420 : : * CommitTransactionCommand/StartTransactionCommand.
4421 : : */
4422 : : void
3369 4423 : 52070 : BeginImplicitTransactionBlock(void)
4424 : : {
4425 : 52070 : TransactionState s = CurrentTransactionState;
4426 : :
4427 : : /*
4428 : : * If we are in STARTED state (that is, no transaction block is open),
4429 : : * switch to IMPLICIT_INPROGRESS state, creating an implicit transaction
4430 : : * block.
4431 : : *
4432 : : * For caller convenience, we consider all other transaction states as
4433 : : * legal here; otherwise the caller would need its own state check, which
4434 : : * seems rather pointless.
4435 : : */
4436 [ + + ]: 52070 : if (s->blockState == TBLOCK_STARTED)
4437 : 6370 : s->blockState = TBLOCK_IMPLICIT_INPROGRESS;
4438 : 52070 : }
4439 : :
4440 : : /*
4441 : : * EndImplicitTransactionBlock
4442 : : * End an implicit transaction block, if we're in one.
4443 : : *
4444 : : * Like EndTransactionBlock, we just make any needed blockState change here.
4445 : : * The real work will be done in the upcoming CommitTransactionCommand().
4446 : : */
4447 : : void
4448 : 21317 : EndImplicitTransactionBlock(void)
4449 : : {
4450 : 21317 : TransactionState s = CurrentTransactionState;
4451 : :
4452 : : /*
4453 : : * If we are in IMPLICIT_INPROGRESS state, switch back to STARTED state,
4454 : : * allowing CommitTransactionCommand to commit whatever happened during
4455 : : * the implicit transaction block as though it were a single statement.
4456 : : *
4457 : : * For caller convenience, we consider all other transaction states as
4458 : : * legal here; otherwise the caller would need its own state check, which
4459 : : * seems rather pointless.
4460 : : */
4461 [ + + ]: 21317 : if (s->blockState == TBLOCK_IMPLICIT_INPROGRESS)
4462 : 5737 : s->blockState = TBLOCK_STARTED;
4463 : 21317 : }
4464 : :
4465 : : /*
4466 : : * DefineSavepoint
4467 : : * This executes a SAVEPOINT command.
4468 : : */
4469 : : void
3315 peter_e@gmx.net 4470 : 1791 : DefineSavepoint(const char *name)
4471 : : {
8126 bruce@momjian.us 4472 : 1791 : TransactionState s = CurrentTransactionState;
4473 : :
4474 : : /*
4475 : : * Workers synchronize transaction state at the beginning of each parallel
4476 : : * operation, so we can't account for new subtransactions after that
4477 : : * point. (Note that this check will certainly error out if s->blockState
4478 : : * is TBLOCK_PARALLEL_INPROGRESS, so we can treat that as an invalid case
4479 : : * below.)
4480 : : */
975 tgl@sss.pgh.pa.us 4481 [ + - - + ]: 1791 : if (IsInParallelMode() || IsParallelWorker())
4230 rhaas@postgresql.org 4482 [ # # ]:UBC 0 : ereport(ERROR,
4483 : : (errcode(ERRCODE_INVALID_TRANSACTION_STATE),
4484 : : errmsg("cannot define savepoints during a parallel operation")));
4485 : :
8159 tgl@sss.pgh.pa.us 4486 [ + + - - ]:CBC 1791 : switch (s->blockState)
4487 : : {
4488 : 1783 : case TBLOCK_INPROGRESS:
4489 : : case TBLOCK_SUBINPROGRESS:
4490 : : /* Normal subtransaction start */
4491 : 1783 : PushTransaction();
3447 4492 : 1783 : s = CurrentTransactionState; /* changed by push */
4493 : :
4494 : : /*
4495 : : * Savepoint names, like the TransactionState block itself, live
4496 : : * in TopTransactionContext.
4497 : : */
8108 4498 [ + + ]: 1783 : if (name)
4499 : 1219 : s->name = MemoryContextStrdup(TopTransactionContext, name);
8159 4500 : 1783 : break;
4501 : :
4502 : : /*
4503 : : * We disallow savepoint commands in implicit transaction blocks.
4504 : : * There would be no great difficulty in allowing them so far as
4505 : : * this module is concerned, but a savepoint seems inconsistent
4506 : : * with exec_simple_query's behavior of abandoning the whole query
4507 : : * string upon error. Also, the point of an implicit transaction
4508 : : * block (as opposed to a regular one) is to automatically close
4509 : : * after an error, so it's hard to see how a savepoint would fit
4510 : : * into that.
4511 : : *
4512 : : * The error messages for this are phrased as if there were no
4513 : : * active transaction block at all, which is historical but
4514 : : * perhaps could be improved.
4515 : : */
3369 4516 : 8 : case TBLOCK_IMPLICIT_INPROGRESS:
4517 [ + - ]: 8 : ereport(ERROR,
4518 : : (errcode(ERRCODE_NO_ACTIVE_SQL_TRANSACTION),
4519 : : /* translator: %s represents an SQL statement name */
4520 : : errmsg("%s can only be used in transaction blocks",
4521 : : "SAVEPOINT")));
4522 : : break;
4523 : :
4524 : : /* These cases are invalid. */
8159 tgl@sss.pgh.pa.us 4525 :UBC 0 : case TBLOCK_DEFAULT:
4526 : : case TBLOCK_STARTED:
4527 : : case TBLOCK_BEGIN:
4528 : : case TBLOCK_PARALLEL_INPROGRESS:
4529 : : case TBLOCK_SUBBEGIN:
4530 : : case TBLOCK_END:
4531 : : case TBLOCK_SUBRELEASE:
4532 : : case TBLOCK_SUBCOMMIT:
4533 : : case TBLOCK_ABORT:
4534 : : case TBLOCK_SUBABORT:
4535 : : case TBLOCK_ABORT_END:
4536 : : case TBLOCK_SUBABORT_END:
4537 : : case TBLOCK_ABORT_PENDING:
4538 : : case TBLOCK_SUBABORT_PENDING:
4539 : : case TBLOCK_SUBRESTART:
4540 : : case TBLOCK_SUBABORT_RESTART:
4541 : : case TBLOCK_PREPARE:
8155 4542 [ # # ]: 0 : elog(FATAL, "DefineSavepoint: unexpected state %s",
4543 : : BlockStateAsString(s->blockState));
4544 : : break;
4545 : : }
8159 tgl@sss.pgh.pa.us 4546 :CBC 1783 : }
4547 : :
4548 : : /*
4549 : : * ReleaseSavepoint
4550 : : * This executes a RELEASE command.
4551 : : *
4552 : : * As above, we don't actually do anything here except change blockState.
4553 : : */
4554 : : void
3207 peter_e@gmx.net 4555 : 190 : ReleaseSavepoint(const char *name)
4556 : : {
8126 bruce@momjian.us 4557 : 190 : TransactionState s = CurrentTransactionState;
4558 : : TransactionState target,
4559 : : xact;
4560 : :
4561 : : /*
4562 : : * Workers synchronize transaction state at the beginning of each parallel
4563 : : * operation, so we can't account for transaction state change after that
4564 : : * point. (Note that this check will certainly error out if s->blockState
4565 : : * is TBLOCK_PARALLEL_INPROGRESS, so we can treat that as an invalid case
4566 : : * below.)
4567 : : */
975 tgl@sss.pgh.pa.us 4568 [ + - - + ]: 190 : if (IsInParallelMode() || IsParallelWorker())
4230 rhaas@postgresql.org 4569 [ # # ]:UBC 0 : ereport(ERROR,
4570 : : (errcode(ERRCODE_INVALID_TRANSACTION_STATE),
4571 : : errmsg("cannot release savepoints during a parallel operation")));
4572 : :
8159 tgl@sss.pgh.pa.us 4573 [ - + + - :CBC 190 : switch (s->blockState)
- ]
4574 : : {
4575 : : /*
4576 : : * We can't release a savepoint if there is no savepoint defined.
4577 : : */
8159 tgl@sss.pgh.pa.us 4578 :UBC 0 : case TBLOCK_INPROGRESS:
4579 [ # # ]: 0 : ereport(ERROR,
4580 : : (errcode(ERRCODE_S_E_INVALID_SPECIFICATION),
4581 : : errmsg("savepoint \"%s\" does not exist", name)));
4582 : : break;
4583 : :
3369 tgl@sss.pgh.pa.us 4584 :CBC 4 : case TBLOCK_IMPLICIT_INPROGRESS:
4585 : : /* See comment about implicit transactions in DefineSavepoint */
4586 [ + - ]: 4 : ereport(ERROR,
4587 : : (errcode(ERRCODE_NO_ACTIVE_SQL_TRANSACTION),
4588 : : /* translator: %s represents an SQL statement name */
4589 : : errmsg("%s can only be used in transaction blocks",
4590 : : "RELEASE SAVEPOINT")));
4591 : : break;
4592 : :
4593 : : /*
4594 : : * We are in a non-aborted subtransaction. This is the only valid
4595 : : * case.
4596 : : */
8159 4597 : 186 : case TBLOCK_SUBINPROGRESS:
4598 : 186 : break;
4599 : :
4600 : : /* These cases are invalid. */
8159 tgl@sss.pgh.pa.us 4601 :UBC 0 : case TBLOCK_DEFAULT:
4602 : : case TBLOCK_STARTED:
4603 : : case TBLOCK_BEGIN:
4604 : : case TBLOCK_PARALLEL_INPROGRESS:
4605 : : case TBLOCK_SUBBEGIN:
4606 : : case TBLOCK_END:
4607 : : case TBLOCK_SUBRELEASE:
4608 : : case TBLOCK_SUBCOMMIT:
4609 : : case TBLOCK_ABORT:
4610 : : case TBLOCK_SUBABORT:
4611 : : case TBLOCK_ABORT_END:
4612 : : case TBLOCK_SUBABORT_END:
4613 : : case TBLOCK_ABORT_PENDING:
4614 : : case TBLOCK_SUBABORT_PENDING:
4615 : : case TBLOCK_SUBRESTART:
4616 : : case TBLOCK_SUBABORT_RESTART:
4617 : : case TBLOCK_PREPARE:
4618 [ # # ]: 0 : elog(FATAL, "ReleaseSavepoint: unexpected state %s",
4619 : : BlockStateAsString(s->blockState));
4620 : : break;
4621 : : }
4622 : :
430 peter@eisentraut.org 4623 [ + - ]:CBC 273 : for (target = s; target; target = target->parent)
4624 : : {
4625 [ + - + + ]: 273 : if (target->name && strcmp(target->name, name) == 0)
8159 tgl@sss.pgh.pa.us 4626 : 186 : break;
4627 : : }
4628 : :
430 peter@eisentraut.org 4629 [ - + ]: 186 : if (!target)
8159 tgl@sss.pgh.pa.us 4630 [ # # ]:UBC 0 : ereport(ERROR,
4631 : : (errcode(ERRCODE_S_E_INVALID_SPECIFICATION),
4632 : : errmsg("savepoint \"%s\" does not exist", name)));
4633 : :
4634 : : /* disallow crossing savepoint level boundaries */
8130 tgl@sss.pgh.pa.us 4635 [ - + ]:CBC 186 : if (target->savepointLevel != s->savepointLevel)
8130 tgl@sss.pgh.pa.us 4636 [ # # ]:UBC 0 : ereport(ERROR,
4637 : : (errcode(ERRCODE_S_E_INVALID_SPECIFICATION),
4638 : : errmsg("savepoint \"%s\" does not exist within current savepoint level", name)));
4639 : :
4640 : : /*
4641 : : * Mark "commit pending" all subtransactions up to the target
4642 : : * subtransaction. The actual commits will happen when control gets to
4643 : : * CommitTransactionCommand.
4644 : : */
8130 tgl@sss.pgh.pa.us 4645 :CBC 186 : xact = CurrentTransactionState;
4646 : : for (;;)
4647 : : {
4648 [ - + ]: 273 : Assert(xact->blockState == TBLOCK_SUBINPROGRESS);
5611 simon@2ndQuadrant.co 4649 : 273 : xact->blockState = TBLOCK_SUBRELEASE;
8130 tgl@sss.pgh.pa.us 4650 [ + + ]: 273 : if (xact == target)
4651 : 186 : break;
4652 : 87 : xact = xact->parent;
430 peter@eisentraut.org 4653 [ - + ]: 87 : Assert(xact);
4654 : : }
8159 tgl@sss.pgh.pa.us 4655 : 186 : }
4656 : :
4657 : : /*
4658 : : * RollbackToSavepoint
4659 : : * This executes a ROLLBACK TO <savepoint> command.
4660 : : *
4661 : : * As above, we don't actually do anything here except change blockState.
4662 : : */
4663 : : void
3207 peter_e@gmx.net 4664 : 572 : RollbackToSavepoint(const char *name)
4665 : : {
8159 tgl@sss.pgh.pa.us 4666 : 572 : TransactionState s = CurrentTransactionState;
4667 : : TransactionState target,
4668 : : xact;
4669 : :
4670 : : /*
4671 : : * Workers synchronize transaction state at the beginning of each parallel
4672 : : * operation, so we can't account for transaction state change after that
4673 : : * point. (Note that this check will certainly error out if s->blockState
4674 : : * is TBLOCK_PARALLEL_INPROGRESS, so we can treat that as an invalid case
4675 : : * below.)
4676 : : */
975 4677 [ + - - + ]: 572 : if (IsInParallelMode() || IsParallelWorker())
4230 rhaas@postgresql.org 4678 [ # # ]:UBC 0 : ereport(ERROR,
4679 : : (errcode(ERRCODE_INVALID_TRANSACTION_STATE),
4680 : : errmsg("cannot rollback to savepoints during a parallel operation")));
4681 : :
8159 tgl@sss.pgh.pa.us 4682 [ + + + - :CBC 572 : switch (s->blockState)
- ]
4683 : : {
4684 : : /*
4685 : : * We can't rollback to a savepoint if there is no savepoint
4686 : : * defined.
4687 : : */
4688 : 4 : case TBLOCK_INPROGRESS:
4689 : : case TBLOCK_ABORT:
4690 [ + - ]: 4 : ereport(ERROR,
4691 : : (errcode(ERRCODE_S_E_INVALID_SPECIFICATION),
4692 : : errmsg("savepoint \"%s\" does not exist", name)));
4693 : : break;
4694 : :
3369 4695 : 4 : case TBLOCK_IMPLICIT_INPROGRESS:
4696 : : /* See comment about implicit transactions in DefineSavepoint */
4697 [ + - ]: 4 : ereport(ERROR,
4698 : : (errcode(ERRCODE_NO_ACTIVE_SQL_TRANSACTION),
4699 : : /* translator: %s represents an SQL statement name */
4700 : : errmsg("%s can only be used in transaction blocks",
4701 : : "ROLLBACK TO SAVEPOINT")));
4702 : : break;
4703 : :
4704 : : /*
4705 : : * There is at least one savepoint, so proceed.
4706 : : */
8159 4707 : 564 : case TBLOCK_SUBINPROGRESS:
4708 : : case TBLOCK_SUBABORT:
4709 : 564 : break;
4710 : :
4711 : : /* These cases are invalid. */
8159 tgl@sss.pgh.pa.us 4712 :UBC 0 : case TBLOCK_DEFAULT:
4713 : : case TBLOCK_STARTED:
4714 : : case TBLOCK_BEGIN:
4715 : : case TBLOCK_PARALLEL_INPROGRESS:
4716 : : case TBLOCK_SUBBEGIN:
4717 : : case TBLOCK_END:
4718 : : case TBLOCK_SUBRELEASE:
4719 : : case TBLOCK_SUBCOMMIT:
4720 : : case TBLOCK_ABORT_END:
4721 : : case TBLOCK_SUBABORT_END:
4722 : : case TBLOCK_ABORT_PENDING:
4723 : : case TBLOCK_SUBABORT_PENDING:
4724 : : case TBLOCK_SUBRESTART:
4725 : : case TBLOCK_SUBABORT_RESTART:
4726 : : case TBLOCK_PREPARE:
4727 [ # # ]: 0 : elog(FATAL, "RollbackToSavepoint: unexpected state %s",
4728 : : BlockStateAsString(s->blockState));
4729 : : break;
4730 : : }
4731 : :
430 peter@eisentraut.org 4732 [ + - ]:CBC 602 : for (target = s; target; target = target->parent)
4733 : : {
4734 [ + - + + ]: 602 : if (target->name && strcmp(target->name, name) == 0)
8159 tgl@sss.pgh.pa.us 4735 : 564 : break;
4736 : : }
4737 : :
430 peter@eisentraut.org 4738 [ - + ]: 564 : if (!target)
8159 tgl@sss.pgh.pa.us 4739 [ # # ]:UBC 0 : ereport(ERROR,
4740 : : (errcode(ERRCODE_S_E_INVALID_SPECIFICATION),
4741 : : errmsg("savepoint \"%s\" does not exist", name)));
4742 : :
4743 : : /* disallow crossing savepoint level boundaries */
8152 tgl@sss.pgh.pa.us 4744 [ - + ]:CBC 564 : if (target->savepointLevel != s->savepointLevel)
8152 tgl@sss.pgh.pa.us 4745 [ # # ]:UBC 0 : ereport(ERROR,
4746 : : (errcode(ERRCODE_S_E_INVALID_SPECIFICATION),
4747 : : errmsg("savepoint \"%s\" does not exist within current savepoint level", name)));
4748 : :
4749 : : /*
4750 : : * Mark "abort pending" all subtransactions up to the target
4751 : : * subtransaction. The actual aborts will happen when control gets to
4752 : : * CommitTransactionCommand.
4753 : : */
8159 tgl@sss.pgh.pa.us 4754 :CBC 564 : xact = CurrentTransactionState;
4755 : : for (;;)
4756 : : {
8108 4757 [ + + ]: 602 : if (xact == target)
4758 : 564 : break;
4759 [ + - ]: 38 : if (xact->blockState == TBLOCK_SUBINPROGRESS)
4760 : 38 : xact->blockState = TBLOCK_SUBABORT_PENDING;
8108 tgl@sss.pgh.pa.us 4761 [ # # ]:UBC 0 : else if (xact->blockState == TBLOCK_SUBABORT)
4762 : 0 : xact->blockState = TBLOCK_SUBABORT_END;
4763 : : else
4764 [ # # ]: 0 : elog(FATAL, "RollbackToSavepoint: unexpected state %s",
4765 : : BlockStateAsString(xact->blockState));
8159 tgl@sss.pgh.pa.us 4766 :CBC 38 : xact = xact->parent;
430 peter@eisentraut.org 4767 [ - + ]: 38 : Assert(xact);
4768 : : }
4769 : :
4770 : : /* And mark the target as "restart pending" */
8108 tgl@sss.pgh.pa.us 4771 [ + + ]: 564 : if (xact->blockState == TBLOCK_SUBINPROGRESS)
4772 : 353 : xact->blockState = TBLOCK_SUBRESTART;
4773 [ + - ]: 211 : else if (xact->blockState == TBLOCK_SUBABORT)
4774 : 211 : xact->blockState = TBLOCK_SUBABORT_RESTART;
4775 : : else
8108 tgl@sss.pgh.pa.us 4776 [ # # ]:UBC 0 : elog(FATAL, "RollbackToSavepoint: unexpected state %s",
4777 : : BlockStateAsString(xact->blockState));
8159 tgl@sss.pgh.pa.us 4778 :CBC 564 : }
4779 : :
4780 : : /*
4781 : : * BeginInternalSubTransaction
4782 : : * This is the same as DefineSavepoint except it allows TBLOCK_STARTED,
4783 : : * TBLOCK_IMPLICIT_INPROGRESS, TBLOCK_PARALLEL_INPROGRESS, TBLOCK_END,
4784 : : * and TBLOCK_PREPARE states, and therefore it can safely be used in
4785 : : * functions that might be called when not inside a BEGIN block or when
4786 : : * running deferred triggers at COMMIT/PREPARE time. Also, it
4787 : : * automatically does CommitTransactionCommand/StartTransactionCommand
4788 : : * instead of expecting the caller to do it.
4789 : : */
4790 : : void
3315 peter_e@gmx.net 4791 : 21348 : BeginInternalSubTransaction(const char *name)
4792 : : {
8126 bruce@momjian.us 4793 : 21348 : TransactionState s = CurrentTransactionState;
975 tgl@sss.pgh.pa.us 4794 : 21348 : bool save_ExitOnAnyError = ExitOnAnyError;
4795 : :
4796 : : /*
4797 : : * Errors within this function are improbable, but if one does happen we
4798 : : * force a FATAL exit. Callers generally aren't prepared to handle losing
4799 : : * control, and moreover our transaction state is probably corrupted if we
4800 : : * fail partway through; so an ordinary ERROR longjmp isn't okay.
4801 : : */
4802 : 21348 : ExitOnAnyError = true;
4803 : :
4804 : : /*
4805 : : * We do not check for parallel mode here. It's permissible to start and
4806 : : * end "internal" subtransactions while in parallel mode, so long as no
4807 : : * new XIDs or command IDs are assigned. Enforcement of that occurs in
4808 : : * AssignTransactionId() and CommandCounterIncrement().
4809 : : */
4810 : :
8155 4811 [ + - - ]: 21348 : switch (s->blockState)
4812 : : {
4813 : 21348 : case TBLOCK_STARTED:
4814 : : case TBLOCK_INPROGRESS:
4815 : : case TBLOCK_IMPLICIT_INPROGRESS:
4816 : : case TBLOCK_PARALLEL_INPROGRESS:
4817 : : case TBLOCK_END:
4818 : : case TBLOCK_PREPARE:
4819 : : case TBLOCK_SUBINPROGRESS:
4820 : : /* Normal subtransaction start */
4821 : 21348 : PushTransaction();
3447 4822 : 21348 : s = CurrentTransactionState; /* changed by push */
4823 : :
4824 : : /*
4825 : : * Savepoint names, like the TransactionState block itself, live
4826 : : * in TopTransactionContext.
4827 : : */
8155 4828 [ + + ]: 21348 : if (name)
8108 4829 : 1047 : s->name = MemoryContextStrdup(TopTransactionContext, name);
8155 4830 : 21348 : break;
4831 : :
4832 : : /* These cases are invalid. */
8155 tgl@sss.pgh.pa.us 4833 :UBC 0 : case TBLOCK_DEFAULT:
4834 : : case TBLOCK_BEGIN:
4835 : : case TBLOCK_SUBBEGIN:
4836 : : case TBLOCK_SUBRELEASE:
4837 : : case TBLOCK_SUBCOMMIT:
4838 : : case TBLOCK_ABORT:
4839 : : case TBLOCK_SUBABORT:
4840 : : case TBLOCK_ABORT_END:
4841 : : case TBLOCK_SUBABORT_END:
4842 : : case TBLOCK_ABORT_PENDING:
4843 : : case TBLOCK_SUBABORT_PENDING:
4844 : : case TBLOCK_SUBRESTART:
4845 : : case TBLOCK_SUBABORT_RESTART:
4846 [ # # ]: 0 : elog(FATAL, "BeginInternalSubTransaction: unexpected state %s",
4847 : : BlockStateAsString(s->blockState));
4848 : : break;
4849 : : }
4850 : :
8155 tgl@sss.pgh.pa.us 4851 :CBC 21348 : CommitTransactionCommand();
4852 : 21348 : StartTransactionCommand();
4853 : :
975 4854 : 21348 : ExitOnAnyError = save_ExitOnAnyError;
8155 4855 : 21348 : }
4856 : :
4857 : : /*
4858 : : * ReleaseCurrentSubTransaction
4859 : : *
4860 : : * RELEASE (ie, commit) the innermost subtransaction, regardless of its
4861 : : * savepoint name (if any).
4862 : : * NB: do NOT use CommitTransactionCommand/StartTransactionCommand with this.
4863 : : */
4864 : : void
4865 : 16537 : ReleaseCurrentSubTransaction(void)
4866 : : {
4867 : 16537 : TransactionState s = CurrentTransactionState;
4868 : :
4869 : : /*
4870 : : * We do not check for parallel mode here. It's permissible to start and
4871 : : * end "internal" subtransactions while in parallel mode, so long as no
4872 : : * new XIDs or command IDs are assigned.
4873 : : */
4874 : :
4875 [ - + ]: 16537 : if (s->blockState != TBLOCK_SUBINPROGRESS)
8155 tgl@sss.pgh.pa.us 4876 [ # # ]:UBC 0 : elog(ERROR, "ReleaseCurrentSubTransaction: unexpected state %s",
4877 : : BlockStateAsString(s->blockState));
8114 tgl@sss.pgh.pa.us 4878 [ - + ]:CBC 16537 : Assert(s->state == TRANS_INPROGRESS);
8155 4879 : 16537 : MemoryContextSwitchTo(CurTransactionContext);
5561 simon@2ndQuadrant.co 4880 : 16537 : CommitSubTransaction();
7714 bruce@momjian.us 4881 : 16537 : s = CurrentTransactionState; /* changed by pop */
8114 tgl@sss.pgh.pa.us 4882 [ - + ]: 16537 : Assert(s->state == TRANS_INPROGRESS);
8155 4883 : 16537 : }
4884 : :
4885 : : /*
4886 : : * RollbackAndReleaseCurrentSubTransaction
4887 : : *
4888 : : * ROLLBACK and RELEASE (ie, abort) the innermost subtransaction, regardless
4889 : : * of its savepoint name (if any).
4890 : : * NB: do NOT use CommitTransactionCommand/StartTransactionCommand with this.
4891 : : */
4892 : : void
4893 : 4811 : RollbackAndReleaseCurrentSubTransaction(void)
4894 : : {
4895 : 4811 : TransactionState s = CurrentTransactionState;
4896 : :
4897 : : /*
4898 : : * We do not check for parallel mode here. It's permissible to start and
4899 : : * end "internal" subtransactions while in parallel mode, so long as no
4900 : : * new XIDs or command IDs are assigned.
4901 : : */
4902 : :
4903 [ + - - ]: 4811 : switch (s->blockState)
4904 : : {
4905 : : /* Must be in a subtransaction */
4906 : 4811 : case TBLOCK_SUBINPROGRESS:
4907 : : case TBLOCK_SUBABORT:
4908 : 4811 : break;
4909 : :
4910 : : /* These cases are invalid. */
8155 tgl@sss.pgh.pa.us 4911 :UBC 0 : case TBLOCK_DEFAULT:
4912 : : case TBLOCK_STARTED:
4913 : : case TBLOCK_BEGIN:
4914 : : case TBLOCK_IMPLICIT_INPROGRESS:
4915 : : case TBLOCK_PARALLEL_INPROGRESS:
4916 : : case TBLOCK_SUBBEGIN:
4917 : : case TBLOCK_INPROGRESS:
4918 : : case TBLOCK_END:
4919 : : case TBLOCK_SUBRELEASE:
4920 : : case TBLOCK_SUBCOMMIT:
4921 : : case TBLOCK_ABORT:
4922 : : case TBLOCK_ABORT_END:
4923 : : case TBLOCK_SUBABORT_END:
4924 : : case TBLOCK_ABORT_PENDING:
4925 : : case TBLOCK_SUBABORT_PENDING:
4926 : : case TBLOCK_SUBRESTART:
4927 : : case TBLOCK_SUBABORT_RESTART:
4928 : : case TBLOCK_PREPARE:
4929 [ # # ]: 0 : elog(FATAL, "RollbackAndReleaseCurrentSubTransaction: unexpected state %s",
4930 : : BlockStateAsString(s->blockState));
4931 : : break;
4932 : : }
4933 : :
4934 : : /*
4935 : : * Abort the current subtransaction, if needed.
4936 : : */
8155 tgl@sss.pgh.pa.us 4937 [ + + ]:CBC 4811 : if (s->blockState == TBLOCK_SUBINPROGRESS)
4938 : 3764 : AbortSubTransaction();
4939 : :
4940 : : /* And clean it up, too */
8108 4941 : 4811 : CleanupSubTransaction();
4942 : :
4943 : 4811 : s = CurrentTransactionState; /* changed by pop */
1492 peter@eisentraut.org 4944 [ + + + + : 4811 : Assert(s->blockState == TBLOCK_SUBINPROGRESS ||
+ - + + +
+ + - -
+ ]
4945 : : s->blockState == TBLOCK_INPROGRESS ||
4946 : : s->blockState == TBLOCK_IMPLICIT_INPROGRESS ||
4947 : : s->blockState == TBLOCK_PARALLEL_INPROGRESS ||
4948 : : s->blockState == TBLOCK_END ||
4949 : : s->blockState == TBLOCK_PREPARE ||
4950 : : s->blockState == TBLOCK_STARTED);
11099 scrappy@hub.org 4951 : 4811 : }
4952 : :
4953 : : /*
4954 : : * AbortOutOfAnyTransaction
4955 : : *
4956 : : * This routine is provided for error recovery purposes. It aborts any
4957 : : * active transaction or transaction block, leaving the system in a known
4958 : : * idle state.
4959 : : */
4960 : : void
9531 tgl@sss.pgh.pa.us 4961 : 20829 : AbortOutOfAnyTransaction(void)
4962 : : {
10280 4963 : 20829 : TransactionState s = CurrentTransactionState;
4964 : :
4965 : : /* Ensure we're not running in a doomed memory context */
3393 4966 : 20829 : AtAbort_Memory();
4967 : :
4968 : : /*
4969 : : * Get out of any transaction or nested transaction
4970 : : */
4971 : : do
4972 : : {
8185 4973 [ + + + + : 20831 : switch (s->blockState)
- - ]
4974 : : {
4975 : 20114 : case TBLOCK_DEFAULT:
5297 4976 [ - + ]: 20114 : if (s->state == TRANS_DEFAULT)
4977 : : {
4978 : : /* Not in a transaction, do nothing */
4979 : : }
4980 : : else
4981 : : {
4982 : : /*
4983 : : * We can get here after an error during transaction start
4984 : : * (state will be TRANS_START). Need to clean up the
4985 : : * incompletely started transaction. First, adjust the
4986 : : * low-level state to suppress warning message from
4987 : : * AbortTransaction.
4988 : : */
5297 tgl@sss.pgh.pa.us 4989 [ # # ]:UBC 0 : if (s->state == TRANS_START)
4990 : 0 : s->state = TRANS_INPROGRESS;
4991 : 0 : AbortTransaction();
4992 : 0 : CleanupTransaction();
4993 : : }
8185 tgl@sss.pgh.pa.us 4994 :CBC 20114 : break;
4995 : 696 : case TBLOCK_STARTED:
4996 : : case TBLOCK_BEGIN:
4997 : : case TBLOCK_INPROGRESS:
4998 : : case TBLOCK_IMPLICIT_INPROGRESS:
4999 : : case TBLOCK_PARALLEL_INPROGRESS:
5000 : : case TBLOCK_END:
5001 : : case TBLOCK_ABORT_PENDING:
5002 : : case TBLOCK_PREPARE:
5003 : : /* In a transaction, so clean up */
5004 : 696 : AbortTransaction();
5005 : 696 : CleanupTransaction();
5006 : 696 : s->blockState = TBLOCK_DEFAULT;
5007 : 696 : break;
5008 : 19 : case TBLOCK_ABORT:
5009 : : case TBLOCK_ABORT_END:
5010 : :
5011 : : /*
5012 : : * AbortTransaction is already done, still need Cleanup.
5013 : : * However, if we failed partway through running ROLLBACK,
5014 : : * there will be an active portal running that command, which
5015 : : * we need to shut down before doing CleanupTransaction.
5016 : : */
3393 5017 : 19 : AtAbort_Portals();
8185 5018 : 19 : CleanupTransaction();
5019 : 19 : s->blockState = TBLOCK_DEFAULT;
5020 : 19 : break;
5021 : :
5022 : : /*
5023 : : * In a subtransaction, so clean it up and abort parent too
5024 : : */
8108 5025 : 2 : case TBLOCK_SUBBEGIN:
5026 : : case TBLOCK_SUBINPROGRESS:
5027 : : case TBLOCK_SUBRELEASE:
5028 : : case TBLOCK_SUBCOMMIT:
5029 : : case TBLOCK_SUBABORT_PENDING:
5030 : : case TBLOCK_SUBRESTART:
8185 5031 : 2 : AbortSubTransaction();
5032 : 2 : CleanupSubTransaction();
8126 bruce@momjian.us 5033 : 2 : s = CurrentTransactionState; /* changed by pop */
8185 tgl@sss.pgh.pa.us 5034 : 2 : break;
5035 : :
8185 tgl@sss.pgh.pa.us 5036 :UBC 0 : case TBLOCK_SUBABORT:
5037 : : case TBLOCK_SUBABORT_END:
5038 : : case TBLOCK_SUBABORT_RESTART:
5039 : : /* As above, but AbortSubTransaction already done */
3393 5040 [ # # ]: 0 : if (s->curTransactionOwner)
5041 : : {
5042 : : /* As in TBLOCK_ABORT, might have a live portal to zap */
5043 : 0 : AtSubAbort_Portals(s->subTransactionId,
5044 : 0 : s->parent->subTransactionId,
5045 : : s->curTransactionOwner,
5046 : 0 : s->parent->curTransactionOwner);
5047 : : }
8185 5048 : 0 : CleanupSubTransaction();
8126 bruce@momjian.us 5049 : 0 : s = CurrentTransactionState; /* changed by pop */
8185 tgl@sss.pgh.pa.us 5050 : 0 : break;
5051 : : }
8185 tgl@sss.pgh.pa.us 5052 [ + + ]:CBC 20831 : } while (s->blockState != TBLOCK_DEFAULT);
5053 : :
5054 : : /* Should be out of all subxacts now */
5055 [ - + ]: 20829 : Assert(s->parent == NULL);
5056 : :
5057 : : /*
5058 : : * Revert to TopMemoryContext, to ensure we exit in a well-defined state
5059 : : * whether there were any transactions to close or not. (Callers that
5060 : : * don't intend to exit soon should switch to some other context to avoid
5061 : : * long-term memory leaks.)
5062 : : */
880 5063 : 20829 : MemoryContextSwitchTo(TopMemoryContext);
10280 5064 : 20829 : }
5065 : :
5066 : : /*
5067 : : * IsTransactionBlock --- are we within a transaction block?
5068 : : */
5069 : : bool
9531 5070 : 252893 : IsTransactionBlock(void)
5071 : : {
10674 bruce@momjian.us 5072 : 252893 : TransactionState s = CurrentTransactionState;
5073 : :
8272 5074 [ + + + + ]: 252893 : if (s->blockState == TBLOCK_DEFAULT || s->blockState == TBLOCK_STARTED)
8617 tgl@sss.pgh.pa.us 5075 : 181008 : return false;
5076 : :
5077 : 71885 : return true;
5078 : : }
5079 : :
5080 : : /*
5081 : : * IsTransactionOrTransactionBlock --- are we within either a transaction
5082 : : * or a transaction block?
5083 : : *
5084 : : * This looks only at the transaction block state, so it returns false while
5085 : : * we're in the middle of starting a transaction, before the transaction
5086 : : * block state has been updated. See also IsCompletelyOutOfTransaction().
5087 : : *
5088 : : * This should match up with IsTransactionBlock and IsTransactionState.
5089 : : */
5090 : : bool
8444 5091 : 473290 : IsTransactionOrTransactionBlock(void)
5092 : : {
5093 : 473290 : TransactionState s = CurrentTransactionState;
5094 : :
8272 bruce@momjian.us 5095 [ + + ]: 473290 : if (s->blockState == TBLOCK_DEFAULT)
8444 tgl@sss.pgh.pa.us 5096 : 377630 : return false;
5097 : :
5098 : 95660 : return true;
5099 : : }
5100 : :
5101 : : /*
5102 : : * IsCompletelyOutOfTransaction --- are we completely out of a transaction?
5103 : : *
5104 : : * The backend is only really "idle" when this returns true. Note that the
5105 : : * purpose of this function is different from that of IsTransactionState().
5106 : : * IsTransactionState() is used to check if we're in a live transaction where
5107 : : * it's safe to access the database, while IsCompletelyOutOfTransaction() is
5108 : : * used to check if we're completely out of a transaction. When we're in the
5109 : : * middle of starting or ending a transaction, we're neither in a live
5110 : : * transaction nor completely out of a transaction.
5111 : : *
5112 : : * This differs from !IsTransactionOrTransactionBlock() in that it also checks
5113 : : * the low-level transaction state, so that it returns false while we're in
5114 : : * the middle of StartTransaction(), or cleaning up a transaction that failed
5115 : : * to start.
5116 : : */
5117 : : bool
2 heikki.linnakangas@i 5118 :GNC 413242 : IsCompletelyOutOfTransaction(void)
5119 : : {
5120 : 413242 : TransactionState s = CurrentTransactionState;
5121 : :
5122 [ + + + - ]: 413242 : return s->blockState == TBLOCK_DEFAULT && s->state == TRANS_DEFAULT;
5123 : : }
5124 : :
5125 : : /*
5126 : : * TransactionBlockStatusCode - return status code to send in ReadyForQuery
5127 : : */
5128 : : char
8617 tgl@sss.pgh.pa.us 5129 :CBC 429840 : TransactionBlockStatusCode(void)
5130 : : {
5131 : 429840 : TransactionState s = CurrentTransactionState;
5132 : :
5133 [ + + + - ]: 429840 : switch (s->blockState)
5134 : : {
5135 : 334864 : case TBLOCK_DEFAULT:
5136 : : case TBLOCK_STARTED:
5137 : 334864 : return 'I'; /* idle --- not in transaction */
5138 : 93653 : case TBLOCK_BEGIN:
5139 : : case TBLOCK_SUBBEGIN:
5140 : : case TBLOCK_INPROGRESS:
5141 : : case TBLOCK_IMPLICIT_INPROGRESS:
5142 : : case TBLOCK_PARALLEL_INPROGRESS:
5143 : : case TBLOCK_SUBINPROGRESS:
5144 : : case TBLOCK_END:
5145 : : case TBLOCK_SUBRELEASE:
5146 : : case TBLOCK_SUBCOMMIT:
5147 : : case TBLOCK_PREPARE:
5148 : 93653 : return 'T'; /* in transaction */
5149 : 1323 : case TBLOCK_ABORT:
5150 : : case TBLOCK_SUBABORT:
5151 : : case TBLOCK_ABORT_END:
5152 : : case TBLOCK_SUBABORT_END:
5153 : : case TBLOCK_ABORT_PENDING:
5154 : : case TBLOCK_SUBABORT_PENDING:
5155 : : case TBLOCK_SUBRESTART:
5156 : : case TBLOCK_SUBABORT_RESTART:
5157 : 1323 : return 'E'; /* in failed transaction */
5158 : : }
5159 : :
5160 : : /* should never get here */
8185 tgl@sss.pgh.pa.us 5161 [ # # ]:UBC 0 : elog(FATAL, "invalid transaction block state: %s",
5162 : : BlockStateAsString(s->blockState));
5163 : : return 0; /* keep compiler quiet */
5164 : : }
5165 : :
5166 : : /*
5167 : : * IsSubTransaction
5168 : : */
5169 : : bool
8185 tgl@sss.pgh.pa.us 5170 :CBC 696591 : IsSubTransaction(void)
5171 : : {
5172 : 696591 : TransactionState s = CurrentTransactionState;
5173 : :
8154 5174 [ + + ]: 696591 : if (s->nestingLevel >= 2)
5175 : 489 : return true;
5176 : :
5177 : 696102 : return false;
5178 : : }
5179 : :
5180 : : /*
5181 : : * StartSubTransaction
5182 : : *
5183 : : * If you're wondering why this is separate from PushTransaction: it's because
5184 : : * we can't conveniently do this stuff right inside DefineSavepoint. The
5185 : : * SAVEPOINT utility command will be executed inside a Portal, and if we
5186 : : * muck with CurrentMemoryContext or CurrentResourceOwner then exit from
5187 : : * the Portal will undo those settings. So we make DefineSavepoint just
5188 : : * push a dummy transaction block, and when control returns to the main
5189 : : * idle loop, CommitTransactionCommand will be called, and we'll come here
5190 : : * to finish starting the subtransaction.
5191 : : */
5192 : : static void
8185 5193 : 23131 : StartSubTransaction(void)
5194 : : {
5195 : 23131 : TransactionState s = CurrentTransactionState;
5196 : :
5197 [ - + ]: 23131 : if (s->state != TRANS_DEFAULT)
8158 tgl@sss.pgh.pa.us 5198 [ # # ]:UBC 0 : elog(WARNING, "StartSubTransaction while in %s state",
5199 : : TransStateAsString(s->state));
5200 : :
8185 tgl@sss.pgh.pa.us 5201 :CBC 23131 : s->state = TRANS_START;
5202 : :
5203 : : /*
5204 : : * Initialize subsystems for new subtransaction
5205 : : *
5206 : : * must initialize resource-management stuff first
5207 : : */
8169 5208 : 23131 : AtSubStart_Memory();
5209 : 23131 : AtSubStart_ResourceOwner();
8114 5210 : 23131 : AfterTriggerBeginSubXact();
5211 : :
8185 5212 : 23131 : s->state = TRANS_INPROGRESS;
5213 : :
5214 : : /*
5215 : : * Call start-of-subxact callbacks
5216 : : */
8108 5217 : 23131 : CallSubXactCallbacks(SUBXACT_EVENT_START_SUB, s->subTransactionId,
5218 : 23131 : s->parent->subTransactionId);
5219 : :
8185 5220 : 23131 : ShowTransactionState("StartSubTransaction");
5221 : 23131 : }
5222 : :
5223 : : /*
5224 : : * CommitSubTransaction
5225 : : *
5226 : : * The caller has to make sure to always reassign CurrentTransactionState
5227 : : * if it has a local pointer to it after calling this function.
5228 : : */
5229 : : static void
5561 simon@2ndQuadrant.co 5230 : 17415 : CommitSubTransaction(void)
5231 : : {
8185 tgl@sss.pgh.pa.us 5232 : 17415 : TransactionState s = CurrentTransactionState;
5233 : :
5234 : 17415 : ShowTransactionState("CommitSubTransaction");
5235 : :
5236 [ - + ]: 17415 : if (s->state != TRANS_INPROGRESS)
8158 tgl@sss.pgh.pa.us 5237 [ # # ]:UBC 0 : elog(WARNING, "CommitSubTransaction while in %s state",
5238 : : TransStateAsString(s->state));
5239 : :
5240 : : /* Pre-commit processing goes here */
5241 : :
5035 tgl@sss.pgh.pa.us 5242 :CBC 17415 : CallSubXactCallbacks(SUBXACT_EVENT_PRE_COMMIT_SUB, s->subTransactionId,
5243 : 17415 : s->parent->subTransactionId);
5244 : :
5245 : : /*
5246 : : * If this subxact has started any unfinished parallel operation, clean up
5247 : : * its workers and exit parallel mode. Warn about leaked resources.
5248 : : */
975 5249 : 17415 : AtEOSubXact_Parallel(true, s->subTransactionId);
5250 [ - + ]: 17415 : if (s->parallelModeLevel != 0)
5251 : : {
975 tgl@sss.pgh.pa.us 5252 [ # # ]:UBC 0 : elog(WARNING, "parallelModeLevel is %d not 0 at end of subtransaction",
5253 : : s->parallelModeLevel);
4230 rhaas@postgresql.org 5254 : 0 : s->parallelModeLevel = 0;
5255 : : }
5256 : :
5257 : : /* Do the actual "commit", such as it is */
8185 tgl@sss.pgh.pa.us 5258 :CBC 17415 : s->state = TRANS_COMMIT;
5259 : :
5260 : : /* Must CCI to ensure commands of subtransaction are seen as done */
5261 : 17415 : CommandCounterIncrement();
5262 : :
5263 : : /*
5264 : : * Prior to 8.4 we marked subcommit in clog at this point. We now only
5265 : : * perform that step, if required, as part of the atomic update of the
5266 : : * whole transaction tree at top level commit or abort.
5267 : : */
5268 : :
5269 : : /* Post-commit cleanup */
2802 tmunro@postgresql.or 5270 [ + + ]: 17415 : if (FullTransactionIdIsValid(s->fullTransactionId))
7024 tgl@sss.pgh.pa.us 5271 : 15470 : AtSubCommit_childXids();
8114 5272 : 17415 : AfterTriggerEndSubXact(true);
8108 5273 : 17415 : AtSubCommit_Portals(s->subTransactionId,
5274 : 17415 : s->parent->subTransactionId,
1884 5275 : 17415 : s->parent->nestingLevel,
8154 5276 : 17415 : s->parent->curTransactionOwner);
8108 5277 : 17415 : AtEOSubXact_LargeObject(true, s->subTransactionId,
5278 : 17415 : s->parent->subTransactionId);
8154 5279 : 17415 : AtSubCommit_Notify();
5280 : :
8108 5281 : 17415 : CallSubXactCallbacks(SUBXACT_EVENT_COMMIT_SUB, s->subTransactionId,
5282 : 17415 : s->parent->subTransactionId);
5283 : :
8169 5284 : 17415 : ResourceOwnerRelease(s->curTransactionOwner,
5285 : : RESOURCE_RELEASE_BEFORE_LOCKS,
5286 : : true, false);
8108 5287 : 17415 : AtEOSubXact_RelationCache(true, s->subTransactionId,
5288 : 17415 : s->parent->subTransactionId);
765 akorotkov@postgresql 5289 : 17415 : AtEOSubXact_TypeCache();
8154 tgl@sss.pgh.pa.us 5290 : 17415 : AtEOSubXact_Inval(true);
8118 5291 : 17415 : AtSubCommit_smgr();
5292 : :
5293 : : /*
5294 : : * The only lock we actually release here is the subtransaction XID lock.
5295 : : */
8108 5296 : 17415 : CurrentResourceOwner = s->curTransactionOwner;
2802 tmunro@postgresql.or 5297 [ + + ]: 17415 : if (FullTransactionIdIsValid(s->fullTransactionId))
5298 : 15470 : XactLockTableDelete(XidFromFullTransactionId(s->fullTransactionId));
5299 : :
5300 : : /*
5301 : : * Other locks should get transferred to their parent resource owner.
5302 : : */
8130 tgl@sss.pgh.pa.us 5303 : 17415 : ResourceOwnerRelease(s->curTransactionOwner,
5304 : : RESOURCE_RELEASE_LOCKS,
5305 : : true, false);
8169 5306 : 17415 : ResourceOwnerRelease(s->curTransactionOwner,
5307 : : RESOURCE_RELEASE_AFTER_LOCKS,
5308 : : true, false);
5309 : :
7026 5310 : 17415 : AtEOXact_GUC(true, s->gucNestLevel);
8108 5311 : 17415 : AtEOSubXact_SPI(true, s->subTransactionId);
5312 : 17415 : AtEOSubXact_on_commit_actions(true, s->subTransactionId,
5313 : 17415 : s->parent->subTransactionId);
5314 : 17415 : AtEOSubXact_Namespace(true, s->subTransactionId,
5315 : 17415 : s->parent->subTransactionId);
5316 : 17415 : AtEOSubXact_Files(true, s->subTransactionId,
5317 : 17415 : s->parent->subTransactionId);
7156 5318 : 17415 : AtEOSubXact_HashTables(true, s->nestingLevel);
7125 5319 : 17415 : AtEOSubXact_PgStat(true, s->nestingLevel);
6774 alvherre@alvh.no-ip. 5320 : 17415 : AtSubCommit_Snapshot(s->nestingLevel);
5321 : :
5322 : : /*
5323 : : * We need to restore the upper transaction's read-only state, in case the
5324 : : * upper is read-write while the child is read-only; GUC will incorrectly
5325 : : * think it should leave the child state in place.
5326 : : */
8158 tgl@sss.pgh.pa.us 5327 : 17415 : XactReadOnly = s->prevXactReadOnly;
5328 : :
8169 5329 : 17415 : CurrentResourceOwner = s->parent->curTransactionOwner;
5330 : 17415 : CurTransactionResourceOwner = s->parent->curTransactionOwner;
8130 5331 : 17415 : ResourceOwnerDelete(s->curTransactionOwner);
8169 5332 : 17415 : s->curTransactionOwner = NULL;
5333 : :
8185 5334 : 17415 : AtSubCommit_Memory();
5335 : :
5336 : 17415 : s->state = TRANS_DEFAULT;
5337 : :
8108 5338 : 17415 : PopTransaction();
8185 5339 : 17415 : }
5340 : :
5341 : : /*
5342 : : * AbortSubTransaction
5343 : : */
5344 : : static void
5345 : 5716 : AbortSubTransaction(void)
5346 : : {
5347 : 5716 : TransactionState s = CurrentTransactionState;
5348 : :
5349 : : /* Prevent cancel/die interrupt while cleaning up */
5350 : 5716 : HOLD_INTERRUPTS();
5351 : :
5352 : : /* Make sure we have a valid memory context and resource owner */
7310 5353 : 5716 : AtSubAbort_Memory();
5354 : 5716 : AtSubAbort_ResourceOwner();
5355 : :
5356 : : /*
5357 : : * Release any LW locks we might be holding as quickly as possible.
5358 : : * (Regular locks, however, must be held till we finish aborting.)
5359 : : * Releasing LW locks is critical since we might try to grab them again
5360 : : * while cleaning up!
5361 : : *
5362 : : * FIXME This may be incorrect --- Are there some locks we should keep?
5363 : : * Buffer locks, for example? I don't think so but I'm not sure.
5364 : : */
8185 5365 : 5716 : LWLockReleaseAll();
5366 : :
5367 : : /*
5368 : : * Cleanup waiting for LSN if any.
5369 : : */
206 akorotkov@postgresql 5370 : 5716 : WaitLSNCleanup();
5371 : :
3915 rhaas@postgresql.org 5372 : 5716 : pgstat_report_wait_end();
5373 : 5716 : pgstat_progress_end_command();
5374 : :
621 andres@anarazel.de 5375 : 5716 : pgaio_error_cleanup();
5376 : :
8185 tgl@sss.pgh.pa.us 5377 : 5716 : UnlockBuffers();
5378 : :
5379 : : /* Reset WAL record construction state */
4391 heikki.linnakangas@i 5380 : 5716 : XLogResetInsertion();
5381 : :
5382 : : /* Cancel condition variable sleep */
3264 rhaas@postgresql.org 5383 : 5716 : ConditionVariableCancelSleep();
5384 : :
5385 : : /*
5386 : : * Also clean up any open wait for lock, since the lock manager will choke
5387 : : * if we try to wait for another lock before doing this.
5388 : : */
5337 5389 : 5716 : LockErrorCleanup();
5390 : :
5391 : : /*
5392 : : * If any timeout events are still active, make sure the timeout interrupt
5393 : : * is scheduled. This covers possible loss of a timeout interrupt due to
5394 : : * longjmp'ing out of the SIGINT handler (see notes in handle_sig_alarm).
5395 : : * We delay this till after LockErrorCleanup so that we don't uselessly
5396 : : * reschedule lock or deadlock check timeouts.
5397 : : */
4747 tgl@sss.pgh.pa.us 5398 : 5716 : reschedule_timeouts();
5399 : :
5400 : : /*
5401 : : * Re-enable signals, in case we got here by longjmp'ing out of a signal
5402 : : * handler. We do this fairly early in the sequence so that the timeout
5403 : : * infrastructure will be functional if needed while aborting.
5404 : : */
1394 tmunro@postgresql.or 5405 : 5716 : sigprocmask(SIG_SETMASK, &UnBlockSig, NULL);
5406 : :
5407 : : /*
5408 : : * check the current transaction state
5409 : : */
7310 tgl@sss.pgh.pa.us 5410 : 5716 : ShowTransactionState("AbortSubTransaction");
5411 : :
5412 [ - + ]: 5716 : if (s->state != TRANS_INPROGRESS)
7310 tgl@sss.pgh.pa.us 5413 [ # # ]:UBC 0 : elog(WARNING, "AbortSubTransaction while in %s state",
5414 : : TransStateAsString(s->state));
5415 : :
7310 tgl@sss.pgh.pa.us 5416 :CBC 5716 : s->state = TRANS_ABORT;
5417 : :
5418 : : /*
5419 : : * Reset user ID which might have been changed transiently. (See notes in
5420 : : * AbortTransaction.)
5421 : : */
6198 5422 : 5716 : SetUserIdAndSecContext(s->prevUser, s->prevSecContext);
5423 : :
5424 : : /* Forget about any active REINDEX. */
2412 5425 : 5716 : ResetReindexState(s->nestingLevel);
5426 : :
5427 : : /* Reset logical streaming state. */
2303 akapila@postgresql.o 5428 : 5716 : ResetLogicalStreamingState();
5429 : :
5430 : : /*
5431 : : * No need for SnapBuildResetExportedSnapshotState() here, snapshot
5432 : : * exports are not supported in subtransactions.
5433 : : */
5434 : :
5435 : : /*
5436 : : * If this subxact has started any unfinished parallel operation, clean up
5437 : : * its workers and exit parallel mode. Don't warn about leaked resources.
5438 : : */
975 tgl@sss.pgh.pa.us 5439 : 5716 : AtEOSubXact_Parallel(false, s->subTransactionId);
5440 : 5716 : s->parallelModeLevel = 0;
5441 : :
5442 : : /*
5443 : : * We can skip all this stuff if the subxact failed before creating a
5444 : : * ResourceOwner...
5445 : : */
8108 5446 [ + - ]: 5716 : if (s->curTransactionOwner)
5447 : : {
5448 : 5716 : AfterTriggerEndSubXact(false);
5449 : 5716 : AtSubAbort_Portals(s->subTransactionId,
5450 : 5716 : s->parent->subTransactionId,
5451 : : s->curTransactionOwner,
5452 : 5716 : s->parent->curTransactionOwner);
5453 : 5716 : AtEOSubXact_LargeObject(false, s->subTransactionId,
5454 : 5716 : s->parent->subTransactionId);
5455 : 5716 : AtSubAbort_Notify();
5456 : :
5457 : : /* Advertise the fact that we aborted in pg_xact. */
7021 5458 : 5716 : (void) RecordTransactionAbort(true);
5459 : :
5460 : : /* Post-abort cleanup */
2802 tmunro@postgresql.or 5461 [ + + ]: 5716 : if (FullTransactionIdIsValid(s->fullTransactionId))
8108 tgl@sss.pgh.pa.us 5462 : 1041 : AtSubAbort_childXids();
5463 : :
5464 : 5716 : CallSubXactCallbacks(SUBXACT_EVENT_ABORT_SUB, s->subTransactionId,
5465 : 5716 : s->parent->subTransactionId);
5466 : :
5467 : 5716 : ResourceOwnerRelease(s->curTransactionOwner,
5468 : : RESOURCE_RELEASE_BEFORE_LOCKS,
5469 : : false, false);
5470 : :
621 andres@anarazel.de 5471 : 5716 : AtEOXact_Aio(false);
8108 tgl@sss.pgh.pa.us 5472 : 5716 : AtEOSubXact_RelationCache(false, s->subTransactionId,
5473 : 5716 : s->parent->subTransactionId);
765 akorotkov@postgresql 5474 : 5716 : AtEOSubXact_TypeCache();
8108 tgl@sss.pgh.pa.us 5475 : 5716 : AtEOSubXact_Inval(false);
5476 : 5716 : ResourceOwnerRelease(s->curTransactionOwner,
5477 : : RESOURCE_RELEASE_LOCKS,
5478 : : false, false);
5479 : 5716 : ResourceOwnerRelease(s->curTransactionOwner,
5480 : : RESOURCE_RELEASE_AFTER_LOCKS,
5481 : : false, false);
5280 rhaas@postgresql.org 5482 : 5716 : AtSubAbort_smgr();
5483 : :
7026 tgl@sss.pgh.pa.us 5484 : 5716 : AtEOXact_GUC(false, s->gucNestLevel);
8108 5485 : 5716 : AtEOSubXact_SPI(false, s->subTransactionId);
5486 : 5716 : AtEOSubXact_on_commit_actions(false, s->subTransactionId,
5487 : 5716 : s->parent->subTransactionId);
5488 : 5716 : AtEOSubXact_Namespace(false, s->subTransactionId,
5489 : 5716 : s->parent->subTransactionId);
5490 : 5716 : AtEOSubXact_Files(false, s->subTransactionId,
5491 : 5716 : s->parent->subTransactionId);
7156 5492 : 5716 : AtEOSubXact_HashTables(false, s->nestingLevel);
7125 5493 : 5716 : AtEOSubXact_PgStat(false, s->nestingLevel);
6774 alvherre@alvh.no-ip. 5494 : 5716 : AtSubAbort_Snapshot(s->nestingLevel);
5495 : : }
5496 : :
5497 : : /*
5498 : : * Restore the upper transaction's read-only state, too. This should be
5499 : : * redundant with GUC's cleanup but we may as well do it for consistency
5500 : : * with the commit case.
5501 : : */
8158 tgl@sss.pgh.pa.us 5502 : 5716 : XactReadOnly = s->prevXactReadOnly;
5503 : :
8185 5504 [ - + ]: 5716 : RESUME_INTERRUPTS();
5505 : 5716 : }
5506 : :
5507 : : /*
5508 : : * CleanupSubTransaction
5509 : : *
5510 : : * The caller has to make sure to always reassign CurrentTransactionState
5511 : : * if it has a local pointer to it after calling this function.
5512 : : */
5513 : : static void
5514 : 5716 : CleanupSubTransaction(void)
5515 : : {
5516 : 5716 : TransactionState s = CurrentTransactionState;
5517 : :
5518 : 5716 : ShowTransactionState("CleanupSubTransaction");
5519 : :
5520 [ - + ]: 5716 : if (s->state != TRANS_ABORT)
8158 tgl@sss.pgh.pa.us 5521 [ # # ]:UBC 0 : elog(WARNING, "CleanupSubTransaction while in %s state",
5522 : : TransStateAsString(s->state));
5523 : :
8108 tgl@sss.pgh.pa.us 5524 :CBC 5716 : AtSubCleanup_Portals(s->subTransactionId);
5525 : :
8169 5526 : 5716 : CurrentResourceOwner = s->parent->curTransactionOwner;
5527 : 5716 : CurTransactionResourceOwner = s->parent->curTransactionOwner;
8108 5528 [ + - ]: 5716 : if (s->curTransactionOwner)
5529 : 5716 : ResourceOwnerDelete(s->curTransactionOwner);
8169 5530 : 5716 : s->curTransactionOwner = NULL;
5531 : :
8185 5532 : 5716 : AtSubCleanup_Memory();
5533 : :
5534 : 5716 : s->state = TRANS_DEFAULT;
5535 : :
8108 5536 : 5716 : PopTransaction();
8185 5537 : 5716 : }
5538 : :
5539 : : /*
5540 : : * PushTransaction
5541 : : * Create transaction state stack entry for a subtransaction
5542 : : *
5543 : : * The caller has to make sure to always reassign CurrentTransactionState
5544 : : * if it has a local pointer to it after calling this function.
5545 : : */
5546 : : static void
5547 : 23131 : PushTransaction(void)
5548 : : {
8126 bruce@momjian.us 5549 : 23131 : TransactionState p = CurrentTransactionState;
5550 : : TransactionState s;
5551 : :
5552 : : /*
5553 : : * We keep subtransaction state nodes in TopTransactionContext.
5554 : : */
5555 : : s = (TransactionState)
8185 tgl@sss.pgh.pa.us 5556 : 23131 : MemoryContextAllocZero(TopTransactionContext,
5557 : : sizeof(TransactionStateData));
5558 : :
5559 : : /*
5560 : : * Assign a subtransaction ID, watching out for counter wraparound.
5561 : : */
8108 5562 : 23131 : currentSubTransactionId += 1;
5563 [ - + ]: 23131 : if (currentSubTransactionId == InvalidSubTransactionId)
5564 : : {
8108 tgl@sss.pgh.pa.us 5565 :UBC 0 : currentSubTransactionId -= 1;
5566 : 0 : pfree(s);
5567 [ # # ]: 0 : ereport(ERROR,
5568 : : (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
5569 : : errmsg("cannot have more than 2^32-1 subtransactions in a transaction")));
5570 : : }
5571 : :
5572 : : /*
5573 : : * We can now stack a minimally valid subtransaction without fear of
5574 : : * failure.
5575 : : */
2802 tmunro@postgresql.or 5576 :CBC 23131 : s->fullTransactionId = InvalidFullTransactionId; /* until assigned */
8108 tgl@sss.pgh.pa.us 5577 : 23131 : s->subTransactionId = currentSubTransactionId;
8185 5578 : 23131 : s->parent = p;
5579 : 23131 : s->nestingLevel = p->nestingLevel + 1;
7026 5580 : 23131 : s->gucNestLevel = NewGUCNestLevel();
8159 5581 : 23131 : s->savepointLevel = p->savepointLevel;
8185 5582 : 23131 : s->state = TRANS_DEFAULT;
5583 : 23131 : s->blockState = TBLOCK_SUBBEGIN;
6198 5584 : 23131 : GetUserIdAndSecContext(&s->prevUser, &s->prevSecContext);
8108 5585 : 23131 : s->prevXactReadOnly = XactReadOnly;
1082 michael@paquier.xyz 5586 : 23131 : s->startedInRecovery = p->startedInRecovery;
4230 rhaas@postgresql.org 5587 : 23131 : s->parallelModeLevel = 0;
975 tgl@sss.pgh.pa.us 5588 [ + + - + ]: 23131 : s->parallelChildXact = (p->parallelModeLevel != 0 || p->parallelChildXact);
1852 akapila@postgresql.o 5589 : 23131 : s->topXidLogged = false;
5590 : :
8108 tgl@sss.pgh.pa.us 5591 : 23131 : CurrentTransactionState = s;
5592 : :
5593 : : /*
5594 : : * AbortSubTransaction and CleanupSubTransaction have to be able to cope
5595 : : * with the subtransaction from here on out; in particular they should not
5596 : : * assume that it necessarily has a transaction context, resource owner,
5597 : : * or XID.
5598 : : */
8185 5599 : 23131 : }
5600 : :
5601 : : /*
5602 : : * PopTransaction
5603 : : * Pop back to parent transaction state
5604 : : *
5605 : : * The caller has to make sure to always reassign CurrentTransactionState
5606 : : * if it has a local pointer to it after calling this function.
5607 : : */
5608 : : static void
5609 : 23131 : PopTransaction(void)
5610 : : {
5611 : 23131 : TransactionState s = CurrentTransactionState;
5612 : :
5613 [ - + ]: 23131 : if (s->state != TRANS_DEFAULT)
8158 tgl@sss.pgh.pa.us 5614 [ # # ]:UBC 0 : elog(WARNING, "PopTransaction while in %s state",
5615 : : TransStateAsString(s->state));
5616 : :
8185 tgl@sss.pgh.pa.us 5617 [ - + ]:CBC 23131 : if (s->parent == NULL)
8185 tgl@sss.pgh.pa.us 5618 [ # # ]:UBC 0 : elog(FATAL, "PopTransaction with no parent");
5619 : :
8185 tgl@sss.pgh.pa.us 5620 :CBC 23131 : CurrentTransactionState = s->parent;
5621 : :
5622 : : /* Let's just make sure CurTransactionContext is good */
5623 : 23131 : CurTransactionContext = s->parent->curTransactionContext;
5624 : 23131 : MemoryContextSwitchTo(CurTransactionContext);
5625 : :
5626 : : /* Ditto for ResourceOwner links */
8169 5627 : 23131 : CurTransactionResourceOwner = s->parent->curTransactionOwner;
5628 : 23131 : CurrentResourceOwner = s->parent->curTransactionOwner;
5629 : :
5630 : : /* Free the old child structure */
8159 5631 [ + + ]: 23131 : if (s->name)
5632 : 2266 : pfree(s->name);
8185 5633 : 23131 : pfree(s);
5634 : 23131 : }
5635 : :
5636 : : /*
5637 : : * EstimateTransactionStateSpace
5638 : : * Estimate the amount of space that will be needed by
5639 : : * SerializeTransactionState. It would be OK to overestimate slightly,
5640 : : * but it's simple for us to work out the precise value, so we do.
5641 : : */
5642 : : Size
4230 rhaas@postgresql.org 5643 : 683 : EstimateTransactionStateSpace(void)
5644 : : {
5645 : : TransactionState s;
2802 tmunro@postgresql.or 5646 : 683 : Size nxids = 0;
5647 : 683 : Size size = SerializedTransactionStateHeaderSize;
5648 : :
4230 rhaas@postgresql.org 5649 [ + + ]: 3058 : for (s = CurrentTransactionState; s != NULL; s = s->parent)
5650 : : {
2802 tmunro@postgresql.or 5651 [ + + ]: 2375 : if (FullTransactionIdIsValid(s->fullTransactionId))
4230 rhaas@postgresql.org 5652 : 1370 : nxids = add_size(nxids, 1);
5653 : 2375 : nxids = add_size(nxids, s->nChildXids);
5654 : : }
5655 : :
2787 tmunro@postgresql.or 5656 : 683 : return add_size(size, mul_size(sizeof(TransactionId), nxids));
5657 : : }
5658 : :
5659 : : /*
5660 : : * SerializeTransactionState
5661 : : * Write out relevant details of our transaction state that will be
5662 : : * needed by a parallel worker.
5663 : : *
5664 : : * We need to save and restore XactDeferrable, XactIsoLevel, and the XIDs
5665 : : * associated with this transaction. These are serialized into a
5666 : : * caller-supplied buffer big enough to hold the number of bytes reported by
5667 : : * EstimateTransactionStateSpace(). We emit the XIDs in sorted order for the
5668 : : * convenience of the receiving process.
5669 : : */
5670 : : void
4230 rhaas@postgresql.org 5671 : 683 : SerializeTransactionState(Size maxsize, char *start_address)
5672 : : {
5673 : : TransactionState s;
4207 bruce@momjian.us 5674 : 683 : Size nxids = 0;
5675 : 683 : Size i = 0;
5676 : : TransactionId *workspace;
5677 : : SerializedTransactionState *result;
5678 : :
2802 tmunro@postgresql.or 5679 : 683 : result = (SerializedTransactionState *) start_address;
5680 : :
5681 : 683 : result->xactIsoLevel = XactIsoLevel;
5682 : 683 : result->xactDeferrable = XactDeferrable;
5683 : 683 : result->topFullTransactionId = XactTopFullTransactionId;
5684 : 683 : result->currentFullTransactionId =
5685 : 683 : CurrentTransactionState->fullTransactionId;
5686 : 683 : result->currentCommandId = currentCommandId;
5687 : :
5688 : : /*
5689 : : * If we're running in a parallel worker and launching a parallel worker
5690 : : * of our own, we can just pass along the information that was passed to
5691 : : * us.
5692 : : */
4230 rhaas@postgresql.org 5693 [ - + ]: 683 : if (nParallelCurrentXids > 0)
5694 : : {
2802 tmunro@postgresql.or 5695 :UBC 0 : result->nParallelCurrentXids = nParallelCurrentXids;
1 tomas.vondra@postgre 5696 :UNC 0 : memcpy(result->parallelCurrentXids, ParallelCurrentXids,
5697 : : nParallelCurrentXids * sizeof(TransactionId));
4230 rhaas@postgresql.org 5698 :UBC 0 : return;
5699 : : }
5700 : :
5701 : : /*
5702 : : * OK, we need to generate a sorted list of XIDs that our workers should
5703 : : * view as current. First, figure out how many there are.
5704 : : */
4230 rhaas@postgresql.org 5705 [ + + ]:CBC 3058 : for (s = CurrentTransactionState; s != NULL; s = s->parent)
5706 : : {
2802 tmunro@postgresql.or 5707 [ + + ]: 2375 : if (FullTransactionIdIsValid(s->fullTransactionId))
4230 rhaas@postgresql.org 5708 : 1370 : nxids = add_size(nxids, 1);
5709 : 2375 : nxids = add_size(nxids, s->nChildXids);
5710 : : }
2802 tmunro@postgresql.or 5711 [ - + ]: 683 : Assert(SerializedTransactionStateHeaderSize + nxids * sizeof(TransactionId)
5712 : : <= maxsize);
5713 : :
5714 : : /* Copy them to our scratch space. */
103 michael@paquier.xyz 5715 :GNC 683 : workspace = palloc_array(TransactionId, nxids);
4230 rhaas@postgresql.org 5716 [ + + ]:CBC 3058 : for (s = CurrentTransactionState; s != NULL; s = s->parent)
5717 : : {
2802 tmunro@postgresql.or 5718 [ + + ]: 2375 : if (FullTransactionIdIsValid(s->fullTransactionId))
5719 : 1370 : workspace[i++] = XidFromFullTransactionId(s->fullTransactionId);
1731 tgl@sss.pgh.pa.us 5720 [ - + ]: 2375 : if (s->nChildXids > 0)
1731 tgl@sss.pgh.pa.us 5721 :UBC 0 : memcpy(&workspace[i], s->childXids,
5722 : 0 : s->nChildXids * sizeof(TransactionId));
4230 rhaas@postgresql.org 5723 :CBC 2375 : i += s->nChildXids;
5724 : : }
5725 [ - + ]: 683 : Assert(i == nxids);
5726 : :
5727 : : /* Sort them. */
5728 : 683 : qsort(workspace, nxids, sizeof(TransactionId), xidComparator);
5729 : :
5730 : : /* Copy data into output area. */
2802 tmunro@postgresql.or 5731 : 683 : result->nParallelCurrentXids = nxids;
1 tomas.vondra@postgre 5732 :GNC 683 : memcpy(result->parallelCurrentXids, workspace,
5733 : : nxids * sizeof(TransactionId));
5734 : : }
5735 : :
5736 : : /*
5737 : : * StartParallelWorkerTransaction
5738 : : * Start a parallel worker transaction, restoring the relevant
5739 : : * transaction state serialized by SerializeTransactionState.
5740 : : */
5741 : : void
4230 rhaas@postgresql.org 5742 :CBC 2049 : StartParallelWorkerTransaction(char *tstatespace)
5743 : : {
5744 : : SerializedTransactionState *tstate;
5745 : :
5746 [ - + ]: 2049 : Assert(CurrentTransactionState->blockState == TBLOCK_DEFAULT);
5747 : 2049 : StartTransaction();
5748 : :
2802 tmunro@postgresql.or 5749 : 2049 : tstate = (SerializedTransactionState *) tstatespace;
5750 : 2049 : XactIsoLevel = tstate->xactIsoLevel;
5751 : 2049 : XactDeferrable = tstate->xactDeferrable;
5752 : 2049 : XactTopFullTransactionId = tstate->topFullTransactionId;
5753 : 2049 : CurrentTransactionState->fullTransactionId =
5754 : : tstate->currentFullTransactionId;
5755 : 2049 : currentCommandId = tstate->currentCommandId;
5756 : 2049 : nParallelCurrentXids = tstate->nParallelCurrentXids;
1 tomas.vondra@postgre 5757 :GNC 2049 : ParallelCurrentXids = tstate->parallelCurrentXids;
5758 : :
4230 rhaas@postgresql.org 5759 :CBC 2049 : CurrentTransactionState->blockState = TBLOCK_PARALLEL_INPROGRESS;
5760 : 2049 : }
5761 : :
5762 : : /*
5763 : : * EndParallelWorkerTransaction
5764 : : * End a parallel worker transaction.
5765 : : */
5766 : : void
5767 : 2034 : EndParallelWorkerTransaction(void)
5768 : : {
5769 [ - + ]: 2034 : Assert(CurrentTransactionState->blockState == TBLOCK_PARALLEL_INPROGRESS);
5770 : 2034 : CommitTransaction();
5771 : 2034 : CurrentTransactionState->blockState = TBLOCK_DEFAULT;
5772 : 2034 : }
5773 : :
5774 : : /*
5775 : : * ShowTransactionState
5776 : : * Debug support
5777 : : */
5778 : : static void
8185 tgl@sss.pgh.pa.us 5779 : 899341 : ShowTransactionState(const char *str)
5780 : : {
5781 : : /* skip work if message will definitely not be printed */
2196 5782 [ - + ]: 899341 : if (message_level_is_interesting(DEBUG5))
3663 rhaas@postgresql.org 5783 :UBC 0 : ShowTransactionStateRec(str, CurrentTransactionState);
8185 tgl@sss.pgh.pa.us 5784 :CBC 899341 : }
5785 : :
5786 : : /*
5787 : : * ShowTransactionStateRec
5788 : : * Recursive subroutine for ShowTransactionState
5789 : : */
5790 : : static void
3663 rhaas@postgresql.org 5791 :UBC 0 : ShowTransactionStateRec(const char *str, TransactionState s)
5792 : : {
5793 : : StringInfoData buf;
5794 : :
995 akorotkov@postgresql 5795 [ # # ]: 0 : if (s->parent)
5796 : : {
5797 : : /*
5798 : : * Since this function recurses, it could be driven to stack overflow.
5799 : : * This is just a debugging aid, so we can leave out some details
5800 : : * instead of erroring out with check_stack_depth().
5801 : : */
5802 [ # # ]: 0 : if (stack_is_too_deep())
5803 [ # # ]: 0 : ereport(DEBUG5,
5804 : : (errmsg_internal("%s(%d): parent omitted to avoid stack overflow",
5805 : : str, s->nestingLevel)));
5806 : : else
5807 : 0 : ShowTransactionStateRec(str, s->parent);
5808 : : }
5809 : :
5810 : 0 : initStringInfo(&buf);
6830 tgl@sss.pgh.pa.us 5811 [ # # ]: 0 : if (s->nChildXids > 0)
5812 : : {
5813 : : int i;
5814 : :
3663 rhaas@postgresql.org 5815 : 0 : appendStringInfo(&buf, ", children: %u", s->childXids[0]);
6830 tgl@sss.pgh.pa.us 5816 [ # # ]: 0 : for (i = 1; i < s->nChildXids; i++)
5817 : 0 : appendStringInfo(&buf, " %u", s->childXids[i]);
5818 : : }
3663 rhaas@postgresql.org 5819 [ # # # # : 0 : ereport(DEBUG5,
# # ]
5820 : : (errmsg_internal("%s(%d) name: %s; blockState: %s; state: %s, xid/subid/cid: %u/%u/%u%s%s",
5821 : : str, s->nestingLevel,
5822 : : s->name ? s->name : "unnamed",
5823 : : BlockStateAsString(s->blockState),
5824 : : TransStateAsString(s->state),
5825 : : XidFromFullTransactionId(s->fullTransactionId),
5826 : : s->subTransactionId,
5827 : : currentCommandId,
5828 : : currentCommandIdUsed ? " (used)" : "",
5829 : : buf.data)));
6830 tgl@sss.pgh.pa.us 5830 : 0 : pfree(buf.data);
8185 5831 : 0 : }
5832 : :
5833 : : /*
5834 : : * BlockStateAsString
5835 : : * Debug support
5836 : : */
5837 : : static const char *
5838 : 0 : BlockStateAsString(TBlockState blockState)
5839 : : {
8159 5840 [ # # # # : 0 : switch (blockState)
# # # # #
# # # # #
# # # # #
# # ]
5841 : : {
8185 5842 : 0 : case TBLOCK_DEFAULT:
5843 : 0 : return "DEFAULT";
5844 : 0 : case TBLOCK_STARTED:
5845 : 0 : return "STARTED";
5846 : 0 : case TBLOCK_BEGIN:
5847 : 0 : return "BEGIN";
5848 : 0 : case TBLOCK_INPROGRESS:
5849 : 0 : return "INPROGRESS";
3369 5850 : 0 : case TBLOCK_IMPLICIT_INPROGRESS:
5851 : 0 : return "IMPLICIT_INPROGRESS";
4230 rhaas@postgresql.org 5852 : 0 : case TBLOCK_PARALLEL_INPROGRESS:
5853 : 0 : return "PARALLEL_INPROGRESS";
8185 tgl@sss.pgh.pa.us 5854 : 0 : case TBLOCK_END:
5855 : 0 : return "END";
5856 : 0 : case TBLOCK_ABORT:
5857 : 0 : return "ABORT";
8108 5858 : 0 : case TBLOCK_ABORT_END:
3206 peter_e@gmx.net 5859 : 0 : return "ABORT_END";
8108 tgl@sss.pgh.pa.us 5860 : 0 : case TBLOCK_ABORT_PENDING:
3206 peter_e@gmx.net 5861 : 0 : return "ABORT_PENDING";
7834 tgl@sss.pgh.pa.us 5862 : 0 : case TBLOCK_PREPARE:
5863 : 0 : return "PREPARE";
8185 5864 : 0 : case TBLOCK_SUBBEGIN:
3206 peter_e@gmx.net 5865 : 0 : return "SUBBEGIN";
8185 tgl@sss.pgh.pa.us 5866 : 0 : case TBLOCK_SUBINPROGRESS:
3206 peter_e@gmx.net 5867 : 0 : return "SUBINPROGRESS";
5611 simon@2ndQuadrant.co 5868 : 0 : case TBLOCK_SUBRELEASE:
3206 peter_e@gmx.net 5869 : 0 : return "SUBRELEASE";
5611 simon@2ndQuadrant.co 5870 : 0 : case TBLOCK_SUBCOMMIT:
3206 peter_e@gmx.net 5871 : 0 : return "SUBCOMMIT";
8185 tgl@sss.pgh.pa.us 5872 : 0 : case TBLOCK_SUBABORT:
3206 peter_e@gmx.net 5873 : 0 : return "SUBABORT";
8108 tgl@sss.pgh.pa.us 5874 : 0 : case TBLOCK_SUBABORT_END:
3206 peter_e@gmx.net 5875 : 0 : return "SUBABORT_END";
8159 tgl@sss.pgh.pa.us 5876 : 0 : case TBLOCK_SUBABORT_PENDING:
3206 peter_e@gmx.net 5877 : 0 : return "SUBABORT_PENDING";
8108 tgl@sss.pgh.pa.us 5878 : 0 : case TBLOCK_SUBRESTART:
3206 peter_e@gmx.net 5879 : 0 : return "SUBRESTART";
8108 tgl@sss.pgh.pa.us 5880 : 0 : case TBLOCK_SUBABORT_RESTART:
3206 peter_e@gmx.net 5881 : 0 : return "SUBABORT_RESTART";
5882 : : }
8185 tgl@sss.pgh.pa.us 5883 : 0 : return "UNRECOGNIZED";
5884 : : }
5885 : :
5886 : : /*
5887 : : * TransStateAsString
5888 : : * Debug support
5889 : : */
5890 : : static const char *
5891 : 0 : TransStateAsString(TransState state)
5892 : : {
8159 5893 [ # # # # : 0 : switch (state)
# # # ]
5894 : : {
8185 5895 : 0 : case TRANS_DEFAULT:
5896 : 0 : return "DEFAULT";
5897 : 0 : case TRANS_START:
5898 : 0 : return "START";
7834 5899 : 0 : case TRANS_INPROGRESS:
3206 peter_e@gmx.net 5900 : 0 : return "INPROGRESS";
8185 tgl@sss.pgh.pa.us 5901 : 0 : case TRANS_COMMIT:
5902 : 0 : return "COMMIT";
5903 : 0 : case TRANS_ABORT:
5904 : 0 : return "ABORT";
7834 5905 : 0 : case TRANS_PREPARE:
5906 : 0 : return "PREPARE";
5907 : : }
8185 5908 : 0 : return "UNRECOGNIZED";
5909 : : }
5910 : :
5911 : : /*
5912 : : * xactGetCommittedChildren
5913 : : *
5914 : : * Gets the list of committed children of the current transaction. The return
5915 : : * value is the number of child transactions. *ptr is set to point to an
5916 : : * array of TransactionIds. The array is allocated in TopTransactionContext;
5917 : : * the caller should *not* pfree() it (this is a change from pre-8.4 code!).
5918 : : * If there are no subxacts, *ptr is set to NULL.
5919 : : */
5920 : : int
8169 tgl@sss.pgh.pa.us 5921 :CBC 412984 : xactGetCommittedChildren(TransactionId **ptr)
5922 : : {
8126 bruce@momjian.us 5923 : 412984 : TransactionState s = CurrentTransactionState;
5924 : :
6830 tgl@sss.pgh.pa.us 5925 [ + + ]: 412984 : if (s->nChildXids == 0)
8185 5926 : 412357 : *ptr = NULL;
5927 : : else
6830 5928 : 627 : *ptr = s->childXids;
5929 : :
5930 : 412984 : return s->nChildXids;
5931 : : }
5932 : :
5933 : : /*
5934 : : * XLOG support routines
5935 : : */
5936 : :
5937 : :
5938 : : /*
5939 : : * Log the commit record for a plain or twophase transaction commit.
5940 : : *
5941 : : * A 2pc commit will be emitted when twophase_xid is valid, a plain one
5942 : : * otherwise.
5943 : : */
5944 : : XLogRecPtr
4276 andres@anarazel.de 5945 : 161716 : XactLogCommitRecord(TimestampTz commit_time,
5946 : : int nsubxacts, TransactionId *subxacts,
5947 : : int nrels, RelFileLocator *rels,
5948 : : int ndroppedstats, xl_xact_stats_item *droppedstats,
5949 : : int nmsgs, SharedInvalidationMessage *msgs,
5950 : : bool relcacheInval,
5951 : : int xactflags, TransactionId twophase_xid,
5952 : : const char *twophase_gid)
5953 : : {
5954 : : xl_xact_commit xlrec;
5955 : : xl_xact_xinfo xl_xinfo;
5956 : : xl_xact_dbinfo xl_dbinfo;
5957 : : xl_xact_subxacts xl_subxacts;
5958 : : xl_xact_relfilelocators xl_relfilelocators;
5959 : : xl_xact_stats_items xl_dropped_stats;
5960 : : xl_xact_invals xl_invals;
5961 : : xl_xact_twophase xl_twophase;
5962 : : xl_xact_origin xl_origin;
5963 : : uint8 info;
5964 : :
5965 [ - + ]: 161716 : Assert(CritSectionCount > 0);
5966 : :
5967 : 161716 : xl_xinfo.xinfo = 0;
5968 : :
5969 : : /* decide between a plain and 2pc commit */
5970 [ + + ]: 161716 : if (!TransactionIdIsValid(twophase_xid))
5971 : 161452 : info = XLOG_XACT_COMMIT;
5972 : : else
5973 : 264 : info = XLOG_XACT_COMMIT_PREPARED;
5974 : :
5975 : : /* First figure out and collect all the information needed */
5976 : :
5977 : 161716 : xlrec.xact_time = commit_time;
5978 : :
5979 [ + + ]: 161716 : if (relcacheInval)
5980 : 4792 : xl_xinfo.xinfo |= XACT_COMPLETION_UPDATE_RELCACHE_FILE;
5981 [ + + ]: 161716 : if (forceSyncCommit)
5982 : 624 : xl_xinfo.xinfo |= XACT_COMPLETION_FORCE_SYNC_COMMIT;
3538 simon@2ndQuadrant.co 5983 [ + + ]: 161716 : if ((xactflags & XACT_FLAGS_ACQUIREDACCESSEXCLUSIVELOCK))
5984 : 66165 : xl_xinfo.xinfo |= XACT_XINFO_HAS_AE_LOCKS;
5985 : :
5986 : : /*
5987 : : * Check if the caller would like to ask standbys for immediate feedback
5988 : : * once this commit is applied.
5989 : : */
3896 rhaas@postgresql.org 5990 [ + + ]: 161716 : if (synchronous_commit >= SYNCHRONOUS_COMMIT_REMOTE_APPLY)
5991 : 3 : xl_xinfo.xinfo |= XACT_COMPLETION_APPLY_FEEDBACK;
5992 : :
5993 : : /*
5994 : : * Relcache invalidations requires information about the current database
5995 : : * and so does logical decoding.
5996 : : */
4276 andres@anarazel.de 5997 [ + + + + : 161716 : if (nmsgs > 0 || XLogLogicalInfoActive())
+ + ]
5998 : : {
5999 : 116719 : xl_xinfo.xinfo |= XACT_XINFO_HAS_DBINFO;
6000 : 116719 : xl_dbinfo.dbId = MyDatabaseId;
6001 : 116719 : xl_dbinfo.tsId = MyDatabaseTableSpace;
6002 : : }
6003 : :
6004 [ + + ]: 161716 : if (nsubxacts > 0)
6005 : : {
6006 : 521 : xl_xinfo.xinfo |= XACT_XINFO_HAS_SUBXACTS;
6007 : 521 : xl_subxacts.nsubxacts = nsubxacts;
6008 : : }
6009 : :
6010 [ + + ]: 161716 : if (nrels > 0)
6011 : : {
1606 rhaas@postgresql.org 6012 : 13060 : xl_xinfo.xinfo |= XACT_XINFO_HAS_RELFILELOCATORS;
6013 : 13060 : xl_relfilelocators.nrels = nrels;
2294 heikki.linnakangas@i 6014 : 13060 : info |= XLR_SPECIAL_REL_UPDATE;
6015 : : }
6016 : :
1697 andres@anarazel.de 6017 [ + + ]: 161716 : if (ndroppedstats > 0)
6018 : : {
6019 : 16156 : xl_xinfo.xinfo |= XACT_XINFO_HAS_DROPPED_STATS;
6020 : 16156 : xl_dropped_stats.nitems = ndroppedstats;
6021 : : }
6022 : :
4276 6023 [ + + ]: 161716 : if (nmsgs > 0)
6024 : : {
6025 : 115714 : xl_xinfo.xinfo |= XACT_XINFO_HAS_INVALS;
6026 : 115714 : xl_invals.nmsgs = nmsgs;
6027 : : }
6028 : :
6029 [ + + ]: 161716 : if (TransactionIdIsValid(twophase_xid))
6030 : : {
6031 : 264 : xl_xinfo.xinfo |= XACT_XINFO_HAS_TWOPHASE;
6032 : 264 : xl_twophase.xid = twophase_xid;
3167 simon@2ndQuadrant.co 6033 [ - + ]: 264 : Assert(twophase_gid != NULL);
6034 : :
6035 [ + + - + ]: 264 : if (XLogLogicalInfoActive())
6036 : 45 : xl_xinfo.xinfo |= XACT_XINFO_HAS_GID;
6037 : : }
6038 : :
6039 : : /* dump transaction origin information */
304 msawada@postgresql.o 6040 [ + + ]: 161716 : if (replorigin_xact_state.origin != InvalidReplOriginId)
6041 : : {
4231 andres@anarazel.de 6042 : 1143 : xl_xinfo.xinfo |= XACT_XINFO_HAS_ORIGIN;
6043 : :
304 msawada@postgresql.o 6044 : 1143 : xl_origin.origin_lsn = replorigin_xact_state.origin_lsn;
6045 : 1143 : xl_origin.origin_timestamp = replorigin_xact_state.origin_timestamp;
6046 : : }
6047 : :
4276 andres@anarazel.de 6048 [ + + ]: 161716 : if (xl_xinfo.xinfo != 0)
6049 : 119929 : info |= XLOG_XACT_HAS_INFO;
6050 : :
6051 : : /* Then include all the collected data into the commit record. */
6052 : :
6053 : 161716 : XLogBeginInsert();
6054 : :
655 peter@eisentraut.org 6055 : 161716 : XLogRegisterData(&xlrec, sizeof(xl_xact_commit));
6056 : :
4276 andres@anarazel.de 6057 [ + + ]: 161716 : if (xl_xinfo.xinfo != 0)
655 peter@eisentraut.org 6058 : 119929 : XLogRegisterData(&xl_xinfo.xinfo, sizeof(xl_xinfo.xinfo));
6059 : :
4276 andres@anarazel.de 6060 [ + + ]: 161716 : if (xl_xinfo.xinfo & XACT_XINFO_HAS_DBINFO)
655 peter@eisentraut.org 6061 : 116719 : XLogRegisterData(&xl_dbinfo, sizeof(xl_dbinfo));
6062 : :
4276 andres@anarazel.de 6063 [ + + ]: 161716 : if (xl_xinfo.xinfo & XACT_XINFO_HAS_SUBXACTS)
6064 : : {
655 peter@eisentraut.org 6065 : 521 : XLogRegisterData(&xl_subxacts,
6066 : : MinSizeOfXactSubxacts);
6067 : 521 : XLogRegisterData(subxacts,
6068 : : nsubxacts * sizeof(TransactionId));
6069 : : }
6070 : :
1606 rhaas@postgresql.org 6071 [ + + ]: 161716 : if (xl_xinfo.xinfo & XACT_XINFO_HAS_RELFILELOCATORS)
6072 : : {
655 peter@eisentraut.org 6073 : 13060 : XLogRegisterData(&xl_relfilelocators,
6074 : : MinSizeOfXactRelfileLocators);
6075 : 13060 : XLogRegisterData(rels,
6076 : : nrels * sizeof(RelFileLocator));
6077 : : }
6078 : :
1697 andres@anarazel.de 6079 [ + + ]: 161716 : if (xl_xinfo.xinfo & XACT_XINFO_HAS_DROPPED_STATS)
6080 : : {
655 peter@eisentraut.org 6081 : 16156 : XLogRegisterData(&xl_dropped_stats,
6082 : : MinSizeOfXactStatsItems);
6083 : 16156 : XLogRegisterData(droppedstats,
6084 : : ndroppedstats * sizeof(xl_xact_stats_item));
6085 : : }
6086 : :
4276 andres@anarazel.de 6087 [ + + ]: 161716 : if (xl_xinfo.xinfo & XACT_XINFO_HAS_INVALS)
6088 : : {
655 peter@eisentraut.org 6089 : 115714 : XLogRegisterData(&xl_invals, MinSizeOfXactInvals);
6090 : 115714 : XLogRegisterData(msgs,
6091 : : nmsgs * sizeof(SharedInvalidationMessage));
6092 : : }
6093 : :
4276 andres@anarazel.de 6094 [ + + ]: 161716 : if (xl_xinfo.xinfo & XACT_XINFO_HAS_TWOPHASE)
6095 : : {
655 peter@eisentraut.org 6096 : 264 : XLogRegisterData(&xl_twophase, sizeof(xl_xact_twophase));
3167 simon@2ndQuadrant.co 6097 [ + + ]: 264 : if (xl_xinfo.xinfo & XACT_XINFO_HAS_GID)
816 peter@eisentraut.org 6098 : 45 : XLogRegisterData(twophase_gid, strlen(twophase_gid) + 1);
6099 : : }
6100 : :
4231 andres@anarazel.de 6101 [ + + ]: 161716 : if (xl_xinfo.xinfo & XACT_XINFO_HAS_ORIGIN)
655 peter@eisentraut.org 6102 : 1143 : XLogRegisterData(&xl_origin, sizeof(xl_xact_origin));
6103 : :
6104 : : /* we allow filtering by xacts */
3628 andres@anarazel.de 6105 : 161716 : XLogSetRecordFlags(XLOG_INCLUDE_ORIGIN);
6106 : :
4276 6107 : 161716 : return XLogInsert(RM_XACT_ID, info);
6108 : : }
6109 : :
6110 : : /*
6111 : : * Log the commit record for a plain or twophase transaction abort.
6112 : : *
6113 : : * A 2pc abort will be emitted when twophase_xid is valid, a plain one
6114 : : * otherwise.
6115 : : */
6116 : : XLogRecPtr
6117 : 10147 : XactLogAbortRecord(TimestampTz abort_time,
6118 : : int nsubxacts, TransactionId *subxacts,
6119 : : int nrels, RelFileLocator *rels,
6120 : : int ndroppedstats, xl_xact_stats_item *droppedstats,
6121 : : int xactflags, TransactionId twophase_xid,
6122 : : const char *twophase_gid)
6123 : : {
6124 : : xl_xact_abort xlrec;
6125 : : xl_xact_xinfo xl_xinfo;
6126 : : xl_xact_subxacts xl_subxacts;
6127 : : xl_xact_relfilelocators xl_relfilelocators;
6128 : : xl_xact_stats_items xl_dropped_stats;
6129 : : xl_xact_twophase xl_twophase;
6130 : : xl_xact_dbinfo xl_dbinfo;
6131 : : xl_xact_origin xl_origin;
6132 : :
6133 : : uint8 info;
6134 : :
6135 [ - + ]: 10147 : Assert(CritSectionCount > 0);
6136 : :
6137 : 10147 : xl_xinfo.xinfo = 0;
6138 : :
6139 : : /* decide between a plain and 2pc abort */
6140 [ + + ]: 10147 : if (!TransactionIdIsValid(twophase_xid))
6141 : 10097 : info = XLOG_XACT_ABORT;
6142 : : else
6143 : 50 : info = XLOG_XACT_ABORT_PREPARED;
6144 : :
6145 : :
6146 : : /* First figure out and collect all the information needed */
6147 : :
6148 : 10147 : xlrec.xact_time = abort_time;
6149 : :
3538 simon@2ndQuadrant.co 6150 [ + + ]: 10147 : if ((xactflags & XACT_FLAGS_ACQUIREDACCESSEXCLUSIVELOCK))
6151 : 5660 : xl_xinfo.xinfo |= XACT_XINFO_HAS_AE_LOCKS;
6152 : :
4276 andres@anarazel.de 6153 [ + + ]: 10147 : if (nsubxacts > 0)
6154 : : {
6155 : 110 : xl_xinfo.xinfo |= XACT_XINFO_HAS_SUBXACTS;
6156 : 110 : xl_subxacts.nsubxacts = nsubxacts;
6157 : : }
6158 : :
6159 [ + + ]: 10147 : if (nrels > 0)
6160 : : {
1606 rhaas@postgresql.org 6161 : 1559 : xl_xinfo.xinfo |= XACT_XINFO_HAS_RELFILELOCATORS;
6162 : 1559 : xl_relfilelocators.nrels = nrels;
2294 heikki.linnakangas@i 6163 : 1559 : info |= XLR_SPECIAL_REL_UPDATE;
6164 : : }
6165 : :
1697 andres@anarazel.de 6166 [ + + ]: 10147 : if (ndroppedstats > 0)
6167 : : {
6168 : 2137 : xl_xinfo.xinfo |= XACT_XINFO_HAS_DROPPED_STATS;
6169 : 2137 : xl_dropped_stats.nitems = ndroppedstats;
6170 : : }
6171 : :
4276 6172 [ + + ]: 10147 : if (TransactionIdIsValid(twophase_xid))
6173 : : {
6174 : 50 : xl_xinfo.xinfo |= XACT_XINFO_HAS_TWOPHASE;
6175 : 50 : xl_twophase.xid = twophase_xid;
3167 simon@2ndQuadrant.co 6176 [ - + ]: 50 : Assert(twophase_gid != NULL);
6177 : :
6178 [ + + - + ]: 50 : if (XLogLogicalInfoActive())
6179 : 15 : xl_xinfo.xinfo |= XACT_XINFO_HAS_GID;
6180 : : }
6181 : :
6182 [ + + + + : 10147 : if (TransactionIdIsValid(twophase_xid) && XLogLogicalInfoActive())
- + ]
6183 : : {
6184 : 15 : xl_xinfo.xinfo |= XACT_XINFO_HAS_DBINFO;
6185 : 15 : xl_dbinfo.dbId = MyDatabaseId;
6186 : 15 : xl_dbinfo.tsId = MyDatabaseTableSpace;
6187 : : }
6188 : :
6189 : : /*
6190 : : * Dump transaction origin information. We need this during recovery to
6191 : : * update the replication origin progress.
6192 : : */
304 msawada@postgresql.o 6193 [ + + ]: 10147 : if (replorigin_xact_state.origin != InvalidReplOriginId)
6194 : : {
3167 simon@2ndQuadrant.co 6195 : 27 : xl_xinfo.xinfo |= XACT_XINFO_HAS_ORIGIN;
6196 : :
304 msawada@postgresql.o 6197 : 27 : xl_origin.origin_lsn = replorigin_xact_state.origin_lsn;
6198 : 27 : xl_origin.origin_timestamp = replorigin_xact_state.origin_timestamp;
6199 : : }
6200 : :
4276 andres@anarazel.de 6201 [ + + ]: 10147 : if (xl_xinfo.xinfo != 0)
6202 : 5917 : info |= XLOG_XACT_HAS_INFO;
6203 : :
6204 : : /* Then include all the collected data into the abort record. */
6205 : :
6206 : 10147 : XLogBeginInsert();
6207 : :
655 peter@eisentraut.org 6208 : 10147 : XLogRegisterData(&xlrec, MinSizeOfXactAbort);
6209 : :
4276 andres@anarazel.de 6210 [ + + ]: 10147 : if (xl_xinfo.xinfo != 0)
655 peter@eisentraut.org 6211 : 5917 : XLogRegisterData(&xl_xinfo, sizeof(xl_xinfo));
6212 : :
3167 simon@2ndQuadrant.co 6213 [ + + ]: 10147 : if (xl_xinfo.xinfo & XACT_XINFO_HAS_DBINFO)
655 peter@eisentraut.org 6214 : 15 : XLogRegisterData(&xl_dbinfo, sizeof(xl_dbinfo));
6215 : :
4276 andres@anarazel.de 6216 [ + + ]: 10147 : if (xl_xinfo.xinfo & XACT_XINFO_HAS_SUBXACTS)
6217 : : {
655 peter@eisentraut.org 6218 : 110 : XLogRegisterData(&xl_subxacts,
6219 : : MinSizeOfXactSubxacts);
6220 : 110 : XLogRegisterData(subxacts,
6221 : : nsubxacts * sizeof(TransactionId));
6222 : : }
6223 : :
1606 rhaas@postgresql.org 6224 [ + + ]: 10147 : if (xl_xinfo.xinfo & XACT_XINFO_HAS_RELFILELOCATORS)
6225 : : {
655 peter@eisentraut.org 6226 : 1559 : XLogRegisterData(&xl_relfilelocators,
6227 : : MinSizeOfXactRelfileLocators);
6228 : 1559 : XLogRegisterData(rels,
6229 : : nrels * sizeof(RelFileLocator));
6230 : : }
6231 : :
1697 andres@anarazel.de 6232 [ + + ]: 10147 : if (xl_xinfo.xinfo & XACT_XINFO_HAS_DROPPED_STATS)
6233 : : {
655 peter@eisentraut.org 6234 : 2137 : XLogRegisterData(&xl_dropped_stats,
6235 : : MinSizeOfXactStatsItems);
6236 : 2137 : XLogRegisterData(droppedstats,
6237 : : ndroppedstats * sizeof(xl_xact_stats_item));
6238 : : }
6239 : :
4276 andres@anarazel.de 6240 [ + + ]: 10147 : if (xl_xinfo.xinfo & XACT_XINFO_HAS_TWOPHASE)
6241 : : {
655 peter@eisentraut.org 6242 : 50 : XLogRegisterData(&xl_twophase, sizeof(xl_xact_twophase));
3167 simon@2ndQuadrant.co 6243 [ + + ]: 50 : if (xl_xinfo.xinfo & XACT_XINFO_HAS_GID)
816 peter@eisentraut.org 6244 : 15 : XLogRegisterData(twophase_gid, strlen(twophase_gid) + 1);
6245 : : }
6246 : :
3167 simon@2ndQuadrant.co 6247 [ + + ]: 10147 : if (xl_xinfo.xinfo & XACT_XINFO_HAS_ORIGIN)
655 peter@eisentraut.org 6248 : 27 : XLogRegisterData(&xl_origin, sizeof(xl_xact_origin));
6249 : :
6250 : : /* Include the replication origin */
1419 akapila@postgresql.o 6251 : 10147 : XLogSetRecordFlags(XLOG_INCLUDE_ORIGIN);
6252 : :
4276 andres@anarazel.de 6253 : 10147 : return XLogInsert(RM_XACT_ID, info);
6254 : : }
6255 : :
6256 : : /*
6257 : : * Before 9.0 this was a fairly short function, but now it performs many
6258 : : * actions for which the order of execution is critical.
6259 : : */
6260 : : static void
6261 : 24627 : xact_redo_commit(xl_xact_parsed_commit *parsed,
6262 : : TransactionId xid,
6263 : : XLogRecPtr lsn,
6264 : : ReplOriginId origin_id)
6265 : : {
6266 : : TransactionId max_xid;
6267 : : TimestampTz commit_time;
6268 : :
3454 alvherre@alvh.no-ip. 6269 [ - + ]: 24627 : Assert(TransactionIdIsValid(xid));
6270 : :
4276 andres@anarazel.de 6271 : 24627 : max_xid = TransactionIdLatest(xid, parsed->nsubxacts, parsed->subxacts);
6272 : :
6273 : : /* Make sure nextXid is beyond any XID mentioned in the record. */
2802 tmunro@postgresql.or 6274 : 24627 : AdvanceNextFullTransactionIdPastXid(max_xid);
6275 : :
3898 andres@anarazel.de 6276 [ - + ]: 24627 : Assert(((parsed->xinfo & XACT_XINFO_HAS_ORIGIN) == 0) ==
6277 : : (origin_id == InvalidReplOriginId));
6278 : :
4231 6279 [ + + ]: 24627 : if (parsed->xinfo & XACT_XINFO_HAS_ORIGIN)
6280 : 20 : commit_time = parsed->origin_timestamp;
6281 : : else
6282 : 24607 : commit_time = parsed->xact_time;
6283 : :
6284 : : /* Set the transaction commit timestamp and metadata */
4276 6285 : 24627 : TransactionTreeSetCommitTsData(xid, parsed->nsubxacts, parsed->subxacts,
6286 : : commit_time, origin_id);
6287 : :
6043 simon@2ndQuadrant.co 6288 [ + + ]: 24627 : if (standbyState == STANDBY_DISABLED)
6289 : : {
6290 : : /*
6291 : : * Mark the transaction committed in pg_xact. We use the async commit
6292 : : * protocol during recovery to ensure that minRecoveryPoint is
6293 : : * advanced before the CLOG is written. This ensures that if we crash,
6294 : : * we don't see the committed status set for transactions that haven't
6295 : : * yet recovered.
6296 : : */
10 jdavis@postgresql.or 6297 : 2233 : TransactionIdAsyncCommitTree(xid, parsed->nsubxacts, parsed->subxacts, lsn);
6298 : : }
6299 : : else
6300 : : {
6301 : : /*
6302 : : * If a transaction completion record arrives that has as-yet
6303 : : * unobserved subtransactions then this will not have been fully
6304 : : * handled by the call to RecordKnownAssignedTransactionIds() in the
6305 : : * main recovery loop in PerformWalRecovery(). So we need to do
6306 : : * bookkeeping again to cover that case. This is confusing and it is
6307 : : * easy to think this call is irrelevant, which has happened three
6308 : : * times in development already. Leave it in.
6309 : : */
6188 simon@2ndQuadrant.co 6310 : 22394 : RecordKnownAssignedTransactionIds(max_xid);
6311 : :
6312 : : /*
6313 : : * Hot standby also needs the commit LSN so that readers can safely
6314 : : * set hint bits.
6315 : : */
2494 alvherre@alvh.no-ip. 6316 : 22394 : TransactionIdAsyncCommitTree(xid, parsed->nsubxacts, parsed->subxacts, lsn);
6317 : :
6318 : : /*
6319 : : * We must mark clog before we update the ProcArray.
6320 : : */
6321 : 22394 : ExpireTreeKnownAssignedTransactionIds(xid, parsed->nsubxacts, parsed->subxacts, max_xid);
6322 : :
6323 : : /*
6324 : : * Send any cache invalidations attached to the commit. We must
6325 : : * maintain the same order of invalidation then release locks as
6326 : : * occurs in CommitTransaction().
6327 : : */
6328 : 22394 : ProcessCommittedInvalidationMessages(parsed->msgs, parsed->nmsgs,
3447 tgl@sss.pgh.pa.us 6329 : 22394 : XactCompletionRelcacheInitFileInval(parsed->xinfo),
6330 : : parsed->dbId, parsed->tsId);
6331 : :
6332 : : /*
6333 : : * Release locks, if any. We do this for both two phase and normal one
6334 : : * phase transactions. In effect we are ignoring the prepare phase and
6335 : : * just going straight to lock release.
6336 : : */
3538 simon@2ndQuadrant.co 6337 [ + + ]: 22394 : if (parsed->xinfo & XACT_XINFO_HAS_AE_LOCKS)
3087 6338 : 10980 : StandbyReleaseLockTree(xid, parsed->nsubxacts, parsed->subxacts);
6339 : : }
6340 : :
4231 andres@anarazel.de 6341 [ + + ]: 24627 : if (parsed->xinfo & XACT_XINFO_HAS_ORIGIN)
6342 : : {
6343 : : /* recover apply progress */
6344 : 20 : replorigin_advance(origin_id, parsed->origin_lsn, lsn,
6345 : : false /* backward */ , false /* WAL */ );
6346 : : }
6347 : :
6348 : : /* Make sure files supposed to be dropped are dropped */
4276 6349 [ + + ]: 24627 : if (parsed->nrels > 0)
6350 : : {
6351 : : /*
6352 : : * First update minimum recovery point to cover this WAL record. Once
6353 : : * a relation is deleted, there's no going back. The buffer manager
6354 : : * enforces the WAL-first rule for normal updates to relation files,
6355 : : * so that the minimum recovery point is always updated before the
6356 : : * corresponding change in the data file is flushed to disk, but we
6357 : : * have to do the same here since we're bypassing the buffer manager.
6358 : : *
6359 : : * Doing this before deleting the files means that if a deletion fails
6360 : : * for some reason, you cannot start up the system even after restart,
6361 : : * until you fix the underlying situation so that the deletion will
6362 : : * succeed. Alternatively, we could update the minimum recovery point
6363 : : * after deletion, but that would leave a small window where the
6364 : : * WAL-first rule would be violated.
6365 : : */
5101 heikki.linnakangas@i 6366 : 2406 : XLogFlush(lsn);
6367 : :
6368 : : /* Make sure files supposed to be dropped are dropped */
1606 rhaas@postgresql.org 6369 : 2406 : DropRelationFiles(parsed->xlocators, parsed->nrels, true);
6370 : : }
6371 : :
1697 andres@anarazel.de 6372 [ + + ]: 24627 : if (parsed->nstats > 0)
6373 : : {
6374 : : /* see equivalent call for relations above */
6375 : 3229 : XLogFlush(lsn);
6376 : :
29 nathan@postgresql.or 6377 :GNC 3229 : pgstat_execute_transactional_drops(parsed->nstats, parsed->stats);
6378 : : }
6379 : :
6380 : : /*
6381 : : * We issue an XLogFlush() for the same reason we emit ForceSyncCommit()
6382 : : * in normal operation. For example, in CREATE DATABASE, we copy all files
6383 : : * from the template database, and then commit the transaction. If we
6384 : : * crash after all the files have been copied but before the commit, you
6385 : : * have files in the data directory without an entry in pg_database. To
6386 : : * minimize the window for that, we use ForceSyncCommit() to rush the
6387 : : * commit record to disk as quick as possible. We have the same window
6388 : : * during recovery, and forcing an XLogFlush() (which updates
6389 : : * minRecoveryPoint during recovery) helps to reduce that problem window,
6390 : : * for any user that requested ForceSyncCommit().
6391 : : */
4276 andres@anarazel.de 6392 [ + + ]:CBC 24627 : if (XactCompletionForceSyncCommit(parsed->xinfo))
6188 simon@2ndQuadrant.co 6393 : 50 : XLogFlush(lsn);
6394 : :
6395 : : /*
6396 : : * If asked by the primary (because someone is waiting for a synchronous
6397 : : * commit = remote_apply), we will need to ask walreceiver to send a reply
6398 : : * immediately.
6399 : : */
3896 rhaas@postgresql.org 6400 [ + + ]: 24627 : if (XactCompletionApplyFeedback(parsed->xinfo))
6401 : 3 : XLogRequestWalReceiverReply();
5632 simon@2ndQuadrant.co 6402 : 24627 : }
6403 : :
6404 : : /*
6405 : : * Be careful with the order of execution, as with xact_redo_commit().
6406 : : * The two functions are similar but differ in key places.
6407 : : *
6408 : : * Note also that an abort can be for a subtransaction and its children,
6409 : : * not just for a top level abort. That means we have to consider
6410 : : * topxid != xid, whereas in commit we would find topxid == xid always
6411 : : * because subtransaction commit is never WAL logged.
6412 : : */
6413 : : static void
2091 akapila@postgresql.o 6414 : 2186 : xact_redo_abort(xl_xact_parsed_abort *parsed, TransactionId xid,
6415 : : XLogRecPtr lsn, ReplOriginId origin_id)
6416 : : {
6417 : : TransactionId max_xid;
6418 : :
3454 alvherre@alvh.no-ip. 6419 [ - + ]: 2186 : Assert(TransactionIdIsValid(xid));
6420 : :
6421 : : /* Make sure nextXid is beyond any XID mentioned in the record. */
4276 andres@anarazel.de 6422 : 2186 : max_xid = TransactionIdLatest(xid,
6423 : : parsed->nsubxacts,
6424 : 2186 : parsed->subxacts);
2802 tmunro@postgresql.or 6425 : 2186 : AdvanceNextFullTransactionIdPastXid(max_xid);
6426 : :
6043 simon@2ndQuadrant.co 6427 [ + + ]: 2186 : if (standbyState == STANDBY_DISABLED)
6428 : : {
6429 : : /* Mark the transaction aborted in pg_xact, no need for async stuff */
4276 andres@anarazel.de 6430 : 20 : TransactionIdAbortTree(xid, parsed->nsubxacts, parsed->subxacts);
6431 : : }
6432 : : else
6433 : : {
6434 : : /*
6435 : : * If a transaction completion record arrives that has as-yet
6436 : : * unobserved subtransactions then this will not have been fully
6437 : : * handled by the call to RecordKnownAssignedTransactionIds() in the
6438 : : * main recovery loop in PerformWalRecovery(). So we need to do
6439 : : * bookkeeping again to cover that case. This is confusing and it is
6440 : : * easy to think this call is irrelevant, which has happened three
6441 : : * times in development already. Leave it in.
6442 : : */
6188 simon@2ndQuadrant.co 6443 : 2166 : RecordKnownAssignedTransactionIds(max_xid);
6444 : :
6445 : : /* Mark the transaction aborted in pg_xact, no need for async stuff */
4276 andres@anarazel.de 6446 : 2166 : TransactionIdAbortTree(xid, parsed->nsubxacts, parsed->subxacts);
6447 : :
6448 : : /*
6449 : : * We must update the ProcArray after we have marked clog.
6450 : : */
2494 alvherre@alvh.no-ip. 6451 : 2166 : ExpireTreeKnownAssignedTransactionIds(xid, parsed->nsubxacts, parsed->subxacts, max_xid);
6452 : :
6453 : : /*
6454 : : * There are no invalidation messages to send or undo.
6455 : : */
6456 : :
6457 : : /*
6458 : : * Release locks, if any. There are no invalidations to send.
6459 : : */
3538 simon@2ndQuadrant.co 6460 [ + + ]: 2166 : if (parsed->xinfo & XACT_XINFO_HAS_AE_LOCKS)
6461 : 1363 : StandbyReleaseLockTree(xid, parsed->nsubxacts, parsed->subxacts);
6462 : : }
6463 : :
2091 akapila@postgresql.o 6464 [ + + ]: 2186 : if (parsed->xinfo & XACT_XINFO_HAS_ORIGIN)
6465 : : {
6466 : : /* recover apply progress */
6467 : 5 : replorigin_advance(origin_id, parsed->origin_lsn, lsn,
6468 : : false /* backward */ , false /* WAL */ );
6469 : : }
6470 : :
6471 : : /* Make sure files supposed to be dropped are dropped */
1948 fujii@postgresql.org 6472 [ + + ]: 2186 : if (parsed->nrels > 0)
6473 : : {
6474 : : /*
6475 : : * See comments about update of minimum recovery point on truncation,
6476 : : * in xact_redo_commit().
6477 : : */
6478 : 381 : XLogFlush(lsn);
6479 : :
1606 rhaas@postgresql.org 6480 : 381 : DropRelationFiles(parsed->xlocators, parsed->nrels, true);
6481 : : }
6482 : :
1697 andres@anarazel.de 6483 [ + + ]: 2186 : if (parsed->nstats > 0)
6484 : : {
6485 : : /* see equivalent call for relations above */
6486 : 507 : XLogFlush(lsn);
6487 : :
29 nathan@postgresql.or 6488 :GNC 507 : pgstat_execute_transactional_drops(parsed->nstats, parsed->stats);
6489 : : }
7834 tgl@sss.pgh.pa.us 6490 :CBC 2186 : }
6491 : :
6492 : : void
4391 heikki.linnakangas@i 6493 : 27210 : xact_redo(XLogReaderState *record)
6494 : : {
4276 andres@anarazel.de 6495 : 27210 : uint8 info = XLogRecGetInfo(record) & XLOG_XACT_OPMASK;
6496 : :
6497 : : /* Backup blocks are not used in xact records */
4391 heikki.linnakangas@i 6498 [ - + ]: 27210 : Assert(!XLogRecHasAnyBlockRefs(record));
6499 : :
3454 alvherre@alvh.no-ip. 6500 [ + + ]: 27210 : if (info == XLOG_XACT_COMMIT)
6501 : : {
8326 tgl@sss.pgh.pa.us 6502 : 24581 : xl_xact_commit *xlrec = (xl_xact_commit *) XLogRecGetData(record);
6503 : : xl_xact_parsed_commit parsed;
6504 : :
3454 alvherre@alvh.no-ip. 6505 : 24581 : ParseCommitRecord(XLogRecGetInfo(record), xlrec, &parsed);
6506 : 24581 : xact_redo_commit(&parsed, XLogRecGetXid(record),
6507 : 24581 : record->EndRecPtr, XLogRecGetOrigin(record));
6508 : : }
6509 [ + + ]: 2629 : else if (info == XLOG_XACT_COMMIT_PREPARED)
6510 : : {
6511 : 46 : xl_xact_commit *xlrec = (xl_xact_commit *) XLogRecGetData(record);
6512 : : xl_xact_parsed_commit parsed;
6513 : :
6514 : 46 : ParseCommitRecord(XLogRecGetInfo(record), xlrec, &parsed);
6515 : 46 : xact_redo_commit(&parsed, parsed.twophase_xid,
6516 : 46 : record->EndRecPtr, XLogRecGetOrigin(record));
6517 : :
6518 : : /* Delete TwoPhaseState gxact entry and/or 2PC file. */
6519 : 46 : LWLockAcquire(TwoPhaseStateLock, LW_EXCLUSIVE);
6520 : 46 : PrepareRedoRemove(parsed.twophase_xid, false);
6521 : 46 : LWLockRelease(TwoPhaseStateLock);
6522 : : }
6523 [ + + ]: 2583 : else if (info == XLOG_XACT_ABORT)
6524 : : {
7834 tgl@sss.pgh.pa.us 6525 : 2161 : xl_xact_abort *xlrec = (xl_xact_abort *) XLogRecGetData(record);
6526 : : xl_xact_parsed_abort parsed;
6527 : :
3454 alvherre@alvh.no-ip. 6528 : 2161 : ParseAbortRecord(XLogRecGetInfo(record), xlrec, &parsed);
2091 akapila@postgresql.o 6529 : 2161 : xact_redo_abort(&parsed, XLogRecGetXid(record),
6530 : 2161 : record->EndRecPtr, XLogRecGetOrigin(record));
6531 : : }
3454 alvherre@alvh.no-ip. 6532 [ + + ]: 422 : else if (info == XLOG_XACT_ABORT_PREPARED)
6533 : : {
6534 : 25 : xl_xact_abort *xlrec = (xl_xact_abort *) XLogRecGetData(record);
6535 : : xl_xact_parsed_abort parsed;
6536 : :
6537 : 25 : ParseAbortRecord(XLogRecGetInfo(record), xlrec, &parsed);
2091 akapila@postgresql.o 6538 : 25 : xact_redo_abort(&parsed, parsed.twophase_xid,
6539 : 25 : record->EndRecPtr, XLogRecGetOrigin(record));
6540 : :
6541 : : /* Delete TwoPhaseState gxact entry and/or 2PC file. */
3454 alvherre@alvh.no-ip. 6542 : 25 : LWLockAcquire(TwoPhaseStateLock, LW_EXCLUSIVE);
6543 : 25 : PrepareRedoRemove(parsed.twophase_xid, false);
6544 : 25 : LWLockRelease(TwoPhaseStateLock);
6545 : : }
7834 tgl@sss.pgh.pa.us 6546 [ + + ]: 397 : else if (info == XLOG_XACT_PREPARE)
6547 : : {
6548 : : /*
6549 : : * Store xid and start/end pointers of the WAL record in TwoPhaseState
6550 : : * gxact entry.
6551 : : */
3454 alvherre@alvh.no-ip. 6552 : 82 : LWLockAcquire(TwoPhaseStateLock, LW_EXCLUSIVE);
509 michael@paquier.xyz 6553 : 82 : PrepareRedoAdd(InvalidFullTransactionId,
6554 : 82 : XLogRecGetData(record),
6555 : : record->ReadRecPtr,
6556 : : record->EndRecPtr,
3167 simon@2ndQuadrant.co 6557 : 82 : XLogRecGetOrigin(record));
3454 alvherre@alvh.no-ip. 6558 : 82 : LWLockRelease(TwoPhaseStateLock);
6559 : : }
6188 simon@2ndQuadrant.co 6560 [ + + ]: 315 : else if (info == XLOG_XACT_ASSIGNMENT)
6561 : : {
6562 : 22 : xl_xact_assignment *xlrec = (xl_xact_assignment *) XLogRecGetData(record);
6563 : :
6043 6564 [ + - ]: 22 : if (standbyState >= STANDBY_INITIALIZED)
6188 6565 : 22 : ProcArrayApplyXidAssignment(xlrec->xtop,
6566 : 22 : xlrec->nsubxacts, xlrec->xsub);
6567 : : }
2319 akapila@postgresql.o 6568 [ - + ]: 293 : else if (info == XLOG_XACT_INVALIDATIONS)
6569 : : {
6570 : : /*
6571 : : * XXX we do ignore this for now, what matters are invalidations
6572 : : * written into the commit record.
6573 : : */
6574 : : }
6575 : : else
7834 tgl@sss.pgh.pa.us 6576 [ # # ]:UBC 0 : elog(PANIC, "xact_redo: unknown op code %u", info);
7834 tgl@sss.pgh.pa.us 6577 :CBC 27210 : }
|