Branch data Line data Source code
1 : : /*-------------------------------------------------------------------------
2 : : *
3 : : * postgres.c
4 : : * POSTGRES C Backend Interface
5 : : *
6 : : * Portions Copyright (c) 1996-2026, PostgreSQL Global Development Group
7 : : * Portions Copyright (c) 1994, Regents of the University of California
8 : : *
9 : : *
10 : : * IDENTIFICATION
11 : : * src/backend/tcop/postgres.c
12 : : *
13 : : * NOTES
14 : : * this is the "main" module of the postgres backend and
15 : : * hence the main module of the "traffic cop".
16 : : *
17 : : *-------------------------------------------------------------------------
18 : : */
19 : :
20 : : #include "postgres.h"
21 : :
22 : : #include <fcntl.h>
23 : : #include <limits.h>
24 : : #include <signal.h>
25 : : #include <unistd.h>
26 : : #include <sys/resource.h>
27 : : #include <sys/socket.h>
28 : : #include <sys/time.h>
29 : :
30 : : #ifdef USE_VALGRIND
31 : : #include <valgrind/valgrind.h>
32 : : #endif
33 : :
34 : : #include "access/parallel.h"
35 : : #include "access/printtup.h"
36 : : #include "access/xact.h"
37 : : #include "catalog/pg_type.h"
38 : : #include "commands/async.h"
39 : : #include "commands/event_trigger.h"
40 : : #include "commands/explain_state.h"
41 : : #include "commands/prepare.h"
42 : : #include "commands/repack.h"
43 : : #include "common/pg_prng.h"
44 : : #include "jit/jit.h"
45 : : #include "libpq/libpq.h"
46 : : #include "libpq/pqformat.h"
47 : : #include "libpq/pqsignal.h"
48 : : #include "mb/pg_wchar.h"
49 : : #include "mb/stringinfo_mb.h"
50 : : #include "miscadmin.h"
51 : : #include "nodes/print.h"
52 : : #include "optimizer/optimizer.h"
53 : : #include "parser/analyze.h"
54 : : #include "parser/parser.h"
55 : : #include "pg_trace.h"
56 : : #include "pgstat.h"
57 : : #include "port/pg_getopt_ctx.h"
58 : : #include "postmaster/interrupt.h"
59 : : #include "postmaster/postmaster.h"
60 : : #include "replication/logicallauncher.h"
61 : : #include "replication/logicalworker.h"
62 : : #include "replication/slotsync.h"
63 : : #include "replication/slot.h"
64 : : #include "replication/walsender.h"
65 : : #include "rewrite/rewriteHandler.h"
66 : : #include "storage/bufmgr.h"
67 : : #include "storage/ipc.h"
68 : : #include "storage/fd.h"
69 : : #include "storage/pmsignal.h"
70 : : #include "storage/proc.h"
71 : : #include "storage/procsignal.h"
72 : : #include "storage/shmem_internal.h"
73 : : #include "storage/sinval.h"
74 : : #include "storage/standby.h"
75 : : #include "tcop/backend_startup.h"
76 : : #include "tcop/fastpath.h"
77 : : #include "tcop/pquery.h"
78 : : #include "tcop/tcopprot.h"
79 : : #include "tcop/utility.h"
80 : : #include "utils/guc_hooks.h"
81 : : #include "utils/injection_point.h"
82 : : #include "utils/lsyscache.h"
83 : : #include "utils/memutils.h"
84 : : #include "utils/ps_status.h"
85 : : #include "utils/snapmgr.h"
86 : : #include "utils/timeout.h"
87 : : #include "utils/timestamp.h"
88 : : #include "utils/varlena.h"
89 : :
90 : : /* ----------------
91 : : * global variables
92 : : * ----------------
93 : : */
94 : : const char *debug_query_string; /* client-supplied query string */
95 : :
96 : : /* Note: whereToSendOutput is initialized for the bootstrap/standalone case */
97 : : CommandDest whereToSendOutput = DestDebug;
98 : :
99 : : /* flag for logging end of session */
100 : : bool Log_disconnections = false;
101 : :
102 : : int log_statement = LOGSTMT_NONE;
103 : :
104 : : /* wait N seconds to allow attach from a debugger */
105 : : int PostAuthDelay = 0;
106 : :
107 : : /* Time between checks that the client is still connected. */
108 : : int client_connection_check_interval = 0;
109 : :
110 : : /* flags for non-system relation kinds to restrict use */
111 : : int restrict_nonsystem_relation_kind;
112 : :
113 : : /*
114 : : * Include signal sender PID/UID in the server log when available
115 : : * (SA_SIGINFO). The caller must supply the already-captured pid and uid
116 : : * values.
117 : : */
118 : : #define ERRDETAIL_SIGNAL_SENDER(pid, uid) \
119 : : ((pid) == 0 ? 0 : \
120 : : errdetail_log("Signal sent by PID %d, UID %d.", (int) (pid), (int) (uid)))
121 : :
122 : : /* ----------------
123 : : * private typedefs etc
124 : : * ----------------
125 : : */
126 : :
127 : : /* type of argument for bind_param_error_callback */
128 : : typedef struct BindParamCbData
129 : : {
130 : : const char *portalName;
131 : : int paramno; /* zero-based param number, or -1 initially */
132 : : const char *paramval; /* textual input string, if available */
133 : : } BindParamCbData;
134 : :
135 : : /* ----------------
136 : : * private variables
137 : : * ----------------
138 : : */
139 : :
140 : : /*
141 : : * Flag to keep track of whether we have started a transaction.
142 : : * For extended query protocol this has to be remembered across messages.
143 : : */
144 : : static bool xact_started = false;
145 : :
146 : : /*
147 : : * Flag to indicate that we are doing the outer loop's read-from-client,
148 : : * as opposed to any random read from client that might happen within
149 : : * commands like COPY FROM STDIN.
150 : : */
151 : : static bool DoingCommandRead = false;
152 : :
153 : : /*
154 : : * Flags to implement skip-till-Sync-after-error behavior for messages of
155 : : * the extended query protocol.
156 : : */
157 : : static bool doing_extended_query_message = false;
158 : : static bool ignore_till_sync = false;
159 : :
160 : : /*
161 : : * If an unnamed prepared statement exists, it's stored here.
162 : : * We keep it separate from the hashtable kept by commands/prepare.c
163 : : * in order to reduce overhead for short-lived queries.
164 : : */
165 : : static CachedPlanSource *unnamed_stmt_psrc = NULL;
166 : :
167 : : /* assorted command-line switches */
168 : : static const char *userDoption = NULL; /* -D switch */
169 : : static bool EchoQuery = false; /* -E switch */
170 : : static bool UseSemiNewlineNewline = false; /* -j switch */
171 : :
172 : : /* reused buffer to pass to SendRowDescriptionMessage() */
173 : : static MemoryContext row_description_context = NULL;
174 : : static StringInfoData row_description_buf;
175 : :
176 : : /* ----------------------------------------------------------------
177 : : * decls for routines only used in this file
178 : : * ----------------------------------------------------------------
179 : : */
180 : : static int InteractiveBackend(StringInfo inBuf);
181 : : static int interactive_getc(void);
182 : : static int SocketBackend(StringInfo inBuf);
183 : : static int ReadCommand(StringInfo inBuf);
184 : : static void forbidden_in_wal_sender(char firstchar);
185 : : static bool check_log_statement(List *stmt_list);
186 : : static char *truncate_query_log(const char *query);
187 : : static int errdetail_execute(List *raw_parsetree_list);
188 : : static int errdetail_params(ParamListInfo params);
189 : : static void bind_param_error_callback(void *arg);
190 : : static void start_xact_command(void);
191 : : static void finish_xact_command(void);
192 : : static bool IsTransactionExitStmt(Node *parsetree);
193 : : static bool IsTransactionExitStmtList(List *pstmts);
194 : : static bool IsTransactionStmtList(List *pstmts);
195 : : static void drop_unnamed_stmt(void);
196 : : static void ProcessRecoveryConflictInterrupts(void);
197 : : static void ProcessRecoveryConflictInterrupt(RecoveryConflictReason reason);
198 : : static void report_recovery_conflict(RecoveryConflictReason reason);
199 : : static void log_disconnections(int code, Datum arg);
200 : : static void enable_statement_timeout(void);
201 : : static void disable_statement_timeout(void);
202 : :
203 : :
204 : : /* ----------------------------------------------------------------
205 : : * infrastructure for valgrind debugging
206 : : * ----------------------------------------------------------------
207 : : */
208 : : #ifdef USE_VALGRIND
209 : : /* This variable should be set at the top of the main loop. */
210 : : static unsigned int old_valgrind_error_count;
211 : :
212 : : /*
213 : : * If Valgrind detected any errors since old_valgrind_error_count was updated,
214 : : * report the current query as the cause. This should be called at the end
215 : : * of message processing.
216 : : */
217 : : static void
218 : : valgrind_report_error_query(const char *query)
219 : : {
220 : : unsigned int valgrind_error_count = VALGRIND_COUNT_ERRORS;
221 : :
222 : : if (unlikely(valgrind_error_count != old_valgrind_error_count) &&
223 : : query != NULL)
224 : : VALGRIND_PRINTF("Valgrind detected %u error(s) during execution of \"%s\"\n",
225 : : valgrind_error_count - old_valgrind_error_count,
226 : : query);
227 : : }
228 : :
229 : : #else /* !USE_VALGRIND */
230 : : #define valgrind_report_error_query(query) ((void) 0)
231 : : #endif /* USE_VALGRIND */
232 : :
233 : :
234 : : /* ----------------------------------------------------------------
235 : : * routines to obtain user input
236 : : * ----------------------------------------------------------------
237 : : */
238 : :
239 : : /* ----------------
240 : : * InteractiveBackend() is called for user interactive connections
241 : : *
242 : : * the string entered by the user is placed in its parameter inBuf,
243 : : * and we act like a Q message was received.
244 : : *
245 : : * EOF is returned if end-of-file input is seen; time to shut down.
246 : : * ----------------
247 : : */
248 : :
249 : : static int
250 : 37447 : InteractiveBackend(StringInfo inBuf)
251 : : {
252 : : int c; /* character read from getc() */
253 : :
254 : : /*
255 : : * display a prompt and obtain input from the user
256 : : */
257 : 37447 : printf("backend> ");
258 : 37447 : fflush(stdout);
259 : :
260 : 37447 : resetStringInfo(inBuf);
261 : :
262 : : /*
263 : : * Read characters until EOF or the appropriate delimiter is seen.
264 : : */
265 [ + + ]: 14570052 : while ((c = interactive_getc()) != EOF)
266 : : {
267 [ + + ]: 14569963 : if (c == '\n')
268 : : {
269 [ + + ]: 388644 : if (UseSemiNewlineNewline)
270 : : {
271 : : /*
272 : : * In -j mode, semicolon followed by two newlines ends the
273 : : * command; otherwise treat newline as regular character.
274 : : */
275 [ + + ]: 388633 : if (inBuf->len > 1 &&
276 [ + + ]: 383854 : inBuf->data[inBuf->len - 1] == '\n' &&
277 [ + + ]: 58115 : inBuf->data[inBuf->len - 2] == ';')
278 : : {
279 : : /* might as well drop the second newline */
280 : 37347 : break;
281 : : }
282 : : }
283 : : else
284 : : {
285 : : /*
286 : : * In plain mode, newline ends the command unless preceded by
287 : : * backslash.
288 : : */
289 [ + + ]: 11 : if (inBuf->len > 0 &&
290 [ - + ]: 9 : inBuf->data[inBuf->len - 1] == '\\')
291 : : {
292 : : /* discard backslash from inBuf */
293 : 0 : inBuf->data[--inBuf->len] = '\0';
294 : : /* discard newline too */
295 : 0 : continue;
296 : : }
297 : : else
298 : : {
299 : : /* keep the newline character, but end the command */
300 : 11 : appendStringInfoChar(inBuf, '\n');
301 : 11 : break;
302 : : }
303 : : }
304 : : }
305 : :
306 : : /* Not newline, or newline treated as regular character */
307 : 14532605 : appendStringInfoChar(inBuf, (char) c);
308 : : }
309 : :
310 : : /* No input before EOF signal means time to quit. */
311 [ + + + + ]: 37447 : if (c == EOF && inBuf->len == 0)
312 : 80 : return EOF;
313 : :
314 : : /*
315 : : * otherwise we have a user query so process it.
316 : : */
317 : :
318 : : /* Add '\0' to make it look the same as message case. */
319 : 37367 : appendStringInfoChar(inBuf, (char) '\0');
320 : :
321 : : /*
322 : : * if the query echo flag was given, print the query..
323 : : */
324 [ - + ]: 37367 : if (EchoQuery)
325 : 0 : printf("statement: %s\n", inBuf->data);
326 : 37367 : fflush(stdout);
327 : :
328 : 37367 : return PqMsg_Query;
329 : : }
330 : :
331 : : /*
332 : : * interactive_getc -- collect one character from stdin
333 : : *
334 : : * Even though we are not reading from a "client" process, we still want to
335 : : * respond to signals, particularly SIGTERM/SIGQUIT.
336 : : */
337 : : static int
338 : 14570052 : interactive_getc(void)
339 : : {
340 : : int c;
341 : :
342 : : /*
343 : : * This will not process catchup interrupts or notifications while
344 : : * reading. But those can't really be relevant for a standalone backend
345 : : * anyway. To properly handle SIGTERM there's a hack in die() that
346 : : * directly processes interrupts at this stage...
347 : : */
348 [ - + ]: 14570052 : CHECK_FOR_INTERRUPTS();
349 : :
350 : 14570052 : c = getc(stdin);
351 : :
352 : 14570052 : ProcessClientReadInterrupt(false);
353 : :
354 : 14570052 : return c;
355 : : }
356 : :
357 : : /* ----------------
358 : : * SocketBackend() Is called for frontend-backend connections
359 : : *
360 : : * Returns the message type code, and loads message body data into inBuf.
361 : : *
362 : : * EOF is returned if the connection is lost.
363 : : * ----------------
364 : : */
365 : : static int
366 : 483217 : SocketBackend(StringInfo inBuf)
367 : : {
368 : : int qtype;
369 : : int maxmsglen;
370 : :
371 : : /*
372 : : * Get message type code from the frontend.
373 : : */
374 : 483217 : HOLD_CANCEL_INTERRUPTS();
375 : 483217 : pq_startmsgread();
376 : 483217 : qtype = pq_getbyte();
377 : :
378 [ + + ]: 483188 : if (qtype == EOF) /* frontend disconnected */
379 : : {
380 [ + + ]: 36 : if (IsTransactionState())
381 [ + - ]: 4 : ereport(COMMERROR,
382 : : (errcode(ERRCODE_CONNECTION_FAILURE),
383 : : errmsg("unexpected EOF on client connection with an open transaction")));
384 : : else
385 : : {
386 : : /*
387 : : * Can't send DEBUG log messages to client at this point. Since
388 : : * we're disconnecting right away, we don't need to restore
389 : : * whereToSendOutput.
390 : : */
391 : 32 : whereToSendOutput = DestNone;
392 [ + + ]: 32 : ereport(DEBUG1,
393 : : (errcode(ERRCODE_CONNECTION_DOES_NOT_EXIST),
394 : : errmsg_internal("unexpected EOF on client connection")));
395 : : }
396 : 36 : return qtype;
397 : : }
398 : :
399 : : /*
400 : : * Validate message type code before trying to read body; if we have lost
401 : : * sync, better to say "command unknown" than to run out of memory because
402 : : * we used garbage as a length word. We can also select a type-dependent
403 : : * limit on what a sane length word could be. (The limit could be chosen
404 : : * more granularly, but it's not clear it's worth fussing over.)
405 : : *
406 : : * This also gives us a place to set the doing_extended_query_message flag
407 : : * as soon as possible.
408 : : */
409 [ + + + + : 483152 : switch (qtype)
+ + + +
- ]
410 : : {
411 : 406661 : case PqMsg_Query:
412 : 406661 : maxmsglen = PQ_LARGE_MESSAGE_LIMIT;
413 : 406661 : doing_extended_query_message = false;
414 : 406661 : break;
415 : :
416 : 1343 : case PqMsg_FunctionCall:
417 : 1343 : maxmsglen = PQ_LARGE_MESSAGE_LIMIT;
418 : 1343 : doing_extended_query_message = false;
419 : 1343 : break;
420 : :
421 : 15763 : case PqMsg_Terminate:
422 : 15763 : maxmsglen = PQ_SMALL_MESSAGE_LIMIT;
423 : 15763 : doing_extended_query_message = false;
424 : 15763 : ignore_till_sync = false;
425 : 15763 : break;
426 : :
427 : 19313 : case PqMsg_Bind:
428 : : case PqMsg_Parse:
429 : 19313 : maxmsglen = PQ_LARGE_MESSAGE_LIMIT;
430 : 19313 : doing_extended_query_message = true;
431 : 19313 : break;
432 : :
433 : 26412 : case PqMsg_Close:
434 : : case PqMsg_Describe:
435 : : case PqMsg_Execute:
436 : : case PqMsg_Flush:
437 : 26412 : maxmsglen = PQ_SMALL_MESSAGE_LIMIT;
438 : 26412 : doing_extended_query_message = true;
439 : 26412 : break;
440 : :
441 : 13489 : case PqMsg_Sync:
442 : 13489 : maxmsglen = PQ_SMALL_MESSAGE_LIMIT;
443 : : /* stop any active skip-till-Sync */
444 : 13489 : ignore_till_sync = false;
445 : : /* mark not-extended, so that a new error doesn't begin skip */
446 : 13489 : doing_extended_query_message = false;
447 : 13489 : break;
448 : :
449 : 22 : case PqMsg_CopyData:
450 : 22 : maxmsglen = PQ_LARGE_MESSAGE_LIMIT;
451 : 22 : doing_extended_query_message = false;
452 : 22 : break;
453 : :
454 : 149 : case PqMsg_CopyDone:
455 : : case PqMsg_CopyFail:
456 : 149 : maxmsglen = PQ_SMALL_MESSAGE_LIMIT;
457 : 149 : doing_extended_query_message = false;
458 : 149 : break;
459 : :
460 : 0 : default:
461 : :
462 : : /*
463 : : * Otherwise we got garbage from the frontend. We treat this as
464 : : * fatal because we have probably lost message boundary sync, and
465 : : * there's no good way to recover.
466 : : */
467 [ # # ]: 0 : ereport(FATAL,
468 : : (errcode(ERRCODE_PROTOCOL_VIOLATION),
469 : : errmsg("invalid frontend message type %d", qtype)));
470 : : maxmsglen = 0; /* keep compiler quiet */
471 : : break;
472 : : }
473 : :
474 : : /*
475 : : * In protocol version 3, all frontend messages have a length word next
476 : : * after the type code; we can read the message contents independently of
477 : : * the type.
478 : : */
479 [ - + ]: 483152 : if (pq_getmessage(inBuf, maxmsglen))
480 : 0 : return EOF; /* suitable message already logged */
481 : 483152 : RESUME_CANCEL_INTERRUPTS();
482 : :
483 : 483152 : return qtype;
484 : : }
485 : :
486 : : /* ----------------
487 : : * ReadCommand reads a command from either the frontend or
488 : : * standard input, places it in inBuf, and returns the
489 : : * message type code (first byte of the message).
490 : : * EOF is returned if end of file.
491 : : * ----------------
492 : : */
493 : : static int
494 : 520664 : ReadCommand(StringInfo inBuf)
495 : : {
496 : : int result;
497 : :
498 [ + + ]: 520664 : if (whereToSendOutput == DestRemote)
499 : 483217 : result = SocketBackend(inBuf);
500 : : else
501 : 37447 : result = InteractiveBackend(inBuf);
502 : 520635 : return result;
503 : : }
504 : :
505 : : /*
506 : : * ProcessClientReadInterrupt() - Process interrupts specific to client reads
507 : : *
508 : : * This is called just before and after low-level reads.
509 : : * 'blocked' is true if no data was available to read and we plan to retry,
510 : : * false if about to read or done reading.
511 : : *
512 : : * Must preserve errno!
513 : : */
514 : : void
515 : 17932223 : ProcessClientReadInterrupt(bool blocked)
516 : : {
517 : 17932223 : int save_errno = errno;
518 : :
519 [ + + ]: 17932223 : if (DoingCommandRead)
520 : : {
521 : : /* Check for general interrupts that arrived before/while reading */
522 [ + + ]: 15460984 : CHECK_FOR_INTERRUPTS();
523 : :
524 : : /* Process sinval catchup interrupts, if any */
525 [ + + ]: 15460955 : if (catchupInterruptPending)
526 : 468 : ProcessCatchupInterrupt();
527 : :
528 : : /* Process notify interrupts, if any */
529 [ + + ]: 15460955 : if (notifyInterruptPending)
530 : 13 : ProcessNotifyInterrupt(true);
531 : :
532 : : /*
533 : : * Processing a catchup or notify interrupt can run a transaction. If
534 : : * the idle stats update timeout fired while we were in it,
535 : : * ProcessInterrupts() did not report the stats because we were not
536 : : * fully idle, but it did clear InterruptPending. Process the timeout
537 : : * now if that happened.
538 : : */
539 [ + + ]: 15460955 : if (IdleStatsUpdateTimeoutPending)
540 : : {
541 : 596 : InterruptPending = true;
542 [ + - ]: 596 : CHECK_FOR_INTERRUPTS();
543 : : }
544 : : }
545 [ - + ]: 2471239 : else if (ProcDiePending)
546 : : {
547 : : /*
548 : : * We're dying. If there is no data available to read, then it's safe
549 : : * (and sane) to handle that now. If we haven't tried to read yet,
550 : : * make sure the process latch is set, so that if there is no data
551 : : * then we'll come back here and die. If we're done reading, also
552 : : * make sure the process latch is set, as we might've undesirably
553 : : * cleared it while reading.
554 : : */
555 [ # # ]: 0 : if (blocked)
556 [ # # ]: 0 : CHECK_FOR_INTERRUPTS();
557 : : else
558 : 0 : SetLatch(MyLatch);
559 : : }
560 : :
561 : 17932194 : errno = save_errno;
562 : 17932194 : }
563 : :
564 : : /*
565 : : * ProcessClientWriteInterrupt() - Process interrupts specific to client writes
566 : : *
567 : : * This is called just before and after low-level writes.
568 : : * 'blocked' is true if no data could be written and we plan to retry,
569 : : * false if about to write or done writing.
570 : : *
571 : : * Must preserve errno!
572 : : */
573 : : void
574 : 2901694 : ProcessClientWriteInterrupt(bool blocked)
575 : : {
576 : 2901694 : int save_errno = errno;
577 : :
578 [ - + ]: 2901694 : if (ProcDiePending)
579 : : {
580 : : /*
581 : : * We're dying. If it's not possible to write, then we should handle
582 : : * that immediately, else a stuck client could indefinitely delay our
583 : : * response to the signal. If we haven't tried to write yet, make
584 : : * sure the process latch is set, so that if the write would block
585 : : * then we'll come back here and die. If we're done writing, also
586 : : * make sure the process latch is set, as we might've undesirably
587 : : * cleared it while writing.
588 : : */
589 [ # # ]: 0 : if (blocked)
590 : : {
591 : : /*
592 : : * Don't mess with whereToSendOutput if ProcessInterrupts wouldn't
593 : : * service ProcDiePending.
594 : : */
595 [ # # # # ]: 0 : if (InterruptHoldoffCount == 0 && CritSectionCount == 0)
596 : : {
597 : : /*
598 : : * We don't want to send the client the error message, as a)
599 : : * that would possibly block again, and b) it would likely
600 : : * lead to loss of protocol sync because we may have already
601 : : * sent a partial protocol message.
602 : : */
603 [ # # ]: 0 : if (whereToSendOutput == DestRemote)
604 : 0 : whereToSendOutput = DestNone;
605 : :
606 [ # # ]: 0 : CHECK_FOR_INTERRUPTS();
607 : : }
608 : : }
609 : : else
610 : 0 : SetLatch(MyLatch);
611 : : }
612 : :
613 : 2901694 : errno = save_errno;
614 : 2901694 : }
615 : :
616 : : /*
617 : : * Do raw parsing (only).
618 : : *
619 : : * A list of parsetrees (RawStmt nodes) is returned, since there might be
620 : : * multiple commands in the given string.
621 : : *
622 : : * NOTE: for interactive queries, it is important to keep this routine
623 : : * separate from the analysis & rewrite stages. Analysis and rewriting
624 : : * cannot be done in an aborted transaction, since they require access to
625 : : * database tables. So, we rely on the raw parser to determine whether
626 : : * we've seen a COMMIT or ABORT command; when we are in abort state, other
627 : : * commands are not processed any further than the raw parse stage.
628 : : */
629 : : List *
630 : 452690 : pg_parse_query(const char *query_string)
631 : : {
632 : : List *raw_parsetree_list;
633 : :
634 : : TRACE_POSTGRESQL_QUERY_PARSE_START(query_string);
635 : :
636 [ - + ]: 452690 : if (log_parser_stats)
637 : 0 : ResetUsage();
638 : :
639 : 452690 : raw_parsetree_list = raw_parser(query_string, RAW_PARSE_DEFAULT);
640 : :
641 [ - + ]: 451907 : if (log_parser_stats)
642 : 0 : ShowUsage("PARSER STATISTICS");
643 : :
644 : : #ifdef DEBUG_NODE_TESTS_ENABLED
645 : :
646 : : /* Optional debugging check: pass raw parsetrees through copyObject() */
647 [ + - ]: 451907 : if (Debug_copy_parse_plan_trees)
648 : : {
649 : 451907 : List *new_list = copyObject(raw_parsetree_list);
650 : :
651 : : /* This checks both copyObject() and the equal() routines... */
652 [ - + ]: 451907 : if (!equal(new_list, raw_parsetree_list))
653 [ # # ]: 0 : elog(WARNING, "copyObject() failed to produce an equal raw parse tree");
654 : : else
655 : 451907 : raw_parsetree_list = new_list;
656 : : }
657 : :
658 : : /*
659 : : * Optional debugging check: pass raw parsetrees through
660 : : * outfuncs/readfuncs
661 : : */
662 [ + - ]: 451907 : if (Debug_write_read_parse_plan_trees)
663 : : {
664 : 451907 : char *str = nodeToStringWithLocations(raw_parsetree_list);
665 : 451907 : List *new_list = stringToNodeWithLocations(str);
666 : :
667 : 451907 : pfree(str);
668 : : /* This checks both outfuncs/readfuncs and the equal() routines... */
669 [ - + ]: 451907 : if (!equal(new_list, raw_parsetree_list))
670 [ # # ]: 0 : elog(WARNING, "outfuncs/readfuncs failed to produce an equal raw parse tree");
671 : : else
672 : 451907 : raw_parsetree_list = new_list;
673 : : }
674 : :
675 : : #endif /* DEBUG_NODE_TESTS_ENABLED */
676 : :
677 : : TRACE_POSTGRESQL_QUERY_PARSE_DONE(query_string);
678 : :
679 [ - + ]: 451907 : if (Debug_print_raw_parse)
680 : 0 : elog_node_display(LOG, "raw parse tree", raw_parsetree_list,
681 : : Debug_pretty_print);
682 : :
683 : 451907 : return raw_parsetree_list;
684 : : }
685 : :
686 : : /*
687 : : * Given a raw parsetree (gram.y output), and optionally information about
688 : : * types of parameter symbols ($n), perform parse analysis and rule rewriting.
689 : : *
690 : : * A list of Query nodes is returned, since either the analyzer or the
691 : : * rewriter might expand one query to several.
692 : : *
693 : : * NOTE: for reasons mentioned above, this must be separate from raw parsing.
694 : : */
695 : : List *
696 : 496542 : pg_analyze_and_rewrite_fixedparams(RawStmt *parsetree,
697 : : const char *query_string,
698 : : const Oid *paramTypes,
699 : : int numParams,
700 : : QueryEnvironment *queryEnv)
701 : : {
702 : : Query *query;
703 : : List *querytree_list;
704 : :
705 : : TRACE_POSTGRESQL_QUERY_REWRITE_START(query_string);
706 : :
707 : : /*
708 : : * (1) Perform parse analysis.
709 : : */
710 [ - + ]: 496542 : if (log_parser_stats)
711 : 0 : ResetUsage();
712 : :
713 : 496542 : query = parse_analyze_fixedparams(parsetree, query_string, paramTypes, numParams,
714 : : queryEnv);
715 : :
716 [ - + ]: 490831 : if (log_parser_stats)
717 : 0 : ShowUsage("PARSE ANALYSIS STATISTICS");
718 : :
719 : : /*
720 : : * (2) Rewrite the queries, as necessary
721 : : */
722 : 490831 : querytree_list = pg_rewrite_query(query);
723 : :
724 : : TRACE_POSTGRESQL_QUERY_REWRITE_DONE(query_string);
725 : :
726 : 490363 : return querytree_list;
727 : : }
728 : :
729 : : /*
730 : : * Do parse analysis and rewriting. This is the same as
731 : : * pg_analyze_and_rewrite_fixedparams except that it's okay to deduce
732 : : * information about $n symbol datatypes from context.
733 : : */
734 : : List *
735 : 7330 : pg_analyze_and_rewrite_varparams(RawStmt *parsetree,
736 : : const char *query_string,
737 : : Oid **paramTypes,
738 : : int *numParams,
739 : : QueryEnvironment *queryEnv)
740 : : {
741 : : Query *query;
742 : : List *querytree_list;
743 : :
744 : : TRACE_POSTGRESQL_QUERY_REWRITE_START(query_string);
745 : :
746 : : /*
747 : : * (1) Perform parse analysis.
748 : : */
749 [ - + ]: 7330 : if (log_parser_stats)
750 : 0 : ResetUsage();
751 : :
752 : 7330 : query = parse_analyze_varparams(parsetree, query_string, paramTypes, numParams,
753 : : queryEnv);
754 : :
755 : : /*
756 : : * Check all parameter types got determined.
757 : : */
758 [ + + ]: 15398 : for (int i = 0; i < *numParams; i++)
759 : : {
760 : 8082 : Oid ptype = (*paramTypes)[i];
761 : :
762 [ + + - + ]: 8082 : if (ptype == InvalidOid || ptype == UNKNOWNOID)
763 [ + - ]: 4 : ereport(ERROR,
764 : : (errcode(ERRCODE_INDETERMINATE_DATATYPE),
765 : : errmsg("could not determine data type of parameter $%d",
766 : : i + 1)));
767 : : }
768 : :
769 [ - + ]: 7316 : if (log_parser_stats)
770 : 0 : ShowUsage("PARSE ANALYSIS STATISTICS");
771 : :
772 : : /*
773 : : * (2) Rewrite the queries, as necessary
774 : : */
775 : 7316 : querytree_list = pg_rewrite_query(query);
776 : :
777 : : TRACE_POSTGRESQL_QUERY_REWRITE_DONE(query_string);
778 : :
779 : 7316 : return querytree_list;
780 : : }
781 : :
782 : : /*
783 : : * Do parse analysis and rewriting. This is the same as
784 : : * pg_analyze_and_rewrite_fixedparams except that, instead of a fixed list of
785 : : * parameter datatypes, a parser callback is supplied that can do
786 : : * external-parameter resolution and possibly other things.
787 : : */
788 : : List *
789 : 25728 : pg_analyze_and_rewrite_withcb(RawStmt *parsetree,
790 : : const char *query_string,
791 : : ParserSetupHook parserSetup,
792 : : void *parserSetupArg,
793 : : QueryEnvironment *queryEnv)
794 : : {
795 : : Query *query;
796 : : List *querytree_list;
797 : :
798 : : TRACE_POSTGRESQL_QUERY_REWRITE_START(query_string);
799 : :
800 : : /*
801 : : * (1) Perform parse analysis.
802 : : */
803 [ - + ]: 25728 : if (log_parser_stats)
804 : 0 : ResetUsage();
805 : :
806 : 25728 : query = parse_analyze_withcb(parsetree, query_string, parserSetup, parserSetupArg,
807 : : queryEnv);
808 : :
809 [ - + ]: 25649 : if (log_parser_stats)
810 : 0 : ShowUsage("PARSE ANALYSIS STATISTICS");
811 : :
812 : : /*
813 : : * (2) Rewrite the queries, as necessary
814 : : */
815 : 25649 : querytree_list = pg_rewrite_query(query);
816 : :
817 : : TRACE_POSTGRESQL_QUERY_REWRITE_DONE(query_string);
818 : :
819 : 25649 : return querytree_list;
820 : : }
821 : :
822 : : /*
823 : : * Perform rewriting of a query produced by parse analysis.
824 : : *
825 : : * Note: query must just have come from the parser, because we do not do
826 : : * AcquireRewriteLocks() on it.
827 : : */
828 : : List *
829 : 528108 : pg_rewrite_query(Query *query)
830 : : {
831 : : List *querytree_list;
832 : :
833 [ - + ]: 528108 : if (Debug_print_parse)
834 : 0 : elog_node_display(LOG, "parse tree", query,
835 : : Debug_pretty_print);
836 : :
837 [ - + ]: 528108 : if (log_parser_stats)
838 : 0 : ResetUsage();
839 : :
840 [ + + ]: 528108 : if (query->commandType == CMD_UTILITY)
841 : : {
842 : : /* don't rewrite utilities, just dump 'em into result list */
843 : 255729 : querytree_list = list_make1(query);
844 : : }
845 : : else
846 : : {
847 : : /* rewrite regular queries */
848 : 272379 : querytree_list = QueryRewrite(query);
849 : : }
850 : :
851 [ - + ]: 527632 : if (log_parser_stats)
852 : 0 : ShowUsage("REWRITER STATISTICS");
853 : :
854 : : #ifdef DEBUG_NODE_TESTS_ENABLED
855 : :
856 : : /* Optional debugging check: pass querytree through copyObject() */
857 [ + - ]: 527632 : if (Debug_copy_parse_plan_trees)
858 : : {
859 : : List *new_list;
860 : :
861 : 527632 : new_list = copyObject(querytree_list);
862 : : /* This checks both copyObject() and the equal() routines... */
863 [ - + ]: 527632 : if (!equal(new_list, querytree_list))
864 [ # # ]: 0 : elog(WARNING, "copyObject() failed to produce an equal rewritten parse tree");
865 : : else
866 : 527632 : querytree_list = new_list;
867 : : }
868 : :
869 : : /* Optional debugging check: pass querytree through outfuncs/readfuncs */
870 [ + - ]: 527632 : if (Debug_write_read_parse_plan_trees)
871 : : {
872 : 527632 : List *new_list = NIL;
873 : : ListCell *lc;
874 : :
875 [ + + + + : 1055716 : foreach(lc, querytree_list)
+ + ]
876 : : {
877 : 528084 : Query *curr_query = lfirst_node(Query, lc);
878 : 528084 : char *str = nodeToStringWithLocations(curr_query);
879 : 528084 : Query *new_query = stringToNodeWithLocations(str);
880 : :
881 : : /*
882 : : * queryId is not saved in stored rules, but we must preserve it
883 : : * here to avoid breaking pg_stat_statements.
884 : : */
885 : 528084 : new_query->queryId = curr_query->queryId;
886 : :
887 : 528084 : new_list = lappend(new_list, new_query);
888 : 528084 : pfree(str);
889 : : }
890 : :
891 : : /* This checks both outfuncs/readfuncs and the equal() routines... */
892 [ - + ]: 527632 : if (!equal(new_list, querytree_list))
893 [ # # ]: 0 : elog(WARNING, "outfuncs/readfuncs failed to produce an equal rewritten parse tree");
894 : : else
895 : 527632 : querytree_list = new_list;
896 : : }
897 : :
898 : : #endif /* DEBUG_NODE_TESTS_ENABLED */
899 : :
900 [ - + ]: 527632 : if (Debug_print_rewritten)
901 : 0 : elog_node_display(LOG, "rewritten parse tree", querytree_list,
902 : : Debug_pretty_print);
903 : :
904 : 527632 : return querytree_list;
905 : : }
906 : :
907 : :
908 : : /*
909 : : * Generate a plan for a single already-rewritten query.
910 : : * This is a thin wrapper around planner() and takes the same parameters.
911 : : */
912 : : PlannedStmt *
913 : 297893 : pg_plan_query(Query *querytree, const char *query_string, int cursorOptions,
914 : : ParamListInfo boundParams, ExplainState *es)
915 : : {
916 : : PlannedStmt *plan;
917 : :
918 : : /* Utility commands have no plans. */
919 [ - + ]: 297893 : if (querytree->commandType == CMD_UTILITY)
920 : 0 : return NULL;
921 : :
922 : : /* Planner must have a snapshot in case it calls user-defined functions. */
923 : : Assert(ActiveSnapshotSet());
924 : :
925 : : TRACE_POSTGRESQL_QUERY_PLAN_START();
926 : :
927 [ - + ]: 297893 : if (log_planner_stats)
928 : 0 : ResetUsage();
929 : :
930 : : /* call the optimizer */
931 : 297893 : plan = planner(querytree, query_string, cursorOptions, boundParams, es);
932 : :
933 [ - + ]: 294490 : if (log_planner_stats)
934 : 0 : ShowUsage("PLANNER STATISTICS");
935 : :
936 : : #ifdef DEBUG_NODE_TESTS_ENABLED
937 : :
938 : : /* Optional debugging check: pass plan tree through copyObject() */
939 [ + - ]: 294490 : if (Debug_copy_parse_plan_trees)
940 : : {
941 : 294490 : PlannedStmt *new_plan = copyObject(plan);
942 : :
943 : : /*
944 : : * equal() currently does not have routines to compare Plan nodes, so
945 : : * don't try to test equality here. Perhaps fix someday?
946 : : */
947 : : #ifdef NOT_USED
948 : : /* This checks both copyObject() and the equal() routines... */
949 : : if (!equal(new_plan, plan))
950 : : elog(WARNING, "copyObject() failed to produce an equal plan tree");
951 : : else
952 : : #endif
953 : 294490 : plan = new_plan;
954 : : }
955 : :
956 : : /* Optional debugging check: pass plan tree through outfuncs/readfuncs */
957 [ + - ]: 294490 : if (Debug_write_read_parse_plan_trees)
958 : : {
959 : : char *str;
960 : : PlannedStmt *new_plan;
961 : :
962 : 294490 : str = nodeToStringWithLocations(plan);
963 : 294490 : new_plan = stringToNodeWithLocations(str);
964 : 294490 : pfree(str);
965 : :
966 : : /*
967 : : * equal() currently does not have routines to compare Plan nodes, so
968 : : * don't try to test equality here. Perhaps fix someday?
969 : : */
970 : : #ifdef NOT_USED
971 : : /* This checks both outfuncs/readfuncs and the equal() routines... */
972 : : if (!equal(new_plan, plan))
973 : : elog(WARNING, "outfuncs/readfuncs failed to produce an equal plan tree");
974 : : else
975 : : #endif
976 : 294490 : plan = new_plan;
977 : : }
978 : :
979 : : #endif /* DEBUG_NODE_TESTS_ENABLED */
980 : :
981 : : /*
982 : : * Print plan if debugging.
983 : : */
984 [ - + ]: 294490 : if (Debug_print_plan)
985 : 0 : elog_node_display(LOG, "plan", plan, Debug_pretty_print);
986 : :
987 : : TRACE_POSTGRESQL_QUERY_PLAN_DONE();
988 : :
989 : 294490 : return plan;
990 : : }
991 : :
992 : : /*
993 : : * Generate plans for a list of already-rewritten queries.
994 : : *
995 : : * For normal optimizable statements, invoke the planner. For utility
996 : : * statements, just make a wrapper PlannedStmt node.
997 : : *
998 : : * The result is a list of PlannedStmt nodes.
999 : : */
1000 : : List *
1001 : 531574 : pg_plan_queries(List *querytrees, const char *query_string, int cursorOptions,
1002 : : ParamListInfo boundParams)
1003 : : {
1004 : 531574 : List *stmt_list = NIL;
1005 : : ListCell *query_list;
1006 : :
1007 [ + - + + : 1060216 : foreach(query_list, querytrees)
+ + ]
1008 : : {
1009 : 532002 : Query *query = lfirst_node(Query, query_list);
1010 : : PlannedStmt *stmt;
1011 : :
1012 [ + + ]: 532002 : if (query->commandType == CMD_UTILITY)
1013 : : {
1014 : : /* Utility commands require no planning. */
1015 : 255683 : stmt = makeNode(PlannedStmt);
1016 : 255683 : stmt->commandType = CMD_UTILITY;
1017 : 255683 : stmt->canSetTag = query->canSetTag;
1018 : 255683 : stmt->utilityStmt = query->utilityStmt;
1019 : 255683 : stmt->stmt_location = query->stmt_location;
1020 : 255683 : stmt->stmt_len = query->stmt_len;
1021 : 255683 : stmt->queryId = query->queryId;
1022 : 255683 : stmt->planOrigin = PLAN_STMT_INTERNAL;
1023 : : }
1024 : : else
1025 : : {
1026 : 276319 : stmt = pg_plan_query(query, query_string, cursorOptions,
1027 : : boundParams, NULL);
1028 : : }
1029 : :
1030 : 528642 : stmt_list = lappend(stmt_list, stmt);
1031 : : }
1032 : :
1033 : 528214 : return stmt_list;
1034 : : }
1035 : :
1036 : :
1037 : : /*
1038 : : * exec_simple_query
1039 : : *
1040 : : * Execute a "simple Query" protocol message.
1041 : : */
1042 : : static void
1043 : 440275 : exec_simple_query(const char *query_string)
1044 : : {
1045 : 440275 : CommandDest dest = whereToSendOutput;
1046 : : MemoryContext oldcontext;
1047 : : List *parsetree_list;
1048 : : ListCell *parsetree_item;
1049 : 440275 : bool save_log_statement_stats = log_statement_stats;
1050 : 440275 : bool was_logged = false;
1051 : : bool use_implicit_block;
1052 : : char msec_str[32];
1053 : :
1054 : : /*
1055 : : * Report query to various monitoring facilities.
1056 : : */
1057 : 440275 : debug_query_string = query_string;
1058 : :
1059 : 440275 : pgstat_report_activity(STATE_RUNNING, query_string);
1060 : :
1061 : : TRACE_POSTGRESQL_QUERY_START(query_string);
1062 : :
1063 : : /*
1064 : : * We use save_log_statement_stats so ShowUsage doesn't report incorrect
1065 : : * results because ResetUsage wasn't called.
1066 : : */
1067 [ + + ]: 440275 : if (save_log_statement_stats)
1068 : 10 : ResetUsage();
1069 : :
1070 : : /*
1071 : : * Start up a transaction command. All queries generated by the
1072 : : * query_string will be in this same command block, *unless* we find a
1073 : : * BEGIN/COMMIT/ABORT statement; we have to force a new xact command after
1074 : : * one of those, else bad things will happen in xact.c. (Note that this
1075 : : * will normally change current memory context.)
1076 : : */
1077 : 440275 : start_xact_command();
1078 : :
1079 : : /*
1080 : : * Zap any pre-existing unnamed statement. (While not strictly necessary,
1081 : : * it seems best to define simple-Query mode as if it used the unnamed
1082 : : * statement and portal; this ensures we recover any storage used by prior
1083 : : * unnamed operations.)
1084 : : */
1085 : 440275 : drop_unnamed_stmt();
1086 : :
1087 : : /*
1088 : : * Switch to appropriate context for constructing parsetrees.
1089 : : */
1090 : 440275 : oldcontext = MemoryContextSwitchTo(MessageContext);
1091 : :
1092 : : /*
1093 : : * Do basic parsing of the query or queries (this should be safe even if
1094 : : * we are in aborted transaction state!)
1095 : : */
1096 : 440275 : parsetree_list = pg_parse_query(query_string);
1097 : :
1098 : : /* Log immediately if dictated by log_statement */
1099 [ + + ]: 439507 : if (check_log_statement(parsetree_list))
1100 : : {
1101 : 207732 : char *truncated_stmt = truncate_query_log(query_string);
1102 : :
1103 [ + + + + ]: 207732 : ereport(LOG,
1104 : : (errmsg("statement: %s",
1105 : : (truncated_stmt != NULL) ? truncated_stmt : query_string),
1106 : : errhidestmt(true),
1107 : : errdetail_execute(parsetree_list)));
1108 : 207732 : was_logged = true;
1109 : :
1110 [ + + ]: 207732 : if (truncated_stmt != NULL)
1111 : 7 : pfree(truncated_stmt);
1112 : : }
1113 : :
1114 : : /*
1115 : : * Switch back to transaction context to enter the loop.
1116 : : */
1117 : 439507 : MemoryContextSwitchTo(oldcontext);
1118 : :
1119 : : /*
1120 : : * For historical reasons, if multiple SQL statements are given in a
1121 : : * single "simple Query" message, we execute them as a single transaction,
1122 : : * unless explicit transaction control commands are included to make
1123 : : * portions of the list be separate transactions. To represent this
1124 : : * behavior properly in the transaction machinery, we use an "implicit"
1125 : : * transaction block.
1126 : : */
1127 : 439507 : use_implicit_block = (list_length(parsetree_list) > 1);
1128 : :
1129 : : /*
1130 : : * Run through the raw parsetree(s) and process each one.
1131 : : */
1132 [ + + + + : 873877 : foreach(parsetree_item, parsetree_list)
+ + ]
1133 : : {
1134 : 465519 : RawStmt *parsetree = lfirst_node(RawStmt, parsetree_item);
1135 : 465519 : bool snapshot_set = false;
1136 : : CommandTag commandTag;
1137 : : QueryCompletion qc;
1138 : 465519 : MemoryContext per_parsetree_context = NULL;
1139 : : List *querytree_list,
1140 : : *plantree_list;
1141 : : Portal portal;
1142 : : DestReceiver *receiver;
1143 : : int16 format;
1144 : : const char *cmdtagname;
1145 : : size_t cmdtaglen;
1146 : :
1147 : 465519 : pgstat_report_query_id(0, true);
1148 : 465519 : pgstat_report_plan_id(0, true);
1149 : :
1150 : : /*
1151 : : * Get the command name for use in status display (it also becomes the
1152 : : * default completion tag, in PortalDefineQuery). Set ps_status and
1153 : : * do any special start-of-SQL-command processing needed by the
1154 : : * destination.
1155 : : */
1156 : 465519 : commandTag = CreateCommandTag(parsetree->stmt);
1157 : 465519 : cmdtagname = GetCommandTagNameAndLen(commandTag, &cmdtaglen);
1158 : :
1159 : 465519 : set_ps_display_with_len(cmdtagname, cmdtaglen);
1160 : :
1161 : 465519 : BeginCommand(commandTag, dest);
1162 : :
1163 : : /*
1164 : : * If we are in an aborted transaction, reject all commands except
1165 : : * COMMIT/ABORT. It is important that this test occur before we try
1166 : : * to do parse analysis, rewrite, or planning, since all those phases
1167 : : * try to do database accesses, which may fail in abort state. (It
1168 : : * might be safe to allow some additional utility commands in this
1169 : : * state, but not many...)
1170 : : */
1171 [ + + ]: 465519 : if (IsAbortedTransactionBlockState() &&
1172 [ + + ]: 1293 : !IsTransactionExitStmt(parsetree->stmt))
1173 [ + - ]: 58 : ereport(ERROR,
1174 : : (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
1175 : : errmsg("current transaction is aborted, "
1176 : : "commands ignored until end of transaction block")));
1177 : :
1178 : : /* Make sure we are in a transaction command */
1179 : 465461 : start_xact_command();
1180 : :
1181 : : /*
1182 : : * If using an implicit transaction block, and we're not already in a
1183 : : * transaction block, start an implicit block to force this statement
1184 : : * to be grouped together with any following ones. (We must do this
1185 : : * each time through the loop; otherwise, a COMMIT/ROLLBACK in the
1186 : : * list would cause later statements to not be grouped.)
1187 : : */
1188 [ + + ]: 465461 : if (use_implicit_block)
1189 : 35143 : BeginImplicitTransactionBlock();
1190 : :
1191 : : /* If we got a cancel signal in parsing or prior command, quit */
1192 [ + + ]: 465461 : CHECK_FOR_INTERRUPTS();
1193 : :
1194 : : /*
1195 : : * Set up a snapshot if parse analysis/planning will need one.
1196 : : */
1197 [ + + ]: 465461 : if (analyze_requires_snapshot(parsetree))
1198 : : {
1199 : 246739 : PushActiveSnapshot(GetTransactionSnapshot());
1200 : 246739 : snapshot_set = true;
1201 : : }
1202 : :
1203 : : /*
1204 : : * OK to analyze, rewrite, and plan this query.
1205 : : *
1206 : : * Switch to appropriate context for constructing query and plan trees
1207 : : * (these can't be in the transaction context, as that will get reset
1208 : : * when the command is COMMIT/ROLLBACK). If we have multiple
1209 : : * parsetrees, we use a separate context for each one, so that we can
1210 : : * free that memory before moving on to the next one. But for the
1211 : : * last (or only) parsetree, just use MessageContext, which will be
1212 : : * reset shortly after completion anyway. In event of an error, the
1213 : : * per_parsetree_context will be deleted when MessageContext is reset.
1214 : : */
1215 [ + + ]: 465461 : if (lnext(parsetree_list, parsetree_item) != NULL)
1216 : : {
1217 : : per_parsetree_context =
1218 : 27196 : AllocSetContextCreate(MessageContext,
1219 : : "per-parsetree message context",
1220 : : ALLOCSET_DEFAULT_SIZES);
1221 : 27196 : oldcontext = MemoryContextSwitchTo(per_parsetree_context);
1222 : : }
1223 : : else
1224 : 438265 : oldcontext = MemoryContextSwitchTo(MessageContext);
1225 : :
1226 : 465461 : querytree_list = pg_analyze_and_rewrite_fixedparams(parsetree, query_string,
1227 : : NULL, 0, NULL);
1228 : :
1229 : 459310 : plantree_list = pg_plan_queries(querytree_list, query_string,
1230 : : CURSOR_OPT_PARALLEL_OK, NULL);
1231 : :
1232 : : /*
1233 : : * Done with the snapshot used for parsing/planning.
1234 : : *
1235 : : * While it looks promising to reuse the same snapshot for query
1236 : : * execution (at least for simple protocol), unfortunately it causes
1237 : : * execution to use a snapshot that has been acquired before locking
1238 : : * any of the tables mentioned in the query. This creates user-
1239 : : * visible anomalies, so refrain. Refer to
1240 : : * https://postgr.es/m/flat/5075D8DF.6050500@fuzzy.cz for details.
1241 : : */
1242 [ + + ]: 456102 : if (snapshot_set)
1243 : 237380 : PopActiveSnapshot();
1244 : :
1245 : : /* If we got a cancel signal in analysis or planning, quit */
1246 [ - + ]: 456102 : CHECK_FOR_INTERRUPTS();
1247 : :
1248 : : /*
1249 : : * Create unnamed portal to run the query or queries in. If there
1250 : : * already is one, silently drop it.
1251 : : */
1252 : 456102 : portal = CreatePortal("", true, true);
1253 : : /* Don't display the portal in pg_cursors */
1254 : 456102 : portal->visible = false;
1255 : :
1256 : : /*
1257 : : * We don't have to copy anything into the portal, because everything
1258 : : * we are passing here is in MessageContext or the
1259 : : * per_parsetree_context, and so will outlive the portal anyway.
1260 : : */
1261 : 456102 : PortalDefineQuery(portal,
1262 : : NULL,
1263 : : query_string,
1264 : : commandTag,
1265 : : plantree_list,
1266 : : NULL);
1267 : :
1268 : : /*
1269 : : * Start the portal. No parameters here.
1270 : : */
1271 : 456102 : PortalStart(portal, NULL, 0, InvalidSnapshot);
1272 : :
1273 : : /*
1274 : : * Select the appropriate output format: text unless we are doing a
1275 : : * FETCH from a binary cursor. (Pretty grotty to have to do this here
1276 : : * --- but it avoids grottiness in other places. Ah, the joys of
1277 : : * backward compatibility...)
1278 : : */
1279 : 455670 : format = 0; /* TEXT is default */
1280 [ + + ]: 455670 : if (IsA(parsetree->stmt, FetchStmt))
1281 : : {
1282 : 3584 : FetchStmt *stmt = (FetchStmt *) parsetree->stmt;
1283 : :
1284 [ + + ]: 3584 : if (!stmt->ismove)
1285 : : {
1286 : 3522 : Portal fportal = GetPortalByName(stmt->portalname);
1287 : :
1288 [ + + ]: 3522 : if (PortalIsValid(fportal) &&
1289 [ + + ]: 3503 : (fportal->cursorOptions & CURSOR_OPT_BINARY))
1290 : 4 : format = 1; /* BINARY */
1291 : : }
1292 : : }
1293 : 455670 : PortalSetResultFormat(portal, 1, &format);
1294 : :
1295 : : /*
1296 : : * Now we can create the destination receiver object.
1297 : : */
1298 : 455670 : receiver = CreateDestReceiver(dest);
1299 [ + + ]: 455670 : if (dest == DestRemote)
1300 : 413293 : SetRemoteDestReceiverParams(receiver, portal);
1301 : :
1302 : : /*
1303 : : * Switch back to transaction context for execution.
1304 : : */
1305 : 455670 : MemoryContextSwitchTo(oldcontext);
1306 : :
1307 : : /*
1308 : : * Run the portal to completion, and then drop it (and the receiver).
1309 : : */
1310 : 455670 : (void) PortalRun(portal,
1311 : : FETCH_ALL,
1312 : : true, /* always top level */
1313 : : receiver,
1314 : : receiver,
1315 : : &qc);
1316 : :
1317 : 434708 : receiver->rDestroy(receiver);
1318 : :
1319 : 434708 : PortalDrop(portal, false);
1320 : :
1321 [ + + ]: 434708 : if (lnext(parsetree_list, parsetree_item) == NULL)
1322 : : {
1323 : : /*
1324 : : * If this is the last parsetree of the query string, close down
1325 : : * transaction statement before reporting command-complete. This
1326 : : * is so that any end-of-transaction errors are reported before
1327 : : * the command-complete message is issued, to avoid confusing
1328 : : * clients who will expect either a command-complete message or an
1329 : : * error, not one and then the other. Also, if we're using an
1330 : : * implicit transaction block, we must close that out first.
1331 : : */
1332 [ + + ]: 407541 : if (use_implicit_block)
1333 : 7884 : EndImplicitTransactionBlock();
1334 : 407541 : finish_xact_command();
1335 : : }
1336 [ + + ]: 27167 : else if (IsA(parsetree->stmt, TransactionStmt))
1337 : : {
1338 : : /*
1339 : : * If this was a transaction control statement, commit it. We will
1340 : : * start a new xact command for the next command.
1341 : : */
1342 : 589 : finish_xact_command();
1343 : : }
1344 : : else
1345 : : {
1346 : : /*
1347 : : * We had better not see XACT_FLAGS_NEEDIMMEDIATECOMMIT set if
1348 : : * we're not calling finish_xact_command(). (The implicit
1349 : : * transaction block should have prevented it from getting set.)
1350 : : */
1351 : : Assert(!(MyXactFlags & XACT_FLAGS_NEEDIMMEDIATECOMMIT));
1352 : :
1353 : : /*
1354 : : * We need a CommandCounterIncrement after every query, except
1355 : : * those that start or end a transaction block.
1356 : : */
1357 : 26578 : CommandCounterIncrement();
1358 : :
1359 : : /*
1360 : : * Disable statement timeout between queries of a multi-query
1361 : : * string, so that the timeout applies separately to each query.
1362 : : * (Our next loop iteration will start a fresh timeout.)
1363 : : */
1364 : 26578 : disable_statement_timeout();
1365 : : }
1366 : :
1367 : : /*
1368 : : * Tell client that we're done with this query. Note we emit exactly
1369 : : * one EndCommand report for each raw parsetree, thus one for each SQL
1370 : : * command the client sent, regardless of rewriting. (But a command
1371 : : * aborted by error will not send an EndCommand report at all.)
1372 : : */
1373 : 434370 : EndCommand(&qc, dest, false);
1374 : :
1375 : : /* Now we may drop the per-parsetree context, if one was created. */
1376 [ + + ]: 434370 : if (per_parsetree_context)
1377 : 27167 : MemoryContextDelete(per_parsetree_context);
1378 : : } /* end loop over parsetrees */
1379 : :
1380 : : /*
1381 : : * Close down transaction statement, if one is open. (This will only do
1382 : : * something if the parsetree list was empty; otherwise the last loop
1383 : : * iteration already did it.)
1384 : : */
1385 : 408358 : finish_xact_command();
1386 : :
1387 : : /*
1388 : : * If there were no parsetrees, return EmptyQueryResponse message.
1389 : : */
1390 [ + + ]: 408358 : if (!parsetree_list)
1391 : 1155 : NullCommand(dest);
1392 : :
1393 : : /*
1394 : : * Emit duration logging if appropriate.
1395 : : */
1396 [ + + + ]: 408358 : switch (check_log_duration(msec_str, was_logged))
1397 : : {
1398 : 18 : case 1:
1399 [ + - ]: 18 : ereport(LOG,
1400 : : (errmsg("duration: %s ms", msec_str),
1401 : : errhidestmt(true)));
1402 : 18 : break;
1403 : 2 : case 2:
1404 : : {
1405 : 2 : char *truncated_stmt = truncate_query_log(query_string);
1406 : :
1407 [ + - + + ]: 2 : ereport(LOG,
1408 : : (errmsg("duration: %s ms statement: %s",
1409 : : msec_str,
1410 : : (truncated_stmt != NULL) ? truncated_stmt : query_string),
1411 : : errhidestmt(true),
1412 : : errdetail_execute(parsetree_list)));
1413 : :
1414 [ + + ]: 2 : if (truncated_stmt != NULL)
1415 : 1 : pfree(truncated_stmt);
1416 : 2 : break;
1417 : : }
1418 : : }
1419 : :
1420 [ + + ]: 408358 : if (save_log_statement_stats)
1421 : 10 : ShowUsage("QUERY STATISTICS");
1422 : :
1423 : : TRACE_POSTGRESQL_QUERY_DONE(query_string);
1424 : :
1425 : 408358 : debug_query_string = NULL;
1426 : 408358 : }
1427 : :
1428 : : /*
1429 : : * exec_parse_message
1430 : : *
1431 : : * Execute a "Parse" protocol message.
1432 : : */
1433 : : static void
1434 : 6119 : exec_parse_message(const char *query_string, /* string to execute */
1435 : : const char *stmt_name, /* name for prepared stmt */
1436 : : Oid *paramTypes, /* parameter types */
1437 : : int numParams) /* number of parameters */
1438 : : {
1439 : 6119 : MemoryContext unnamed_stmt_context = NULL;
1440 : : MemoryContext oldcontext;
1441 : : List *parsetree_list;
1442 : : RawStmt *raw_parse_tree;
1443 : : List *querytree_list;
1444 : : CachedPlanSource *psrc;
1445 : : bool is_named;
1446 : 6119 : bool save_log_statement_stats = log_statement_stats;
1447 : : char msec_str[32];
1448 : :
1449 : : /*
1450 : : * Report query to various monitoring facilities.
1451 : : */
1452 : 6119 : debug_query_string = query_string;
1453 : :
1454 : 6119 : pgstat_report_activity(STATE_RUNNING, query_string);
1455 : :
1456 : 6119 : set_ps_display("PARSE");
1457 : :
1458 [ - + ]: 6119 : if (save_log_statement_stats)
1459 : 0 : ResetUsage();
1460 : :
1461 [ - + - - ]: 6119 : ereport(DEBUG2,
1462 : : (errmsg_internal("parse %s: %s",
1463 : : *stmt_name ? stmt_name : "<unnamed>",
1464 : : query_string)));
1465 : :
1466 : : /*
1467 : : * Start up a transaction command so we can run parse analysis etc. (Note
1468 : : * that this will normally change current memory context.) Nothing happens
1469 : : * if we are already in one. This also arms the statement timeout if
1470 : : * necessary.
1471 : : */
1472 : 6119 : start_xact_command();
1473 : :
1474 : : /*
1475 : : * Switch to appropriate context for constructing parsetrees.
1476 : : *
1477 : : * We have two strategies depending on whether the prepared statement is
1478 : : * named or not. For a named prepared statement, we do parsing in
1479 : : * MessageContext and copy the finished trees into the prepared
1480 : : * statement's plancache entry; then the reset of MessageContext releases
1481 : : * temporary space used by parsing and rewriting. For an unnamed prepared
1482 : : * statement, we assume the statement isn't going to hang around long, so
1483 : : * getting rid of temp space quickly is probably not worth the costs of
1484 : : * copying parse trees. So in this case, we create the plancache entry's
1485 : : * query_context here, and do all the parsing work therein.
1486 : : */
1487 : 6119 : is_named = (stmt_name[0] != '\0');
1488 [ + + ]: 6119 : if (is_named)
1489 : : {
1490 : : /* Named prepared statement --- parse in MessageContext */
1491 : 2252 : oldcontext = MemoryContextSwitchTo(MessageContext);
1492 : : }
1493 : : else
1494 : : {
1495 : : /* Unnamed prepared statement --- release any prior unnamed stmt */
1496 : 3867 : drop_unnamed_stmt();
1497 : : /* Create context for parsing */
1498 : : unnamed_stmt_context =
1499 : 3867 : AllocSetContextCreate(MessageContext,
1500 : : "unnamed prepared statement",
1501 : : ALLOCSET_DEFAULT_SIZES);
1502 : 3867 : oldcontext = MemoryContextSwitchTo(unnamed_stmt_context);
1503 : : }
1504 : :
1505 : : /*
1506 : : * Do basic parsing of the query or queries (this should be safe even if
1507 : : * we are in aborted transaction state!)
1508 : : */
1509 : 6119 : parsetree_list = pg_parse_query(query_string);
1510 : :
1511 : : /*
1512 : : * We only allow a single user statement in a prepared statement. This is
1513 : : * mainly to keep the protocol simple --- otherwise we'd need to worry
1514 : : * about multiple result tupdescs and things like that.
1515 : : */
1516 [ + + ]: 6110 : if (list_length(parsetree_list) > 1)
1517 [ + - ]: 5 : ereport(ERROR,
1518 : : (errcode(ERRCODE_SYNTAX_ERROR),
1519 : : errmsg("cannot insert multiple commands into a prepared statement")));
1520 : :
1521 [ + + ]: 6105 : if (parsetree_list != NIL)
1522 : : {
1523 : 6101 : bool snapshot_set = false;
1524 : :
1525 : 6101 : raw_parse_tree = linitial_node(RawStmt, parsetree_list);
1526 : :
1527 : : /*
1528 : : * If we are in an aborted transaction, reject all commands except
1529 : : * COMMIT/ROLLBACK. It is important that this test occur before we
1530 : : * try to do parse analysis, rewrite, or planning, since all those
1531 : : * phases try to do database accesses, which may fail in abort state.
1532 : : * (It might be safe to allow some additional utility commands in this
1533 : : * state, but not many...)
1534 : : */
1535 [ + + ]: 6101 : if (IsAbortedTransactionBlockState() &&
1536 [ + + ]: 5 : !IsTransactionExitStmt(raw_parse_tree->stmt))
1537 [ + - ]: 1 : ereport(ERROR,
1538 : : (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
1539 : : errmsg("current transaction is aborted, "
1540 : : "commands ignored until end of transaction block")));
1541 : :
1542 : : /*
1543 : : * Create the CachedPlanSource before we do parse analysis, since it
1544 : : * needs to see the unmodified raw parse tree.
1545 : : */
1546 : 6100 : psrc = CreateCachedPlan(raw_parse_tree, query_string,
1547 : : CreateCommandTag(raw_parse_tree->stmt));
1548 : :
1549 : : /*
1550 : : * Set up a snapshot if parse analysis will need one.
1551 : : */
1552 [ + + ]: 6100 : if (analyze_requires_snapshot(raw_parse_tree))
1553 : : {
1554 : 5716 : PushActiveSnapshot(GetTransactionSnapshot());
1555 : 5716 : snapshot_set = true;
1556 : : }
1557 : :
1558 : : /*
1559 : : * Analyze and rewrite the query. Note that the originally specified
1560 : : * parameter set is not required to be complete, so we have to use
1561 : : * pg_analyze_and_rewrite_varparams().
1562 : : */
1563 : 6100 : querytree_list = pg_analyze_and_rewrite_varparams(raw_parse_tree,
1564 : : query_string,
1565 : : ¶mTypes,
1566 : : &numParams,
1567 : : NULL);
1568 : :
1569 : : /* Done with the snapshot used for parsing */
1570 [ + + ]: 6086 : if (snapshot_set)
1571 : 5702 : PopActiveSnapshot();
1572 : : }
1573 : : else
1574 : : {
1575 : : /* Empty input string. This is legal. */
1576 : 4 : raw_parse_tree = NULL;
1577 : 4 : psrc = CreateCachedPlan(raw_parse_tree, query_string,
1578 : : CMDTAG_UNKNOWN);
1579 : 4 : querytree_list = NIL;
1580 : : }
1581 : :
1582 : : /*
1583 : : * CachedPlanSource must be a direct child of MessageContext before we
1584 : : * reparent unnamed_stmt_context under it, else we have a disconnected
1585 : : * circular subgraph. Klugy, but less so than flipping contexts even more
1586 : : * above.
1587 : : */
1588 [ + + ]: 6090 : if (unnamed_stmt_context)
1589 : 3843 : MemoryContextSetParent(psrc->context, MessageContext);
1590 : :
1591 : : /* Finish filling in the CachedPlanSource */
1592 : 6090 : CompleteCachedPlan(psrc,
1593 : : querytree_list,
1594 : : unnamed_stmt_context,
1595 : : paramTypes,
1596 : : numParams,
1597 : : NULL,
1598 : : NULL,
1599 : : CURSOR_OPT_PARALLEL_OK, /* allow parallel mode */
1600 : : true); /* fixed result */
1601 : :
1602 : : /* If we got a cancel signal during analysis, quit */
1603 [ - + ]: 6090 : CHECK_FOR_INTERRUPTS();
1604 : :
1605 [ + + ]: 6090 : if (is_named)
1606 : : {
1607 : : /*
1608 : : * Store the query as a prepared statement.
1609 : : */
1610 : 2247 : StorePreparedStatement(stmt_name, psrc, false);
1611 : : }
1612 : : else
1613 : : {
1614 : : /*
1615 : : * We just save the CachedPlanSource into unnamed_stmt_psrc.
1616 : : */
1617 : 3843 : SaveCachedPlan(psrc);
1618 : 3843 : unnamed_stmt_psrc = psrc;
1619 : : }
1620 : :
1621 : 6090 : MemoryContextSwitchTo(oldcontext);
1622 : :
1623 : : /*
1624 : : * We do NOT close the open transaction command here; that only happens
1625 : : * when the client sends Sync. Instead, do CommandCounterIncrement just
1626 : : * in case something happened during parse/plan.
1627 : : */
1628 : 6090 : CommandCounterIncrement();
1629 : :
1630 : : /*
1631 : : * Send ParseComplete.
1632 : : */
1633 [ + - ]: 6090 : if (whereToSendOutput == DestRemote)
1634 : 6090 : pq_putemptymessage(PqMsg_ParseComplete);
1635 : :
1636 : : /*
1637 : : * Emit duration logging if appropriate.
1638 : : */
1639 [ - + + ]: 6090 : switch (check_log_duration(msec_str, false))
1640 : : {
1641 : 0 : case 1:
1642 [ # # ]: 0 : ereport(LOG,
1643 : : (errmsg("duration: %s ms", msec_str),
1644 : : errhidestmt(true)));
1645 : 0 : break;
1646 : 14 : case 2:
1647 : : {
1648 : 14 : char *truncated_stmt = truncate_query_log(query_string);
1649 : :
1650 [ + - + + : 14 : ereport(LOG,
+ + ]
1651 : : (errmsg("duration: %s ms parse %s: %s",
1652 : : msec_str,
1653 : : *stmt_name ? stmt_name : "<unnamed>",
1654 : : (truncated_stmt != NULL) ? truncated_stmt : query_string),
1655 : : errhidestmt(true)));
1656 : :
1657 [ + + ]: 14 : if (truncated_stmt != NULL)
1658 : 1 : pfree(truncated_stmt);
1659 : 14 : break;
1660 : : }
1661 : : }
1662 : :
1663 [ - + ]: 6090 : if (save_log_statement_stats)
1664 : 0 : ShowUsage("PARSE MESSAGE STATISTICS");
1665 : :
1666 : 6090 : debug_query_string = NULL;
1667 : 6090 : }
1668 : :
1669 : : /*
1670 : : * exec_bind_message
1671 : : *
1672 : : * Process a "Bind" message to create a portal from a prepared statement
1673 : : */
1674 : : static void
1675 : 12849 : exec_bind_message(StringInfo input_message)
1676 : : {
1677 : : const char *portal_name;
1678 : : const char *stmt_name;
1679 : : int numPFormats;
1680 : 12849 : int16 *pformats = NULL;
1681 : : int numParams;
1682 : : int numRFormats;
1683 : 12849 : int16 *rformats = NULL;
1684 : : CachedPlanSource *psrc;
1685 : : CachedPlan *cplan;
1686 : : Portal portal;
1687 : : char *query_string;
1688 : : char *saved_stmt_name;
1689 : : ParamListInfo params;
1690 : : MemoryContext oldContext;
1691 : 12849 : bool save_log_statement_stats = log_statement_stats;
1692 : 12849 : bool snapshot_set = false;
1693 : : char msec_str[32];
1694 : : ParamsErrorCbData params_data;
1695 : : ErrorContextCallback params_errcxt;
1696 : : ListCell *lc;
1697 : :
1698 : : /* Get the fixed part of the message */
1699 : 12849 : portal_name = pq_getmsgstring(input_message);
1700 : 12849 : stmt_name = pq_getmsgstring(input_message);
1701 : :
1702 [ - + - - : 12849 : ereport(DEBUG2,
- - ]
1703 : : (errmsg_internal("bind %s to %s",
1704 : : *portal_name ? portal_name : "<unnamed>",
1705 : : *stmt_name ? stmt_name : "<unnamed>")));
1706 : :
1707 : : /* Find prepared statement */
1708 [ + + ]: 12849 : if (stmt_name[0] != '\0')
1709 : : {
1710 : : PreparedStatement *pstmt;
1711 : :
1712 : 9054 : pstmt = FetchPreparedStatement(stmt_name, true);
1713 : 9049 : psrc = pstmt->plansource;
1714 : : }
1715 : : else
1716 : : {
1717 : : /* special-case the unnamed statement */
1718 : 3795 : psrc = unnamed_stmt_psrc;
1719 [ - + ]: 3795 : if (!psrc)
1720 [ # # ]: 0 : ereport(ERROR,
1721 : : (errcode(ERRCODE_UNDEFINED_PSTATEMENT),
1722 : : errmsg("unnamed prepared statement does not exist")));
1723 : : }
1724 : :
1725 : : /*
1726 : : * Report query to various monitoring facilities.
1727 : : */
1728 : 12844 : debug_query_string = psrc->query_string;
1729 : :
1730 : 12844 : pgstat_report_activity(STATE_RUNNING, psrc->query_string);
1731 : :
1732 [ + - + + : 25528 : foreach(lc, psrc->query_list)
+ + ]
1733 : : {
1734 : 12844 : Query *query = lfirst_node(Query, lc);
1735 : :
1736 [ + + ]: 12844 : if (query->queryId != INT64CONST(0))
1737 : : {
1738 : 160 : pgstat_report_query_id(query->queryId, false);
1739 : 160 : break;
1740 : : }
1741 : : }
1742 : :
1743 : 12844 : set_ps_display("BIND");
1744 : :
1745 [ - + ]: 12844 : if (save_log_statement_stats)
1746 : 0 : ResetUsage();
1747 : :
1748 : : /*
1749 : : * Start up a transaction command so we can call functions etc. (Note that
1750 : : * this will normally change current memory context.) Nothing happens if
1751 : : * we are already in one. This also arms the statement timeout if
1752 : : * necessary.
1753 : : */
1754 : 12844 : start_xact_command();
1755 : :
1756 : : /* Switch back to message context */
1757 : 12844 : MemoryContextSwitchTo(MessageContext);
1758 : :
1759 : : /* Get the parameter format codes */
1760 : 12844 : numPFormats = pq_getmsgint(input_message, 2);
1761 [ + + ]: 12844 : if (numPFormats > 0)
1762 : : {
1763 : 2564 : pformats = palloc_array(int16, numPFormats);
1764 [ + + ]: 6048 : for (int i = 0; i < numPFormats; i++)
1765 : 3484 : pformats[i] = pq_getmsgint(input_message, 2);
1766 : : }
1767 : :
1768 : : /* Get the parameter value count */
1769 : 12844 : numParams = pq_getmsgint(input_message, 2);
1770 : :
1771 [ + + - + ]: 12844 : if (numPFormats > 1 && numPFormats != numParams)
1772 [ # # ]: 0 : ereport(ERROR,
1773 : : (errcode(ERRCODE_PROTOCOL_VIOLATION),
1774 : : errmsg("bind message has %d parameter formats but %d parameters",
1775 : : numPFormats, numParams)));
1776 : :
1777 [ + + ]: 12844 : if (numParams != psrc->num_params)
1778 [ + - ]: 40 : ereport(ERROR,
1779 : : (errcode(ERRCODE_PROTOCOL_VIOLATION),
1780 : : errmsg("bind message supplies %d parameters, but prepared statement \"%s\" requires %d",
1781 : : numParams, stmt_name, psrc->num_params)));
1782 : :
1783 : : /*
1784 : : * If we are in aborted transaction state, the only portals we can
1785 : : * actually run are those containing COMMIT or ROLLBACK commands. We
1786 : : * disallow binding anything else to avoid problems with infrastructure
1787 : : * that expects to run inside a valid transaction. We also disallow
1788 : : * binding any parameters, since we can't risk calling user-defined I/O
1789 : : * functions.
1790 : : */
1791 [ + + ]: 12804 : if (IsAbortedTransactionBlockState() &&
1792 [ + - + - ]: 10 : (!(psrc->raw_parse_tree &&
1793 [ - + ]: 10 : IsTransactionExitStmt(psrc->raw_parse_tree->stmt)) ||
1794 : : numParams != 0))
1795 [ # # ]: 0 : ereport(ERROR,
1796 : : (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
1797 : : errmsg("current transaction is aborted, "
1798 : : "commands ignored until end of transaction block")));
1799 : :
1800 : : /*
1801 : : * Create the portal. Allow silent replacement of an existing portal only
1802 : : * if the unnamed portal is specified.
1803 : : */
1804 [ + - ]: 12804 : if (portal_name[0] == '\0')
1805 : 12804 : portal = CreatePortal(portal_name, true, true);
1806 : : else
1807 : 0 : portal = CreatePortal(portal_name, false, false);
1808 : :
1809 : 12804 : INJECTION_POINT("bind-portal-created", NULL);
1810 : :
1811 : : /*
1812 : : * Prepare to copy stuff into the portal's memory context. We do all this
1813 : : * copying first, because it could possibly fail (out-of-memory) and we
1814 : : * don't want a failure to occur between GetCachedPlan and
1815 : : * PortalDefineQuery; that would result in leaking our plancache refcount.
1816 : : */
1817 : 12800 : oldContext = MemoryContextSwitchTo(portal->portalContext);
1818 : :
1819 : : /* Copy the plan's query string into the portal */
1820 : 12800 : query_string = pstrdup(psrc->query_string);
1821 : :
1822 : : /* Likewise make a copy of the statement name, unless it's unnamed */
1823 [ + + ]: 12800 : if (stmt_name[0])
1824 : 9045 : saved_stmt_name = pstrdup(stmt_name);
1825 : : else
1826 : 3755 : saved_stmt_name = NULL;
1827 : :
1828 : : /*
1829 : : * Set a snapshot if we have parameters to fetch (since the input
1830 : : * functions might need it) or the query isn't a utility command (and
1831 : : * hence could require redoing parse analysis and planning). We keep the
1832 : : * snapshot active till we're done, so that plancache.c doesn't have to
1833 : : * take new ones.
1834 : : */
1835 [ + + ]: 12800 : if (numParams > 0 ||
1836 [ + - + + ]: 4488 : (psrc->raw_parse_tree &&
1837 : 2244 : analyze_requires_snapshot(psrc->raw_parse_tree)))
1838 : : {
1839 : 11747 : PushActiveSnapshot(GetTransactionSnapshot());
1840 : 11747 : snapshot_set = true;
1841 : : }
1842 : :
1843 : : /*
1844 : : * Fetch parameters, if any, and store in the portal's memory context.
1845 : : */
1846 [ + + ]: 12800 : if (numParams > 0)
1847 : : {
1848 : 10556 : char **knownTextValues = NULL; /* allocate on first use */
1849 : : BindParamCbData one_param_data;
1850 : :
1851 : : /*
1852 : : * Set up an error callback so that if there's an error in this phase,
1853 : : * we can report the specific parameter causing the problem.
1854 : : */
1855 : 10556 : one_param_data.portalName = portal->name;
1856 : 10556 : one_param_data.paramno = -1;
1857 : 10556 : one_param_data.paramval = NULL;
1858 : 10556 : params_errcxt.previous = error_context_stack;
1859 : 10556 : params_errcxt.callback = bind_param_error_callback;
1860 : 10556 : params_errcxt.arg = &one_param_data;
1861 : 10556 : error_context_stack = ¶ms_errcxt;
1862 : :
1863 : 10556 : params = makeParamList(numParams);
1864 : :
1865 [ + + ]: 28914 : for (int paramno = 0; paramno < numParams; paramno++)
1866 : : {
1867 : 18359 : Oid ptype = psrc->param_types[paramno];
1868 : : int32 plength;
1869 : : Datum pval;
1870 : : bool isNull;
1871 : : StringInfoData pbuf;
1872 : : char csave;
1873 : : int16 pformat;
1874 : :
1875 : 18359 : one_param_data.paramno = paramno;
1876 : 18359 : one_param_data.paramval = NULL;
1877 : :
1878 : 18359 : plength = pq_getmsgint(input_message, 4);
1879 : 18359 : isNull = (plength == -1);
1880 : :
1881 [ + + ]: 18359 : if (!isNull)
1882 : : {
1883 : : char *pvalue;
1884 : :
1885 : : /*
1886 : : * Rather than copying data around, we just initialize a
1887 : : * StringInfo pointing to the correct portion of the message
1888 : : * buffer. We assume we can scribble on the message buffer to
1889 : : * add a trailing NUL which is required for the input function
1890 : : * call.
1891 : : */
1892 : 17750 : pvalue = unconstify(char *, pq_getmsgbytes(input_message, plength));
1893 : 17750 : csave = pvalue[plength];
1894 : 17750 : pvalue[plength] = '\0';
1895 : 17750 : initReadOnlyStringInfo(&pbuf, pvalue, plength);
1896 : : }
1897 : : else
1898 : : {
1899 : 609 : pbuf.data = NULL; /* keep compiler quiet */
1900 : 609 : csave = 0;
1901 : : }
1902 : :
1903 [ + + ]: 18359 : if (numPFormats > 1)
1904 : 1792 : pformat = pformats[paramno];
1905 [ + + ]: 16567 : else if (numPFormats > 0)
1906 : 1692 : pformat = pformats[0];
1907 : : else
1908 : 14875 : pformat = 0; /* default = text */
1909 : :
1910 [ + + ]: 18359 : if (pformat == 0) /* text mode */
1911 : : {
1912 : : Oid typinput;
1913 : : Oid typioparam;
1914 : : char *pstring;
1915 : :
1916 : 18333 : getTypeInputInfo(ptype, &typinput, &typioparam);
1917 : :
1918 : : /*
1919 : : * We have to do encoding conversion before calling the
1920 : : * typinput routine.
1921 : : */
1922 [ + + ]: 18333 : if (isNull)
1923 : 609 : pstring = NULL;
1924 : : else
1925 : 17724 : pstring = pg_client_to_server(pbuf.data, plength);
1926 : :
1927 : : /* Now we can log the input string in case of error */
1928 : 18333 : one_param_data.paramval = pstring;
1929 : :
1930 : 18333 : pval = OidInputFunctionCall(typinput, pstring, typioparam, -1);
1931 : :
1932 : 18332 : one_param_data.paramval = NULL;
1933 : :
1934 : : /*
1935 : : * If we might need to log parameters later, save a copy of
1936 : : * the converted string in MessageContext; then free the
1937 : : * result of encoding conversion, if any was done.
1938 : : */
1939 [ + + ]: 18332 : if (pstring)
1940 : : {
1941 [ + + ]: 17723 : if (log_parameter_max_length_on_error != 0)
1942 : : {
1943 : : MemoryContext oldcxt;
1944 : :
1945 : 7 : oldcxt = MemoryContextSwitchTo(MessageContext);
1946 : :
1947 [ + + ]: 7 : if (knownTextValues == NULL)
1948 : 5 : knownTextValues = palloc0_array(char *, numParams);
1949 : :
1950 [ + + ]: 7 : if (log_parameter_max_length_on_error < 0)
1951 : 4 : knownTextValues[paramno] = pstrdup(pstring);
1952 : : else
1953 : : {
1954 : : /*
1955 : : * We can trim the saved string, knowing that we
1956 : : * won't print all of it. But we must copy at
1957 : : * least two more full characters than
1958 : : * BuildParamLogString wants to use; otherwise it
1959 : : * might fail to include the trailing ellipsis.
1960 : : */
1961 : 3 : knownTextValues[paramno] =
1962 : 3 : pnstrdup(pstring,
1963 : : log_parameter_max_length_on_error
1964 : 3 : + 2 * MAX_MULTIBYTE_CHAR_LEN);
1965 : : }
1966 : :
1967 : 7 : MemoryContextSwitchTo(oldcxt);
1968 : : }
1969 [ - + ]: 17723 : if (pstring != pbuf.data)
1970 : 0 : pfree(pstring);
1971 : : }
1972 : : }
1973 [ + - ]: 26 : else if (pformat == 1) /* binary mode */
1974 : : {
1975 : : Oid typreceive;
1976 : : Oid typioparam;
1977 : : StringInfo bufptr;
1978 : :
1979 : : /*
1980 : : * Call the parameter type's binary input converter
1981 : : */
1982 : 26 : getTypeBinaryInputInfo(ptype, &typreceive, &typioparam);
1983 : :
1984 [ - + ]: 26 : if (isNull)
1985 : 0 : bufptr = NULL;
1986 : : else
1987 : 26 : bufptr = &pbuf;
1988 : :
1989 : 26 : pval = OidReceiveFunctionCall(typreceive, bufptr, typioparam, -1);
1990 : :
1991 : : /* Trouble if it didn't eat the whole buffer */
1992 [ + - - + ]: 26 : if (!isNull && pbuf.cursor != pbuf.len)
1993 [ # # ]: 0 : ereport(ERROR,
1994 : : (errcode(ERRCODE_INVALID_BINARY_REPRESENTATION),
1995 : : errmsg("incorrect binary data format in bind parameter %d",
1996 : : paramno + 1)));
1997 : : }
1998 : : else
1999 : : {
2000 [ # # ]: 0 : ereport(ERROR,
2001 : : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
2002 : : errmsg("unsupported format code: %d",
2003 : : pformat)));
2004 : : pval = 0; /* keep compiler quiet */
2005 : : }
2006 : :
2007 : : /* Restore message buffer contents */
2008 [ + + ]: 18358 : if (!isNull)
2009 : 17749 : pbuf.data[plength] = csave;
2010 : :
2011 : 18358 : params->params[paramno].value = pval;
2012 : 18358 : params->params[paramno].isnull = isNull;
2013 : :
2014 : : /*
2015 : : * We mark the params as CONST. This ensures that any custom plan
2016 : : * makes full use of the parameter values.
2017 : : */
2018 : 18358 : params->params[paramno].pflags = PARAM_FLAG_CONST;
2019 : 18358 : params->params[paramno].ptype = ptype;
2020 : : }
2021 : :
2022 : : /* Pop the per-parameter error callback */
2023 : 10555 : error_context_stack = error_context_stack->previous;
2024 : :
2025 : : /*
2026 : : * Once all parameters have been received, prepare for printing them
2027 : : * in future errors, if configured to do so. (This is saved in the
2028 : : * portal, so that they'll appear when the query is executed later.)
2029 : : */
2030 [ + + ]: 10555 : if (log_parameter_max_length_on_error != 0)
2031 : 4 : params->paramValuesStr =
2032 : 4 : BuildParamLogString(params,
2033 : : knownTextValues,
2034 : : log_parameter_max_length_on_error);
2035 : : }
2036 : : else
2037 : 2244 : params = NULL;
2038 : :
2039 : : /* Done storing stuff in portal's context */
2040 : 12799 : MemoryContextSwitchTo(oldContext);
2041 : :
2042 : : /*
2043 : : * Set up another error callback so that all the parameters are logged if
2044 : : * we get an error during the rest of the BIND processing.
2045 : : */
2046 : 12799 : params_data.portalName = portal->name;
2047 : 12799 : params_data.params = params;
2048 : 12799 : params_errcxt.previous = error_context_stack;
2049 : 12799 : params_errcxt.callback = ParamsErrorCallback;
2050 : 12799 : params_errcxt.arg = ¶ms_data;
2051 : 12799 : error_context_stack = ¶ms_errcxt;
2052 : :
2053 : : /* Get the result format codes */
2054 : 12799 : numRFormats = pq_getmsgint(input_message, 2);
2055 [ + - ]: 12799 : if (numRFormats > 0)
2056 : : {
2057 : 12799 : rformats = palloc_array(int16, numRFormats);
2058 [ + + ]: 25598 : for (int i = 0; i < numRFormats; i++)
2059 : 12799 : rformats[i] = pq_getmsgint(input_message, 2);
2060 : : }
2061 : :
2062 : 12799 : pq_getmsgend(input_message);
2063 : :
2064 : : /*
2065 : : * Obtain a plan from the CachedPlanSource. Any cruft from (re)planning
2066 : : * will be generated in MessageContext. The plan refcount will be
2067 : : * assigned to the Portal, so it will be released at portal destruction.
2068 : : */
2069 : 12799 : cplan = GetCachedPlan(psrc, params, NULL, NULL);
2070 : :
2071 : : /*
2072 : : * Now we can define the portal.
2073 : : *
2074 : : * DO NOT put any code that could possibly throw an error between the
2075 : : * above GetCachedPlan call and here.
2076 : : */
2077 : 12798 : PortalDefineQuery(portal,
2078 : : saved_stmt_name,
2079 : : query_string,
2080 : : psrc->commandTag,
2081 : : cplan->stmt_list,
2082 : : cplan);
2083 : :
2084 : 12798 : INJECTION_POINT("bind-portal-defined", NULL);
2085 : :
2086 : : /* Portal is defined, set the plan ID based on its contents. */
2087 [ + - + + : 25588 : foreach(lc, portal->stmts)
+ + ]
2088 : : {
2089 : 12794 : PlannedStmt *plan = lfirst_node(PlannedStmt, lc);
2090 : :
2091 [ - + ]: 12794 : if (plan->planId != INT64CONST(0))
2092 : : {
2093 : 0 : pgstat_report_plan_id(plan->planId, false);
2094 : 0 : break;
2095 : : }
2096 : : }
2097 : :
2098 : : /* Done with the snapshot used for parameter I/O and parsing/planning */
2099 [ + + ]: 12794 : if (snapshot_set)
2100 : 11743 : PopActiveSnapshot();
2101 : :
2102 : : /*
2103 : : * And we're ready to start portal execution.
2104 : : */
2105 : 12794 : PortalStart(portal, params, 0, InvalidSnapshot);
2106 : :
2107 : : /*
2108 : : * Apply the result format requests to the portal.
2109 : : */
2110 : 12794 : PortalSetResultFormat(portal, numRFormats, rformats);
2111 : :
2112 : : /*
2113 : : * Done binding; remove the parameters error callback. Entries emitted
2114 : : * later determine independently whether to log the parameters or not.
2115 : : */
2116 : 12794 : error_context_stack = error_context_stack->previous;
2117 : :
2118 : : /*
2119 : : * Send BindComplete.
2120 : : */
2121 [ + - ]: 12794 : if (whereToSendOutput == DestRemote)
2122 : 12794 : pq_putemptymessage(PqMsg_BindComplete);
2123 : :
2124 : : /*
2125 : : * Emit duration logging if appropriate.
2126 : : */
2127 [ - + + ]: 12794 : switch (check_log_duration(msec_str, false))
2128 : : {
2129 : 0 : case 1:
2130 [ # # ]: 0 : ereport(LOG,
2131 : : (errmsg("duration: %s ms", msec_str),
2132 : : errhidestmt(true)));
2133 : 0 : break;
2134 : 13 : case 2:
2135 : : {
2136 : 13 : char *truncated_stmt = truncate_query_log(psrc->query_string);
2137 : :
2138 [ + - + + : 13 : ereport(LOG,
- + - + +
+ ]
2139 : : (errmsg("duration: %s ms bind %s%s%s: %s",
2140 : : msec_str,
2141 : : *stmt_name ? stmt_name : "<unnamed>",
2142 : : *portal_name ? "/" : "",
2143 : : *portal_name ? portal_name : "",
2144 : : (truncated_stmt != NULL) ? truncated_stmt : psrc->query_string),
2145 : : errhidestmt(true),
2146 : : errdetail_params(params)));
2147 : :
2148 [ + + ]: 13 : if (truncated_stmt != NULL)
2149 : 1 : pfree(truncated_stmt);
2150 : 13 : break;
2151 : : }
2152 : : }
2153 : :
2154 [ - + ]: 12794 : if (save_log_statement_stats)
2155 : 0 : ShowUsage("BIND MESSAGE STATISTICS");
2156 : :
2157 : : valgrind_report_error_query(debug_query_string);
2158 : :
2159 : 12794 : debug_query_string = NULL;
2160 : 12794 : }
2161 : :
2162 : : /*
2163 : : * exec_execute_message
2164 : : *
2165 : : * Process an "Execute" message for a portal
2166 : : */
2167 : : static void
2168 : 12794 : exec_execute_message(const char *portal_name, long max_rows)
2169 : : {
2170 : : CommandDest dest;
2171 : : DestReceiver *receiver;
2172 : : Portal portal;
2173 : : bool completed;
2174 : : QueryCompletion qc;
2175 : : const char *sourceText;
2176 : : const char *prepStmtName;
2177 : : ParamListInfo portalParams;
2178 : 12794 : bool save_log_statement_stats = log_statement_stats;
2179 : : bool is_xact_command;
2180 : : bool execute_is_fetch;
2181 : 12794 : bool was_logged = false;
2182 : : char msec_str[32];
2183 : : ParamsErrorCbData params_data;
2184 : : ErrorContextCallback params_errcxt;
2185 : : const char *cmdtagname;
2186 : : size_t cmdtaglen;
2187 : : ListCell *lc;
2188 : :
2189 : : /* Adjust destination to tell printtup.c what to do */
2190 : 12794 : dest = whereToSendOutput;
2191 [ + - ]: 12794 : if (dest == DestRemote)
2192 : 12794 : dest = DestRemoteExecute;
2193 : :
2194 : 12794 : portal = GetPortalByName(portal_name);
2195 [ - + ]: 12794 : if (!PortalIsValid(portal))
2196 [ # # ]: 0 : ereport(ERROR,
2197 : : (errcode(ERRCODE_UNDEFINED_CURSOR),
2198 : : errmsg("portal \"%s\" does not exist", portal_name)));
2199 : :
2200 : : /*
2201 : : * If the original query was a null string, just return
2202 : : * EmptyQueryResponse.
2203 : : */
2204 [ - + ]: 12794 : if (portal->commandTag == CMDTAG_UNKNOWN)
2205 : : {
2206 : : Assert(portal->stmts == NIL);
2207 : 0 : NullCommand(dest);
2208 : 0 : return;
2209 : : }
2210 : :
2211 : : /* Does the portal contain a transaction command? */
2212 : 12794 : is_xact_command = IsTransactionStmtList(portal->stmts);
2213 : :
2214 : : /*
2215 : : * We must copy the sourceText and prepStmtName into MessageContext in
2216 : : * case the portal is destroyed during finish_xact_command. We do not
2217 : : * make a copy of the portalParams though, preferring to just not print
2218 : : * them in that case.
2219 : : */
2220 : 12794 : sourceText = pstrdup(portal->sourceText);
2221 [ + + ]: 12794 : if (portal->prepStmtName)
2222 : 9044 : prepStmtName = pstrdup(portal->prepStmtName);
2223 : : else
2224 : 3750 : prepStmtName = "<unnamed>";
2225 : 12794 : portalParams = portal->portalParams;
2226 : :
2227 : : /*
2228 : : * Report query to various monitoring facilities.
2229 : : */
2230 : 12794 : debug_query_string = sourceText;
2231 : :
2232 : 12794 : pgstat_report_activity(STATE_RUNNING, sourceText);
2233 : :
2234 [ + - + + : 25438 : foreach(lc, portal->stmts)
+ + ]
2235 : : {
2236 : 12794 : PlannedStmt *stmt = lfirst_node(PlannedStmt, lc);
2237 : :
2238 [ + + ]: 12794 : if (stmt->queryId != INT64CONST(0))
2239 : : {
2240 : 150 : pgstat_report_query_id(stmt->queryId, false);
2241 : 150 : break;
2242 : : }
2243 : : }
2244 : :
2245 [ + - + + : 25588 : foreach(lc, portal->stmts)
+ + ]
2246 : : {
2247 : 12794 : PlannedStmt *stmt = lfirst_node(PlannedStmt, lc);
2248 : :
2249 [ - + ]: 12794 : if (stmt->planId != INT64CONST(0))
2250 : : {
2251 : 0 : pgstat_report_plan_id(stmt->planId, false);
2252 : 0 : break;
2253 : : }
2254 : : }
2255 : :
2256 : 12794 : cmdtagname = GetCommandTagNameAndLen(portal->commandTag, &cmdtaglen);
2257 : :
2258 : 12794 : set_ps_display_with_len(cmdtagname, cmdtaglen);
2259 : :
2260 [ - + ]: 12794 : if (save_log_statement_stats)
2261 : 0 : ResetUsage();
2262 : :
2263 : 12794 : BeginCommand(portal->commandTag, dest);
2264 : :
2265 : : /*
2266 : : * Create dest receiver in MessageContext (we don't want it in transaction
2267 : : * context, because that may get deleted if portal contains VACUUM).
2268 : : */
2269 : 12794 : receiver = CreateDestReceiver(dest);
2270 [ + - ]: 12794 : if (dest == DestRemoteExecute)
2271 : 12794 : SetRemoteDestReceiverParams(receiver, portal);
2272 : :
2273 : : /*
2274 : : * Ensure we are in a transaction command (this should normally be the
2275 : : * case already due to prior BIND).
2276 : : */
2277 : 12794 : start_xact_command();
2278 : :
2279 : : /*
2280 : : * If we re-issue an Execute protocol request against an existing portal,
2281 : : * then we are only fetching more rows rather than completely re-executing
2282 : : * the query from the start. atStart is never reset for a v3 portal, so we
2283 : : * are safe to use this check.
2284 : : */
2285 : 12794 : execute_is_fetch = !portal->atStart;
2286 : :
2287 : : /* Log immediately if dictated by log_statement */
2288 [ + + ]: 12794 : if (check_log_statement(portal->stmts))
2289 : : {
2290 : 4012 : char *truncated_source = truncate_query_log(sourceText);
2291 : :
2292 [ + - + + : 4012 : ereport(LOG,
- + - + -
+ ]
2293 : : (errmsg("%s %s%s%s: %s",
2294 : : execute_is_fetch ?
2295 : : _("execute fetch from") :
2296 : : _("execute"),
2297 : : prepStmtName,
2298 : : *portal_name ? "/" : "",
2299 : : *portal_name ? portal_name : "",
2300 : : (truncated_source != NULL) ? truncated_source : sourceText),
2301 : : errhidestmt(true),
2302 : : errdetail_params(portalParams)));
2303 : 4012 : was_logged = true;
2304 : :
2305 [ + + ]: 4012 : if (truncated_source != NULL)
2306 : 1 : pfree(truncated_source);
2307 : : }
2308 : :
2309 : : /*
2310 : : * If we are in aborted transaction state, the only portals we can
2311 : : * actually run are those containing COMMIT or ROLLBACK commands.
2312 : : */
2313 [ + + ]: 12794 : if (IsAbortedTransactionBlockState() &&
2314 [ - + ]: 1 : !IsTransactionExitStmtList(portal->stmts))
2315 [ # # ]: 0 : ereport(ERROR,
2316 : : (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
2317 : : errmsg("current transaction is aborted, "
2318 : : "commands ignored until end of transaction block")));
2319 : :
2320 : : /* Check for cancel signal before we start execution */
2321 [ - + ]: 12794 : CHECK_FOR_INTERRUPTS();
2322 : :
2323 : : /*
2324 : : * Okay to run the portal. Set the error callback so that parameters are
2325 : : * logged. The parameters must have been saved during the bind phase.
2326 : : */
2327 : 12794 : params_data.portalName = portal->name;
2328 : 12794 : params_data.params = portalParams;
2329 : 12794 : params_errcxt.previous = error_context_stack;
2330 : 12794 : params_errcxt.callback = ParamsErrorCallback;
2331 : 12794 : params_errcxt.arg = ¶ms_data;
2332 : 12794 : error_context_stack = ¶ms_errcxt;
2333 : :
2334 [ + - ]: 12794 : if (max_rows <= 0)
2335 : 12794 : max_rows = FETCH_ALL;
2336 : :
2337 : 12794 : completed = PortalRun(portal,
2338 : : max_rows,
2339 : : true, /* always top level */
2340 : : receiver,
2341 : : receiver,
2342 : : &qc);
2343 : :
2344 : 12740 : receiver->rDestroy(receiver);
2345 : :
2346 : : /* Done executing; remove the params error callback */
2347 : 12740 : error_context_stack = error_context_stack->previous;
2348 : :
2349 [ + - ]: 12740 : if (completed)
2350 : : {
2351 [ + + - + ]: 12740 : if (is_xact_command || (MyXactFlags & XACT_FLAGS_NEEDIMMEDIATECOMMIT))
2352 : : {
2353 : : /*
2354 : : * If this was a transaction control statement, commit it. We
2355 : : * will start a new xact command for the next command (if any).
2356 : : * Likewise if the statement required immediate commit. Without
2357 : : * this provision, we wouldn't force commit until Sync is
2358 : : * received, which creates a hazard if the client tries to
2359 : : * pipeline immediate-commit statements.
2360 : : */
2361 : 482 : finish_xact_command();
2362 : :
2363 : : /*
2364 : : * These commands typically don't have any parameters, and even if
2365 : : * one did we couldn't print them now because the storage went
2366 : : * away during finish_xact_command. So pretend there were none.
2367 : : */
2368 : 482 : portalParams = NULL;
2369 : : }
2370 : : else
2371 : : {
2372 : : /*
2373 : : * We need a CommandCounterIncrement after every query, except
2374 : : * those that start or end a transaction block.
2375 : : */
2376 : 12258 : CommandCounterIncrement();
2377 : :
2378 : : /*
2379 : : * Set XACT_FLAGS_PIPELINING whenever we complete an Execute
2380 : : * message without immediately committing the transaction.
2381 : : */
2382 : 12258 : MyXactFlags |= XACT_FLAGS_PIPELINING;
2383 : :
2384 : : /*
2385 : : * Disable statement timeout whenever we complete an Execute
2386 : : * message. The next protocol message will start a fresh timeout.
2387 : : */
2388 : 12258 : disable_statement_timeout();
2389 : : }
2390 : :
2391 : : /* Send appropriate CommandComplete to client */
2392 : 12740 : EndCommand(&qc, dest, false);
2393 : : }
2394 : : else
2395 : : {
2396 : : /* Portal run not complete, so send PortalSuspended */
2397 [ # # ]: 0 : if (whereToSendOutput == DestRemote)
2398 : 0 : pq_putemptymessage(PqMsg_PortalSuspended);
2399 : :
2400 : : /*
2401 : : * Set XACT_FLAGS_PIPELINING whenever we suspend an Execute message,
2402 : : * too.
2403 : : */
2404 : 0 : MyXactFlags |= XACT_FLAGS_PIPELINING;
2405 : : }
2406 : :
2407 : : /*
2408 : : * Emit duration logging if appropriate.
2409 : : */
2410 [ + + + ]: 12740 : switch (check_log_duration(msec_str, was_logged))
2411 : : {
2412 : 8 : case 1:
2413 [ + - ]: 8 : ereport(LOG,
2414 : : (errmsg("duration: %s ms", msec_str),
2415 : : errhidestmt(true)));
2416 : 8 : break;
2417 : 1 : case 2:
2418 : : {
2419 : 1 : char *truncated_source = truncate_query_log(sourceText);
2420 : :
2421 [ + - + - : 1 : ereport(LOG,
- + - + -
+ ]
2422 : : (errmsg("duration: %s ms %s %s%s%s: %s",
2423 : : msec_str,
2424 : : execute_is_fetch ?
2425 : : _("execute fetch from") :
2426 : : _("execute"),
2427 : : prepStmtName,
2428 : : *portal_name ? "/" : "",
2429 : : *portal_name ? portal_name : "",
2430 : : (truncated_source != NULL) ? truncated_source : sourceText),
2431 : : errhidestmt(true),
2432 : : errdetail_params(portalParams)));
2433 : :
2434 [ + - ]: 1 : if (truncated_source != NULL)
2435 : 1 : pfree(truncated_source);
2436 : 1 : break;
2437 : : }
2438 : : }
2439 : :
2440 [ - + ]: 12740 : if (save_log_statement_stats)
2441 : 0 : ShowUsage("EXECUTE MESSAGE STATISTICS");
2442 : :
2443 : : valgrind_report_error_query(debug_query_string);
2444 : :
2445 : 12740 : debug_query_string = NULL;
2446 : : }
2447 : :
2448 : : /*
2449 : : * check_log_statement
2450 : : * Determine whether command should be logged because of log_statement
2451 : : *
2452 : : * stmt_list can be either raw grammar output or a list of planned
2453 : : * statements
2454 : : */
2455 : : static bool
2456 : 452301 : check_log_statement(List *stmt_list)
2457 : : {
2458 : : ListCell *stmt_item;
2459 : :
2460 [ + + ]: 452301 : if (log_statement == LOGSTMT_NONE)
2461 : 240557 : return false;
2462 [ + - ]: 211744 : if (log_statement == LOGSTMT_ALL)
2463 : 211744 : return true;
2464 : :
2465 : : /* Else we have to inspect the statement(s) to see whether to log */
2466 [ # # # # : 0 : foreach(stmt_item, stmt_list)
# # ]
2467 : : {
2468 : 0 : Node *stmt = (Node *) lfirst(stmt_item);
2469 : :
2470 [ # # ]: 0 : if (GetCommandLogLevel(stmt) <= log_statement)
2471 : 0 : return true;
2472 : : }
2473 : :
2474 : 0 : return false;
2475 : : }
2476 : :
2477 : : /*
2478 : : * check_log_duration
2479 : : * Determine whether current command's duration should be logged
2480 : : * We also check if this statement in this transaction must be logged
2481 : : * (regardless of its duration).
2482 : : *
2483 : : * Returns:
2484 : : * 0 if no logging is needed
2485 : : * 1 if just the duration should be logged
2486 : : * 2 if duration and query details should be logged
2487 : : *
2488 : : * If logging is needed, the duration in msec is formatted into msec_str[],
2489 : : * which must be a 32-byte buffer.
2490 : : *
2491 : : * was_logged should be true if caller already logged query details (this
2492 : : * essentially prevents 2 from being returned).
2493 : : */
2494 : : int
2495 : 441325 : check_log_duration(char *msec_str, bool was_logged)
2496 : : {
2497 [ + - + - ]: 441325 : if (log_duration || log_min_duration_sample >= 0 ||
2498 [ + + - + ]: 441325 : log_min_duration_statement >= 0 || xact_is_sampled)
2499 : : {
2500 : : long secs;
2501 : : int usecs;
2502 : : int msecs;
2503 : : bool exceeded_duration;
2504 : : bool exceeded_sample_duration;
2505 : 56 : bool in_sample = false;
2506 : :
2507 : 56 : TimestampDifference(GetCurrentStatementStartTimestamp(),
2508 : : GetCurrentTimestamp(),
2509 : : &secs, &usecs);
2510 : 56 : msecs = usecs / 1000;
2511 : :
2512 : : /*
2513 : : * This odd-looking test for log_min_duration_* being exceeded is
2514 : : * designed to avoid integer overflow with very long durations: don't
2515 : : * compute secs * 1000 until we've verified it will fit in int.
2516 : : */
2517 [ - + ]: 56 : exceeded_duration = (log_min_duration_statement == 0 ||
2518 [ # # ]: 0 : (log_min_duration_statement > 0 &&
2519 [ # # ]: 0 : (secs > log_min_duration_statement / 1000 ||
2520 [ # # ]: 0 : secs * 1000 + msecs >= log_min_duration_statement)));
2521 : :
2522 [ + - ]: 112 : exceeded_sample_duration = (log_min_duration_sample == 0 ||
2523 [ - + ]: 56 : (log_min_duration_sample > 0 &&
2524 [ # # ]: 0 : (secs > log_min_duration_sample / 1000 ||
2525 [ # # ]: 0 : secs * 1000 + msecs >= log_min_duration_sample)));
2526 : :
2527 : : /*
2528 : : * Do not log if log_statement_sample_rate = 0. Log a sample if
2529 : : * log_statement_sample_rate <= 1 and avoid unnecessary PRNG call if
2530 : : * log_statement_sample_rate = 1.
2531 : : */
2532 [ - + ]: 56 : if (exceeded_sample_duration)
2533 [ # # ]: 0 : in_sample = log_statement_sample_rate != 0 &&
2534 [ # # ]: 0 : (log_statement_sample_rate == 1 ||
2535 [ # # ]: 0 : pg_prng_double(&pg_global_prng_state) <= log_statement_sample_rate);
2536 : :
2537 [ - + - - : 56 : if (exceeded_duration || in_sample || log_duration || xact_is_sampled)
- - - - ]
2538 : : {
2539 : 56 : snprintf(msec_str, 32, "%ld.%03d",
2540 : 56 : secs * 1000 + msecs, usecs % 1000);
2541 [ - + - - : 56 : if ((exceeded_duration || in_sample || xact_is_sampled) && !was_logged)
- - + + ]
2542 : 56 : return 2;
2543 : : else
2544 : 26 : return 1;
2545 : : }
2546 : : }
2547 : :
2548 : 441269 : return 0;
2549 : : }
2550 : :
2551 : : /*
2552 : : * truncate_query_log
2553 : : * Truncate query string if needed for logging
2554 : : *
2555 : : * Returns a palloc'd copy of the query truncated for logging, with an
2556 : : * ellipsis appended if truncation occurs, or NULL if no truncation is
2557 : : * required.
2558 : : */
2559 : : static char *
2560 : 217904 : truncate_query_log(const char *query)
2561 : : {
2562 : : size_t query_len;
2563 : : size_t truncated_len;
2564 : : char *truncated_query;
2565 : :
2566 : : /* Truncation is disabled when the limit is negative */
2567 [ + - + + ]: 217904 : if (!query || log_statement_max_length < 0)
2568 : 217890 : return NULL;
2569 : :
2570 : 14 : query_len = strnlen(query,
2571 : 14 : (size_t) log_statement_max_length +
2572 : : MAX_MULTIBYTE_CHAR_LEN);
2573 : :
2574 : : /*
2575 : : * No need to allocate a truncated copy if the query is shorter than
2576 : : * log_statement_max_length.
2577 : : */
2578 [ - + ]: 14 : if (query_len <= (size_t) log_statement_max_length)
2579 : 0 : return NULL;
2580 : :
2581 : : /* Truncate at a multibyte character boundary */
2582 : 14 : truncated_len = pg_mbcliplen(query, query_len, log_statement_max_length);
2583 : 14 : truncated_query = (char *) palloc(truncated_len + 4);
2584 : 14 : memcpy(truncated_query, query, truncated_len);
2585 : 14 : memcpy(truncated_query + truncated_len, "...", 3);
2586 : 14 : truncated_query[truncated_len + 3] = '\0';
2587 : :
2588 : 14 : return truncated_query;
2589 : : }
2590 : :
2591 : : /*
2592 : : * errdetail_execute
2593 : : *
2594 : : * Add an errdetail() line showing the query referenced by an EXECUTE, if any.
2595 : : * The argument is the raw parsetree list.
2596 : : */
2597 : : static int
2598 : 207716 : errdetail_execute(List *raw_parsetree_list)
2599 : : {
2600 : : ListCell *parsetree_item;
2601 : :
2602 [ + + + + : 409708 : foreach(parsetree_item, raw_parsetree_list)
+ + ]
2603 : : {
2604 : 208122 : RawStmt *parsetree = lfirst_node(RawStmt, parsetree_item);
2605 : :
2606 [ + + ]: 208122 : if (IsA(parsetree->stmt, ExecuteStmt))
2607 : : {
2608 : 6130 : ExecuteStmt *stmt = (ExecuteStmt *) parsetree->stmt;
2609 : : PreparedStatement *pstmt;
2610 : :
2611 : 6130 : pstmt = FetchPreparedStatement(stmt->name, false);
2612 [ + - ]: 6130 : if (pstmt)
2613 : : {
2614 : : char *truncated_stmt =
2615 : 6130 : truncate_query_log(pstmt->plansource->query_string);
2616 : :
2617 [ + + ]: 12258 : errdetail("prepare: %s",
2618 : : truncated_stmt ?
2619 : 6128 : truncated_stmt : pstmt->plansource->query_string);
2620 : :
2621 [ + + ]: 6130 : if (truncated_stmt != NULL)
2622 : 2 : pfree(truncated_stmt);
2623 : :
2624 : 6130 : return 0;
2625 : : }
2626 : : }
2627 : : }
2628 : :
2629 : 201586 : return 0;
2630 : : }
2631 : :
2632 : : /*
2633 : : * errdetail_params
2634 : : *
2635 : : * Add an errdetail() line showing bind-parameter data, if available.
2636 : : * Note that this is only used for statement logging, so it is controlled
2637 : : * by log_parameter_max_length not log_parameter_max_length_on_error.
2638 : : */
2639 : : static int
2640 : 4026 : errdetail_params(ParamListInfo params)
2641 : : {
2642 [ + + + - : 4026 : if (params && params->numParams > 0 && log_parameter_max_length != 0)
+ + ]
2643 : : {
2644 : : char *str;
2645 : :
2646 : 2490 : str = BuildParamLogString(params, NULL, log_parameter_max_length);
2647 [ + - + - ]: 2490 : if (str && str[0] != '\0')
2648 : 2490 : errdetail("Parameters: %s", str);
2649 : : }
2650 : :
2651 : 4026 : return 0;
2652 : : }
2653 : :
2654 : : /*
2655 : : * errdetail_recovery_conflict
2656 : : *
2657 : : * Add an errdetail() line showing conflict source.
2658 : : */
2659 : : static int
2660 : 12 : errdetail_recovery_conflict(RecoveryConflictReason reason)
2661 : : {
2662 [ + + + + : 12 : switch (reason)
+ - + +
- ]
2663 : : {
2664 : 1 : case RECOVERY_CONFLICT_BUFFERPIN:
2665 : 1 : errdetail("User was holding shared buffer pin for too long.");
2666 : 1 : break;
2667 : 1 : case RECOVERY_CONFLICT_LOCK:
2668 : 1 : errdetail("User was holding a relation lock for too long.");
2669 : 1 : break;
2670 : 1 : case RECOVERY_CONFLICT_TABLESPACE:
2671 : 1 : errdetail("User was or might have been using tablespace that must be dropped.");
2672 : 1 : break;
2673 : 1 : case RECOVERY_CONFLICT_SNAPSHOT:
2674 : 1 : errdetail("User query might have needed to see row versions that must be removed.");
2675 : 1 : break;
2676 : 5 : case RECOVERY_CONFLICT_LOGICALSLOT:
2677 : 5 : errdetail("User was using a logical replication slot that must be invalidated.");
2678 : 5 : break;
2679 : 0 : case RECOVERY_CONFLICT_STARTUP_DEADLOCK:
2680 : 0 : errdetail("User transaction caused deadlock with recovery.");
2681 : 0 : break;
2682 : 1 : case RECOVERY_CONFLICT_BUFFERPIN_DEADLOCK:
2683 : 1 : errdetail("User transaction caused buffer deadlock with recovery.");
2684 : 1 : break;
2685 : 2 : case RECOVERY_CONFLICT_DATABASE:
2686 : 2 : errdetail("User was connected to a database that must be dropped.");
2687 : 2 : break;
2688 : : }
2689 : :
2690 : 12 : return 0;
2691 : : }
2692 : :
2693 : : /*
2694 : : * bind_param_error_callback
2695 : : *
2696 : : * Error context callback used while parsing parameters in a Bind message
2697 : : */
2698 : : static void
2699 : 1 : bind_param_error_callback(void *arg)
2700 : : {
2701 : 1 : BindParamCbData *data = (BindParamCbData *) arg;
2702 : : StringInfoData buf;
2703 : : char *quotedval;
2704 : :
2705 [ - + ]: 1 : if (data->paramno < 0)
2706 : 0 : return;
2707 : :
2708 : : /* If we have a textual value, quote it, and trim if necessary */
2709 [ + - ]: 1 : if (data->paramval)
2710 : : {
2711 : 1 : initStringInfo(&buf);
2712 : 1 : appendStringInfoStringQuoted(&buf, data->paramval,
2713 : : log_parameter_max_length_on_error);
2714 : 1 : quotedval = buf.data;
2715 : : }
2716 : : else
2717 : 0 : quotedval = NULL;
2718 : :
2719 [ + - - + ]: 1 : if (data->portalName && data->portalName[0] != '\0')
2720 : : {
2721 [ # # ]: 0 : if (quotedval)
2722 : 0 : errcontext("portal \"%s\" parameter $%d = %s",
2723 : 0 : data->portalName, data->paramno + 1, quotedval);
2724 : : else
2725 : 0 : errcontext("portal \"%s\" parameter $%d",
2726 : 0 : data->portalName, data->paramno + 1);
2727 : : }
2728 : : else
2729 : : {
2730 [ + - ]: 1 : if (quotedval)
2731 : 1 : errcontext("unnamed portal parameter $%d = %s",
2732 : 1 : data->paramno + 1, quotedval);
2733 : : else
2734 : 0 : errcontext("unnamed portal parameter $%d",
2735 : 0 : data->paramno + 1);
2736 : : }
2737 : :
2738 [ + - ]: 1 : if (quotedval)
2739 : 1 : pfree(quotedval);
2740 : : }
2741 : :
2742 : : /*
2743 : : * exec_describe_statement_message
2744 : : *
2745 : : * Process a "Describe" message for a prepared statement
2746 : : */
2747 : : static void
2748 : 81 : exec_describe_statement_message(const char *stmt_name)
2749 : : {
2750 : : CachedPlanSource *psrc;
2751 : :
2752 : : /*
2753 : : * Start up a transaction command. (Note that this will normally change
2754 : : * current memory context.) Nothing happens if we are already in one.
2755 : : */
2756 : 81 : start_xact_command();
2757 : :
2758 : : /* Switch back to message context */
2759 : 81 : MemoryContextSwitchTo(MessageContext);
2760 : :
2761 : : /* Find prepared statement */
2762 [ + + ]: 81 : if (stmt_name[0] != '\0')
2763 : : {
2764 : : PreparedStatement *pstmt;
2765 : :
2766 : 45 : pstmt = FetchPreparedStatement(stmt_name, true);
2767 : 44 : psrc = pstmt->plansource;
2768 : : }
2769 : : else
2770 : : {
2771 : : /* special-case the unnamed statement */
2772 : 36 : psrc = unnamed_stmt_psrc;
2773 [ - + ]: 36 : if (!psrc)
2774 [ # # ]: 0 : ereport(ERROR,
2775 : : (errcode(ERRCODE_UNDEFINED_PSTATEMENT),
2776 : : errmsg("unnamed prepared statement does not exist")));
2777 : : }
2778 : :
2779 : : /* Prepared statements shouldn't have changeable result descs */
2780 : : Assert(psrc->fixed_result);
2781 : :
2782 : : /*
2783 : : * If we are in aborted transaction state, we can't run
2784 : : * SendRowDescriptionMessage(), because that needs catalog accesses.
2785 : : * Hence, refuse to Describe statements that return data. (We shouldn't
2786 : : * just refuse all Describes, since that might break the ability of some
2787 : : * clients to issue COMMIT or ROLLBACK commands, if they use code that
2788 : : * blindly Describes whatever it does.) We can Describe parameters
2789 : : * without doing anything dangerous, so we don't restrict that.
2790 : : */
2791 [ + + ]: 80 : if (IsAbortedTransactionBlockState() &&
2792 [ - + ]: 4 : psrc->resultDesc)
2793 [ # # ]: 0 : ereport(ERROR,
2794 : : (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
2795 : : errmsg("current transaction is aborted, "
2796 : : "commands ignored until end of transaction block")));
2797 : :
2798 [ - + ]: 80 : if (whereToSendOutput != DestRemote)
2799 : 0 : return; /* can't actually do anything... */
2800 : :
2801 : : /*
2802 : : * First describe the parameters...
2803 : : */
2804 : 80 : pq_beginmessage_reuse(&row_description_buf, PqMsg_ParameterDescription);
2805 : 80 : pq_sendint16(&row_description_buf, psrc->num_params);
2806 : :
2807 [ + + ]: 89 : for (int i = 0; i < psrc->num_params; i++)
2808 : : {
2809 : 9 : Oid ptype = psrc->param_types[i];
2810 : :
2811 : 9 : pq_sendint32(&row_description_buf, (int) ptype);
2812 : : }
2813 : 80 : pq_endmessage_reuse(&row_description_buf);
2814 : :
2815 : : /*
2816 : : * Next send RowDescription or NoData to describe the result...
2817 : : */
2818 [ + + ]: 80 : if (psrc->resultDesc)
2819 : : {
2820 : : List *tlist;
2821 : :
2822 : : /* Get the plan's primary targetlist */
2823 : 72 : tlist = CachedPlanGetTargetList(psrc, NULL);
2824 : :
2825 : 71 : SendRowDescriptionMessage(&row_description_buf,
2826 : : psrc->resultDesc,
2827 : : tlist,
2828 : : NULL);
2829 : : }
2830 : : else
2831 : 8 : pq_putemptymessage(PqMsg_NoData);
2832 : : }
2833 : :
2834 : : /*
2835 : : * exec_describe_portal_message
2836 : : *
2837 : : * Process a "Describe" message for a portal
2838 : : */
2839 : : static void
2840 : 12796 : exec_describe_portal_message(const char *portal_name)
2841 : : {
2842 : : Portal portal;
2843 : :
2844 : : /*
2845 : : * Start up a transaction command. (Note that this will normally change
2846 : : * current memory context.) Nothing happens if we are already in one.
2847 : : */
2848 : 12796 : start_xact_command();
2849 : :
2850 : : /* Switch back to message context */
2851 : 12796 : MemoryContextSwitchTo(MessageContext);
2852 : :
2853 : 12796 : portal = GetPortalByName(portal_name);
2854 [ + + ]: 12796 : if (!PortalIsValid(portal))
2855 [ + - ]: 1 : ereport(ERROR,
2856 : : (errcode(ERRCODE_UNDEFINED_CURSOR),
2857 : : errmsg("portal \"%s\" does not exist", portal_name)));
2858 : :
2859 : : /*
2860 : : * If we are in aborted transaction state, we can't run
2861 : : * SendRowDescriptionMessage(), because that needs catalog accesses.
2862 : : * Hence, refuse to Describe portals that return data. (We shouldn't just
2863 : : * refuse all Describes, since that might break the ability of some
2864 : : * clients to issue COMMIT or ROLLBACK commands, if they use code that
2865 : : * blindly Describes whatever it does.)
2866 : : */
2867 [ + + ]: 12795 : if (IsAbortedTransactionBlockState() &&
2868 [ - + ]: 1 : portal->tupDesc)
2869 [ # # ]: 0 : ereport(ERROR,
2870 : : (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
2871 : : errmsg("current transaction is aborted, "
2872 : : "commands ignored until end of transaction block")));
2873 : :
2874 [ - + ]: 12795 : if (whereToSendOutput != DestRemote)
2875 : 0 : return; /* can't actually do anything... */
2876 : :
2877 [ + + ]: 12795 : if (portal->tupDesc)
2878 : 5207 : SendRowDescriptionMessage(&row_description_buf,
2879 : : portal->tupDesc,
2880 : : FetchPortalTargetList(portal),
2881 : : portal->formats);
2882 : : else
2883 : 7588 : pq_putemptymessage(PqMsg_NoData);
2884 : : }
2885 : :
2886 : :
2887 : : /*
2888 : : * Convenience routines for starting/committing a single command.
2889 : : */
2890 : : static void
2891 : 951713 : start_xact_command(void)
2892 : : {
2893 [ + + ]: 951713 : if (!xact_started)
2894 : : {
2895 : 455694 : StartTransactionCommand();
2896 : :
2897 : 455694 : xact_started = true;
2898 : : }
2899 [ + + ]: 496019 : else if (MyXactFlags & XACT_FLAGS_PIPELINING)
2900 : : {
2901 : : /*
2902 : : * When the first Execute message is completed, following commands
2903 : : * will be done in an implicit transaction block created via
2904 : : * pipelining. The transaction state needs to be updated to an
2905 : : * implicit block if we're not already in a transaction block (like
2906 : : * one started by an explicit BEGIN).
2907 : : */
2908 : 18594 : BeginImplicitTransactionBlock();
2909 : : }
2910 : :
2911 : : /*
2912 : : * Start statement timeout if necessary. Note that this'll intentionally
2913 : : * not reset the clock on an already started timeout, to avoid the timing
2914 : : * overhead when start_xact_command() is invoked repeatedly, without an
2915 : : * interceding finish_xact_command() (e.g. parse/bind/execute). If that's
2916 : : * not desired, the timeout has to be disabled explicitly.
2917 : : */
2918 : 951713 : enable_statement_timeout();
2919 : :
2920 : : /* Start timeout for checking if the client has gone away if necessary. */
2921 [ - + - - ]: 951713 : if (client_connection_check_interval > 0 &&
2922 [ # # ]: 0 : IsUnderPostmaster &&
2923 : 0 : MyProcPort &&
2924 [ # # ]: 0 : !get_timeout_active(CLIENT_CONNECTION_CHECK_TIMEOUT))
2925 : 0 : enable_timeout_after(CLIENT_CONNECTION_CHECK_TIMEOUT,
2926 : : client_connection_check_interval);
2927 : 951713 : }
2928 : :
2929 : : static void
2930 : 831802 : finish_xact_command(void)
2931 : : {
2932 : : /* cancel active statement timeout after each command */
2933 : 831802 : disable_statement_timeout();
2934 : :
2935 [ + + ]: 831802 : if (xact_started)
2936 : : {
2937 : 423976 : CommitTransactionCommand();
2938 : :
2939 : : #ifdef MEMORY_CONTEXT_CHECKING
2940 : : /* Check all memory contexts that weren't freed during commit */
2941 : : /* (those that were, were checked before being deleted) */
2942 : : MemoryContextCheck(TopMemoryContext);
2943 : : #endif
2944 : :
2945 : : #ifdef SHOW_MEMORY_STATS
2946 : : /* Print mem stats after each commit for leak tracking */
2947 : : MemoryContextStats(TopMemoryContext);
2948 : : #endif
2949 : :
2950 : 423606 : xact_started = false;
2951 : : }
2952 : 831432 : }
2953 : :
2954 : :
2955 : : /*
2956 : : * Convenience routines for checking whether a statement is one of the
2957 : : * ones that we allow in transaction-aborted state.
2958 : : */
2959 : :
2960 : : /* Test a bare parsetree */
2961 : : static bool
2962 : 1304 : IsTransactionExitStmt(Node *parsetree)
2963 : : {
2964 [ + - + + ]: 1304 : if (parsetree && IsA(parsetree, TransactionStmt))
2965 : : {
2966 : 1253 : TransactionStmt *stmt = (TransactionStmt *) parsetree;
2967 : :
2968 [ + + ]: 1253 : if (stmt->kind == TRANS_STMT_COMMIT ||
2969 [ + + ]: 765 : stmt->kind == TRANS_STMT_PREPARE ||
2970 [ + + ]: 763 : stmt->kind == TRANS_STMT_ROLLBACK ||
2971 [ + + ]: 227 : stmt->kind == TRANS_STMT_ROLLBACK_TO)
2972 : 1245 : return true;
2973 : : }
2974 : 59 : return false;
2975 : : }
2976 : :
2977 : : /* Test a list that contains PlannedStmt nodes */
2978 : : static bool
2979 : 1 : IsTransactionExitStmtList(List *pstmts)
2980 : : {
2981 [ + - ]: 1 : if (list_length(pstmts) == 1)
2982 : : {
2983 : 1 : PlannedStmt *pstmt = linitial_node(PlannedStmt, pstmts);
2984 : :
2985 [ + - + - ]: 2 : if (pstmt->commandType == CMD_UTILITY &&
2986 : 1 : IsTransactionExitStmt(pstmt->utilityStmt))
2987 : 1 : return true;
2988 : : }
2989 : 0 : return false;
2990 : : }
2991 : :
2992 : : /* Test a list that contains PlannedStmt nodes */
2993 : : static bool
2994 : 12794 : IsTransactionStmtList(List *pstmts)
2995 : : {
2996 [ + - ]: 12794 : if (list_length(pstmts) == 1)
2997 : : {
2998 : 12794 : PlannedStmt *pstmt = linitial_node(PlannedStmt, pstmts);
2999 : :
3000 [ + + ]: 12794 : if (pstmt->commandType == CMD_UTILITY &&
3001 [ + + ]: 2008 : IsA(pstmt->utilityStmt, TransactionStmt))
3002 : 487 : return true;
3003 : : }
3004 : 12307 : return false;
3005 : : }
3006 : :
3007 : : /* Release any existing unnamed prepared statement */
3008 : : static void
3009 : 444146 : drop_unnamed_stmt(void)
3010 : : {
3011 : : /* paranoia to avoid a dangling pointer in case of error */
3012 [ + + ]: 444146 : if (unnamed_stmt_psrc)
3013 : : {
3014 : 3703 : CachedPlanSource *psrc = unnamed_stmt_psrc;
3015 : :
3016 : 3703 : unnamed_stmt_psrc = NULL;
3017 : 3703 : DropCachedPlan(psrc);
3018 : : }
3019 : 444146 : }
3020 : :
3021 : :
3022 : : /* --------------------------------
3023 : : * signal handler routines used in PostgresMain()
3024 : : * --------------------------------
3025 : : */
3026 : :
3027 : : /*
3028 : : * quickdie() occurs when signaled SIGQUIT by the postmaster.
3029 : : *
3030 : : * Either some backend has bought the farm, or we've been told to shut down
3031 : : * "immediately"; so we need to stop what we're doing and exit.
3032 : : */
3033 : : void
3034 : 0 : quickdie(SIGNAL_ARGS)
3035 : : {
3036 : 0 : sigaddset(&BlockSig, SIGQUIT); /* prevent nested calls */
3037 : 0 : sigprocmask(SIG_SETMASK, &BlockSig, NULL);
3038 : :
3039 : : /*
3040 : : * Prevent interrupts while exiting; though we just blocked signals that
3041 : : * would queue new interrupts, one may have been pending. We don't want a
3042 : : * quickdie() downgraded to a mere query cancel.
3043 : : */
3044 : 0 : HOLD_INTERRUPTS();
3045 : :
3046 : : /*
3047 : : * If we're aborting out of client auth, don't risk trying to send
3048 : : * anything to the client; we will likely violate the protocol, not to
3049 : : * mention that we may have interrupted the guts of OpenSSL or some
3050 : : * authentication library.
3051 : : */
3052 [ # # # # ]: 0 : if (ClientAuthInProgress && whereToSendOutput == DestRemote)
3053 : 0 : whereToSendOutput = DestNone;
3054 : :
3055 : : /*
3056 : : * Notify the client before exiting, to give a clue on what happened.
3057 : : *
3058 : : * It's dubious to call ereport() from a signal handler. It is certainly
3059 : : * not async-signal safe. But it seems better to try, than to disconnect
3060 : : * abruptly and leave the client wondering what happened. It's remotely
3061 : : * possible that we crash or hang while trying to send the message, but
3062 : : * receiving a SIGQUIT is a sign that something has already gone badly
3063 : : * wrong, so there's not much to lose. Assuming the postmaster is still
3064 : : * running, it will SIGKILL us soon if we get stuck for some reason.
3065 : : *
3066 : : * One thing we can do to make this a tad safer is to clear the error
3067 : : * context stack, so that context callbacks are not called. That's a lot
3068 : : * less code that could be reached here, and the context info is unlikely
3069 : : * to be very relevant to a SIGQUIT report anyway.
3070 : : */
3071 : 0 : error_context_stack = NULL;
3072 : :
3073 : : /*
3074 : : * When responding to a postmaster-issued signal, we send the message only
3075 : : * to the client; sending to the server log just creates log spam, plus
3076 : : * it's more code that we need to hope will work in a signal handler.
3077 : : *
3078 : : * Ideally these should be ereport(FATAL), but then we'd not get control
3079 : : * back to force the correct type of process exit.
3080 : : */
3081 [ # # # # ]: 0 : switch (GetQuitSignalReason())
3082 : : {
3083 : 0 : case PMQUIT_NOT_SENT:
3084 : : /* Hmm, SIGQUIT arrived out of the blue */
3085 [ # # ]: 0 : ereport(WARNING,
3086 : : (errcode(ERRCODE_ADMIN_SHUTDOWN),
3087 : : errmsg("terminating connection because of unexpected SIGQUIT signal")));
3088 : 0 : break;
3089 : 0 : case PMQUIT_FOR_CRASH:
3090 : : /* A crash-and-restart cycle is in progress */
3091 [ # # ]: 0 : ereport(WARNING_CLIENT_ONLY,
3092 : : (errcode(ERRCODE_CRASH_SHUTDOWN),
3093 : : errmsg("terminating connection because of crash of another server process"),
3094 : : errdetail("The postmaster has commanded this server process to roll back"
3095 : : " the current transaction and exit, because another"
3096 : : " server process exited abnormally and possibly corrupted"
3097 : : " shared memory."),
3098 : : errhint("In a moment you should be able to reconnect to the"
3099 : : " database and repeat your command.")));
3100 : 0 : break;
3101 : 0 : case PMQUIT_FOR_STOP:
3102 : : /* Immediate-mode stop */
3103 [ # # ]: 0 : ereport(WARNING_CLIENT_ONLY,
3104 : : (errcode(ERRCODE_ADMIN_SHUTDOWN),
3105 : : errmsg("terminating connection due to immediate shutdown command")));
3106 : 0 : break;
3107 : : }
3108 : :
3109 : : /*
3110 : : * We DO NOT want to run proc_exit() or atexit() callbacks -- we're here
3111 : : * because shared memory may be corrupted, so we don't want to try to
3112 : : * clean up our transaction. Just nail the windows shut and get out of
3113 : : * town. The callbacks wouldn't be safe to run from a signal handler,
3114 : : * anyway.
3115 : : *
3116 : : * Note we do _exit(2) not _exit(0). This is to force the postmaster into
3117 : : * a system reset cycle if someone sends a manual SIGQUIT to a random
3118 : : * backend. This is necessary precisely because we don't clean up our
3119 : : * shared memory state. (The "dead man switch" mechanism in pmsignal.c
3120 : : * should ensure the postmaster sees this as a crash, too, but no harm in
3121 : : * being doubly sure.)
3122 : : */
3123 : 0 : _exit(2);
3124 : : }
3125 : :
3126 : : /*
3127 : : * Shutdown signal from postmaster: abort transaction and exit
3128 : : * at soonest convenient time
3129 : : */
3130 : : void
3131 : 1226 : die(SIGNAL_ARGS)
3132 : : {
3133 : : /* Don't joggle the elbow of proc_exit */
3134 [ + + ]: 1226 : if (!proc_exit_inprogress)
3135 : : {
3136 : 841 : InterruptPending = true;
3137 : 841 : ProcDiePending = true;
3138 : :
3139 : : /*
3140 : : * Record who sent the signal. Will be 0 on platforms without
3141 : : * SA_SIGINFO, which is fine -- ProcessInterrupts() checks for that.
3142 : : * Only set on the first SIGTERM so we report the original sender.
3143 : : */
3144 [ + + ]: 841 : if (ProcDieSenderPid == 0)
3145 : : {
3146 : 840 : ProcDieSenderPid = pg_siginfo->pid;
3147 : 840 : ProcDieSenderUid = pg_siginfo->uid;
3148 : : }
3149 : : }
3150 : :
3151 : : /* for the cumulative stats system */
3152 : 1226 : pgStatSessionEndCause = DISCONNECT_KILLED;
3153 : :
3154 : : /* If we're still here, waken anything waiting on the process latch */
3155 : 1226 : SetLatch(MyLatch);
3156 : :
3157 : : /*
3158 : : * If we're in single user mode, we want to quit immediately - we can't
3159 : : * rely on latches as they wouldn't work when stdin/stdout is a file.
3160 : : * Rather ugly, but it's unlikely to be worthwhile to invest much more
3161 : : * effort just for the benefit of single user mode.
3162 : : */
3163 [ + + - + ]: 1226 : if (DoingCommandRead && whereToSendOutput != DestRemote)
3164 : 0 : ProcessInterrupts();
3165 : 1226 : }
3166 : :
3167 : : /*
3168 : : * Query-cancel signal from postmaster: abort current transaction
3169 : : * at soonest convenient time
3170 : : */
3171 : : void
3172 : 74 : StatementCancelHandler(SIGNAL_ARGS)
3173 : : {
3174 : : /*
3175 : : * Don't joggle the elbow of proc_exit
3176 : : */
3177 [ + - ]: 74 : if (!proc_exit_inprogress)
3178 : : {
3179 : 74 : InterruptPending = true;
3180 : 74 : QueryCancelPending = true;
3181 : : }
3182 : :
3183 : : /* If we're still here, waken anything waiting on the process latch */
3184 : 74 : SetLatch(MyLatch);
3185 : 74 : }
3186 : :
3187 : : /* signal handler for floating point exception */
3188 : : void
3189 : 0 : FloatExceptionHandler(SIGNAL_ARGS)
3190 : : {
3191 : : /* We're not returning, so no need to save errno */
3192 [ # # ]: 0 : ereport(ERROR,
3193 : : (errcode(ERRCODE_FLOATING_POINT_EXCEPTION),
3194 : : errmsg("floating-point exception"),
3195 : : errdetail("An invalid floating-point operation was signaled. "
3196 : : "This probably means an out-of-range result or an "
3197 : : "invalid operation, such as division by zero.")));
3198 : : }
3199 : :
3200 : : /*
3201 : : * Tell the next CHECK_FOR_INTERRUPTS() to process recovery conflicts. Runs
3202 : : * in a SIGUSR1 handler.
3203 : : */
3204 : : void
3205 : 18 : HandleRecoveryConflictInterrupt(void)
3206 : : {
3207 [ + - ]: 18 : if (pg_atomic_read_u32(&MyProc->pendingRecoveryConflicts) != 0)
3208 : 18 : InterruptPending = true;
3209 : : /* latch will be set by procsignal_sigusr1_handler */
3210 : 18 : }
3211 : :
3212 : : /*
3213 : : * Check one individual conflict reason.
3214 : : */
3215 : : static void
3216 : 18 : ProcessRecoveryConflictInterrupt(RecoveryConflictReason reason)
3217 : : {
3218 [ + + + + : 18 : switch (reason)
+ + - ]
3219 : : {
3220 : 2 : case RECOVERY_CONFLICT_STARTUP_DEADLOCK:
3221 : :
3222 : : /*
3223 : : * The startup process is waiting on a lock held by us, and has
3224 : : * requested us to check if it is a deadlock (i.e. the deadlock
3225 : : * timeout expired).
3226 : : *
3227 : : * If we aren't waiting for a lock we can never deadlock.
3228 : : */
3229 [ + - ]: 2 : if (GetAwaitedLock() == NULL)
3230 : 2 : return;
3231 : :
3232 : : /* Set the flag so that ProcSleep() will check for deadlocks. */
3233 : 0 : CheckDeadLockAlert();
3234 : 0 : return;
3235 : :
3236 : 5 : case RECOVERY_CONFLICT_BUFFERPIN_DEADLOCK:
3237 : :
3238 : : /*
3239 : : * The startup process is waiting on a buffer pin, and has
3240 : : * requested us to check if there is a deadlock involving the pin.
3241 : : *
3242 : : * If we're not waiting on a lock, there can be no deadlock.
3243 : : */
3244 [ + + ]: 5 : if (GetAwaitedLock() == NULL)
3245 : 4 : return;
3246 : :
3247 : : /*
3248 : : * If we're not holding the buffer pin, also no deadlock. (The
3249 : : * startup process doesn't know who's holding the pin, and sends
3250 : : * this signal to *all* backends, so this is the common case.)
3251 : : */
3252 [ - + ]: 1 : if (!HoldingBufferPinThatDelaysRecovery())
3253 : 0 : return;
3254 : :
3255 : : /*
3256 : : * Otherwise, we probably have a deadlock. Unfortunately the
3257 : : * normal deadlock detector doesn't know about buffer pins, so we
3258 : : * cannot perform comprehensively deadlock check. Instead, we
3259 : : * just assume that it is a deadlock if the above two conditions
3260 : : * are met. In principle this can lead to false positives, but
3261 : : * it's rare in practice because sessions in a hot standby server
3262 : : * rarely hold locks that can block other backends.
3263 : : */
3264 : 1 : report_recovery_conflict(reason);
3265 : 0 : return;
3266 : :
3267 : 1 : case RECOVERY_CONFLICT_BUFFERPIN:
3268 : :
3269 : : /*
3270 : : * Someone is holding a buffer pin that the startup process is
3271 : : * waiting for, and it got tired of waiting. If that's us, error
3272 : : * out to release the pin.
3273 : : */
3274 [ - + ]: 1 : if (!HoldingBufferPinThatDelaysRecovery())
3275 : 0 : return;
3276 : :
3277 : 1 : report_recovery_conflict(reason);
3278 : 0 : return;
3279 : :
3280 : 3 : case RECOVERY_CONFLICT_LOCK:
3281 : : case RECOVERY_CONFLICT_TABLESPACE:
3282 : : case RECOVERY_CONFLICT_SNAPSHOT:
3283 : :
3284 : : /*
3285 : : * If we aren't in a transaction any longer then ignore.
3286 : : */
3287 [ - + ]: 3 : if (!IsTransactionOrTransactionBlock())
3288 : 0 : return;
3289 : :
3290 : 3 : report_recovery_conflict(reason);
3291 : 0 : return;
3292 : :
3293 : 5 : case RECOVERY_CONFLICT_LOGICALSLOT:
3294 : 5 : report_recovery_conflict(reason);
3295 : 0 : return;
3296 : :
3297 : 2 : case RECOVERY_CONFLICT_DATABASE:
3298 : :
3299 : : /* The database is being dropped; terminate the session */
3300 : 2 : report_recovery_conflict(reason);
3301 : 0 : return;
3302 : : }
3303 [ # # ]: 0 : elog(FATAL, "unrecognized conflict mode: %d", (int) reason);
3304 : : }
3305 : :
3306 : : /*
3307 : : * This transaction or session is conflicting with recovery and needs to be
3308 : : * killed. Roll back the transaction, if that's sufficient, or terminate the
3309 : : * connection, or do nothing if we're already in an aborted state.
3310 : : */
3311 : : static void
3312 : 12 : report_recovery_conflict(RecoveryConflictReason reason)
3313 : : {
3314 : : bool fatal;
3315 : :
3316 [ + + ]: 12 : if (reason == RECOVERY_CONFLICT_DATABASE)
3317 : : {
3318 : : /* note: no hint about reconnecting, and different errcode */
3319 : 2 : pgstat_report_recovery_conflict(reason);
3320 [ + - ]: 2 : ereport(FATAL,
3321 : : (errcode(ERRCODE_DATABASE_DROPPED),
3322 : : errmsg("terminating connection due to conflict with recovery"),
3323 : : errdetail_recovery_conflict(reason)));
3324 : : }
3325 [ + + ]: 10 : if (reason == RECOVERY_CONFLICT_LOGICALSLOT)
3326 : : {
3327 : : /*
3328 : : * RECOVERY_CONFLICT_LOGICALSLOT is a special case that always throws
3329 : : * an ERROR (ie never promotes to FATAL), though it still has to
3330 : : * respect QueryCancelHoldoffCount, so it shares this code path.
3331 : : * Logical decoding slots are only acquired while performing logical
3332 : : * decoding. During logical decoding no user controlled code is run.
3333 : : * During [sub]transaction abort, the slot is released. Therefore
3334 : : * user controlled code cannot intercept an error before the
3335 : : * replication slot is released.
3336 : : */
3337 : 5 : fatal = false;
3338 : : }
3339 : : else
3340 : : {
3341 : 5 : fatal = IsSubTransaction();
3342 : : }
3343 : :
3344 : : /*
3345 : : * If we're not in a subtransaction then we are OK to throw an ERROR to
3346 : : * resolve the conflict.
3347 : : *
3348 : : * XXX other times that we can throw just an ERROR *may* be
3349 : : * RECOVERY_CONFLICT_LOCK if no locks are held in parent transactions
3350 : : *
3351 : : * RECOVERY_CONFLICT_SNAPSHOT if no snapshots are held by parent
3352 : : * transactions and the transaction is not transaction-snapshot mode
3353 : : *
3354 : : * RECOVERY_CONFLICT_TABLESPACE if no temp files or cursors open in parent
3355 : : * transactions
3356 : : */
3357 [ + - ]: 10 : if (!fatal)
3358 : : {
3359 : : /*
3360 : : * If we already aborted then we no longer need to cancel. We do this
3361 : : * here since we do not wish to ignore aborted subtransactions, which
3362 : : * must cause FATAL, currently.
3363 : : */
3364 [ - + ]: 10 : if (IsAbortedTransactionBlockState())
3365 : 0 : return;
3366 : :
3367 : : /*
3368 : : * If a recovery conflict happens while we are waiting for input from
3369 : : * the client, the client is presumably just sitting idle in a
3370 : : * transaction, preventing recovery from making progress. We'll drop
3371 : : * through to the FATAL case below to dislodge it, in that case.
3372 : : */
3373 [ + + ]: 10 : if (!DoingCommandRead)
3374 : : {
3375 : : /* Avoid losing sync in the FE/BE protocol. */
3376 [ - + ]: 6 : if (QueryCancelHoldoffCount != 0)
3377 : : {
3378 : : /*
3379 : : * Re-arm and defer this interrupt until later. See similar
3380 : : * code in ProcessInterrupts().
3381 : : */
3382 : 0 : (void) pg_atomic_fetch_or_u32(&MyProc->pendingRecoveryConflicts, (1 << reason));
3383 : 0 : InterruptPending = true;
3384 : 0 : return;
3385 : : }
3386 : :
3387 : : /*
3388 : : * We are cleared to throw an ERROR. Either it's the logical slot
3389 : : * case, or we have a top-level transaction that we can abort and
3390 : : * a conflict that isn't inherently non-retryable.
3391 : : */
3392 : 6 : LockErrorCleanup();
3393 : 6 : pgstat_report_recovery_conflict(reason);
3394 [ + - ]: 6 : ereport(ERROR,
3395 : : (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
3396 : : errmsg("canceling statement due to conflict with recovery"),
3397 : : errdetail_recovery_conflict(reason)));
3398 : : }
3399 : : }
3400 : :
3401 : : /*
3402 : : * We couldn't resolve the conflict with ERROR, so terminate the whole
3403 : : * session.
3404 : : */
3405 : 4 : pgstat_report_recovery_conflict(reason);
3406 [ + - ]: 4 : ereport(FATAL,
3407 : : (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
3408 : : errmsg("terminating connection due to conflict with recovery"),
3409 : : errdetail_recovery_conflict(reason),
3410 : : errhint("In a moment you should be able to reconnect to the"
3411 : : " database and repeat your command.")));
3412 : : }
3413 : :
3414 : : /*
3415 : : * Check each possible recovery conflict reason.
3416 : : */
3417 : : static void
3418 : 18 : ProcessRecoveryConflictInterrupts(void)
3419 : : {
3420 : : uint32 pending;
3421 : :
3422 : : /*
3423 : : * We don't need to worry about joggling the elbow of proc_exit, because
3424 : : * proc_exit_prepare() holds interrupts, so ProcessInterrupts() won't call
3425 : : * us.
3426 : : */
3427 : : Assert(!proc_exit_inprogress);
3428 : : Assert(InterruptHoldoffCount == 0);
3429 : :
3430 : : /* Are any recovery conflict pending? */
3431 : 18 : pending = pg_atomic_read_membarrier_u32(&MyProc->pendingRecoveryConflicts);
3432 [ - + ]: 18 : if (pending == 0)
3433 : 0 : return;
3434 : :
3435 : : /*
3436 : : * Check the conflicts one by one, clearing each flag only before
3437 : : * processing the particular conflict. This ensures that if multiple
3438 : : * conflicts are pending, we come back here to process the remaining
3439 : : * conflicts, if an error is thrown during processing one of them.
3440 : : */
3441 : 18 : for (RecoveryConflictReason reason = 0;
3442 [ + + ]: 104 : reason < NUM_RECOVERY_CONFLICT_REASONS;
3443 : 86 : reason++)
3444 : : {
3445 [ + + ]: 98 : if ((pending & (1 << reason)) != 0)
3446 : : {
3447 : : /* clear the flag */
3448 : 18 : (void) pg_atomic_fetch_and_u32(&MyProc->pendingRecoveryConflicts, ~(1 << reason));
3449 : :
3450 : 18 : ProcessRecoveryConflictInterrupt(reason);
3451 : : }
3452 : : }
3453 : : }
3454 : :
3455 : : /*
3456 : : * ProcessInterrupts: out-of-line portion of CHECK_FOR_INTERRUPTS() macro
3457 : : *
3458 : : * If an interrupt condition is pending, and it's safe to service it,
3459 : : * then clear the flag and accept the interrupt. Called only when
3460 : : * InterruptPending is true.
3461 : : *
3462 : : * Note: if INTERRUPTS_CAN_BE_PROCESSED() is true, then ProcessInterrupts
3463 : : * is guaranteed to clear the InterruptPending flag before returning.
3464 : : * (This is not the same as guaranteeing that it's still clear when we
3465 : : * return; another interrupt could have arrived. But we promise that
3466 : : * any pre-existing one will have been serviced.)
3467 : : */
3468 : : void
3469 : 7028 : ProcessInterrupts(void)
3470 : : {
3471 : : /* OK to accept any interrupts now? */
3472 [ + + + + ]: 7028 : if (InterruptHoldoffCount != 0 || CritSectionCount != 0)
3473 : 792 : return;
3474 : 6236 : InterruptPending = false;
3475 : :
3476 [ + + ]: 6236 : if (ProcDiePending)
3477 : : {
3478 : 833 : int sender_pid = ProcDieSenderPid;
3479 : 833 : int sender_uid = ProcDieSenderUid;
3480 : :
3481 : 833 : ProcDiePending = false;
3482 : 833 : ProcDieSenderPid = 0;
3483 : 833 : ProcDieSenderUid = 0;
3484 : 833 : QueryCancelPending = false; /* ProcDie trumps QueryCancel */
3485 : 833 : LockErrorCleanup();
3486 : : /* As in quickdie, don't risk sending to client during auth */
3487 [ - + - - ]: 833 : if (ClientAuthInProgress && whereToSendOutput == DestRemote)
3488 : 0 : whereToSendOutput = DestNone;
3489 [ - + ]: 833 : if (ClientAuthInProgress)
3490 [ # # ]: 0 : ereport(FATAL,
3491 : : (errcode(ERRCODE_QUERY_CANCELED),
3492 : : errmsg("canceling authentication due to timeout")));
3493 [ + + ]: 833 : else if (AmAutoVacuumWorkerProcess())
3494 [ + - + - ]: 4 : ereport(FATAL,
3495 : : (errcode(ERRCODE_ADMIN_SHUTDOWN),
3496 : : errmsg("terminating autovacuum process due to administrator command"),
3497 : : ERRDETAIL_SIGNAL_SENDER(sender_pid, sender_uid)));
3498 [ + + ]: 829 : else if (IsLogicalWorker())
3499 [ + - + - ]: 119 : ereport(FATAL,
3500 : : (errcode(ERRCODE_ADMIN_SHUTDOWN),
3501 : : errmsg("terminating logical replication worker due to administrator command"),
3502 : : ERRDETAIL_SIGNAL_SENDER(sender_pid, sender_uid)));
3503 [ + + ]: 710 : else if (IsLogicalLauncher())
3504 : : {
3505 [ + + + - ]: 561 : ereport(DEBUG1,
3506 : : (errmsg_internal("logical replication launcher shutting down"),
3507 : : ERRDETAIL_SIGNAL_SENDER(sender_pid, sender_uid)));
3508 : :
3509 : : /*
3510 : : * The logical replication launcher can be stopped at any time.
3511 : : * Use exit status 1 so the background worker is restarted.
3512 : : */
3513 : 561 : proc_exit(1);
3514 : : }
3515 [ + + ]: 149 : else if (AmWalReceiverProcess())
3516 [ + - + - ]: 102 : ereport(FATAL,
3517 : : (errcode(ERRCODE_ADMIN_SHUTDOWN),
3518 : : errmsg("terminating walreceiver process due to administrator command"),
3519 : : ERRDETAIL_SIGNAL_SENDER(sender_pid, sender_uid)));
3520 [ + + ]: 47 : else if (AmBackgroundWorkerProcess())
3521 [ + - + - ]: 11 : ereport(FATAL,
3522 : : (errcode(ERRCODE_ADMIN_SHUTDOWN),
3523 : : errmsg("terminating background worker \"%s\" due to administrator command",
3524 : : MyBgworkerEntry->bgw_type),
3525 : : ERRDETAIL_SIGNAL_SENDER(sender_pid, sender_uid)));
3526 [ + + ]: 36 : else if (AmIoWorkerProcess())
3527 : : {
3528 [ - + - - ]: 4 : ereport(DEBUG1,
3529 : : (errmsg_internal("io worker shutting down due to administrator command"),
3530 : : ERRDETAIL_SIGNAL_SENDER(sender_pid, sender_uid)));
3531 : :
3532 : 4 : proc_exit(0);
3533 : : }
3534 : : else
3535 [ + - + - ]: 32 : ereport(FATAL,
3536 : : (errcode(ERRCODE_ADMIN_SHUTDOWN),
3537 : : errmsg("terminating connection due to administrator command"),
3538 : : ERRDETAIL_SIGNAL_SENDER(sender_pid, sender_uid)));
3539 : : }
3540 : :
3541 [ - + ]: 5403 : if (CheckClientConnectionPending)
3542 : : {
3543 : 0 : CheckClientConnectionPending = false;
3544 : :
3545 : : /*
3546 : : * Check for lost connection and re-arm, if still configured, but not
3547 : : * if we've arrived back at DoingCommandRead state. We don't want to
3548 : : * wake up idle sessions, and they already know how to detect lost
3549 : : * connections.
3550 : : */
3551 [ # # # # ]: 0 : if (!DoingCommandRead && client_connection_check_interval > 0)
3552 : : {
3553 [ # # ]: 0 : if (!pq_check_connection())
3554 : 0 : ClientConnectionLost = true;
3555 : : else
3556 : 0 : enable_timeout_after(CLIENT_CONNECTION_CHECK_TIMEOUT,
3557 : : client_connection_check_interval);
3558 : : }
3559 : : }
3560 : :
3561 [ + + ]: 5403 : if (ClientConnectionLost)
3562 : : {
3563 : 8 : QueryCancelPending = false; /* lost connection trumps QueryCancel */
3564 : 8 : LockErrorCleanup();
3565 : : /* don't send to client, we already know the connection to be dead. */
3566 : 8 : whereToSendOutput = DestNone;
3567 [ + - ]: 8 : ereport(FATAL,
3568 : : (errcode(ERRCODE_CONNECTION_FAILURE),
3569 : : errmsg("connection to client lost")));
3570 : : }
3571 : :
3572 : : /*
3573 : : * Don't allow query cancel interrupts while reading input from the
3574 : : * client, because we might lose sync in the FE/BE protocol. (Die
3575 : : * interrupts are OK, because we won't read any further messages from the
3576 : : * client in that case.)
3577 : : *
3578 : : * See similar logic in ProcessRecoveryConflictInterrupts().
3579 : : */
3580 [ + + + + ]: 5395 : if (QueryCancelPending && QueryCancelHoldoffCount != 0)
3581 : : {
3582 : : /*
3583 : : * Re-arm InterruptPending so that we process the cancel request as
3584 : : * soon as we're done reading the message. (XXX this is seriously
3585 : : * ugly: it complicates INTERRUPTS_CAN_BE_PROCESSED(), and it means we
3586 : : * can't use that macro directly as the initial test in this function,
3587 : : * meaning that this code also creates opportunities for other bugs to
3588 : : * appear.)
3589 : : */
3590 : 6 : InterruptPending = true;
3591 : : }
3592 [ + + ]: 5389 : else if (QueryCancelPending)
3593 : : {
3594 : : bool lock_timeout_occurred;
3595 : : bool stmt_timeout_occurred;
3596 : :
3597 : 63 : QueryCancelPending = false;
3598 : :
3599 : : /*
3600 : : * If LOCK_TIMEOUT and STATEMENT_TIMEOUT indicators are both set, we
3601 : : * need to clear both, so always fetch both.
3602 : : */
3603 : 63 : lock_timeout_occurred = get_timeout_indicator(LOCK_TIMEOUT, true);
3604 : 63 : stmt_timeout_occurred = get_timeout_indicator(STATEMENT_TIMEOUT, true);
3605 : :
3606 : : /*
3607 : : * If both were set, we want to report whichever timeout completed
3608 : : * earlier; this ensures consistent behavior if the machine is slow
3609 : : * enough that the second timeout triggers before we get here. A tie
3610 : : * is arbitrarily broken in favor of reporting a lock timeout.
3611 : : */
3612 [ + + - + : 63 : if (lock_timeout_occurred && stmt_timeout_occurred &&
- - ]
3613 : 0 : get_timeout_finish_time(STATEMENT_TIMEOUT) < get_timeout_finish_time(LOCK_TIMEOUT))
3614 : 0 : lock_timeout_occurred = false; /* report stmt timeout */
3615 : :
3616 [ + + ]: 63 : if (lock_timeout_occurred)
3617 : : {
3618 : 5 : LockErrorCleanup();
3619 [ + - ]: 5 : ereport(ERROR,
3620 : : (errcode(ERRCODE_LOCK_NOT_AVAILABLE),
3621 : : errmsg("canceling statement due to lock timeout")));
3622 : : }
3623 [ + + ]: 58 : if (stmt_timeout_occurred)
3624 : : {
3625 : 6 : LockErrorCleanup();
3626 [ + - ]: 6 : ereport(ERROR,
3627 : : (errcode(ERRCODE_QUERY_CANCELED),
3628 : : errmsg("canceling statement due to statement timeout")));
3629 : : }
3630 [ - + ]: 52 : if (AmAutoVacuumWorkerProcess())
3631 : : {
3632 : 0 : LockErrorCleanup();
3633 [ # # ]: 0 : ereport(ERROR,
3634 : : (errcode(ERRCODE_QUERY_CANCELED),
3635 : : errmsg("canceling autovacuum task")));
3636 : : }
3637 : :
3638 : : /*
3639 : : * If we are reading a command from the client, just ignore the cancel
3640 : : * request --- sending an extra error message won't accomplish
3641 : : * anything. Otherwise, go ahead and throw the error.
3642 : : */
3643 [ + + ]: 52 : if (!DoingCommandRead)
3644 : : {
3645 : 49 : LockErrorCleanup();
3646 [ + - ]: 49 : ereport(ERROR,
3647 : : (errcode(ERRCODE_QUERY_CANCELED),
3648 : : errmsg("canceling statement due to user request")));
3649 : : }
3650 : : }
3651 : :
3652 [ + + ]: 5335 : if (pg_atomic_read_u32(&MyProc->pendingRecoveryConflicts) != 0)
3653 : 18 : ProcessRecoveryConflictInterrupts();
3654 : :
3655 [ + + ]: 5323 : if (IdleInTransactionSessionTimeoutPending)
3656 : : {
3657 : : /*
3658 : : * If the GUC has been reset to zero, ignore the signal. This is
3659 : : * important because the GUC update itself won't disable any pending
3660 : : * interrupt. We need to unset the flag before the injection point,
3661 : : * otherwise we could loop in interrupts checking.
3662 : : */
3663 : 1 : IdleInTransactionSessionTimeoutPending = false;
3664 [ + - ]: 1 : if (IdleInTransactionSessionTimeout > 0)
3665 : : {
3666 : 1 : INJECTION_POINT("idle-in-transaction-session-timeout", NULL);
3667 [ + - ]: 1 : ereport(FATAL,
3668 : : (errcode(ERRCODE_IDLE_IN_TRANSACTION_SESSION_TIMEOUT),
3669 : : errmsg("terminating connection due to idle-in-transaction timeout")));
3670 : : }
3671 : : }
3672 : :
3673 [ + + ]: 5322 : if (TransactionTimeoutPending)
3674 : : {
3675 : : /* As above, ignore the signal if the GUC has been reset to zero. */
3676 : 1 : TransactionTimeoutPending = false;
3677 [ + - ]: 1 : if (TransactionTimeout > 0)
3678 : : {
3679 : 1 : INJECTION_POINT("transaction-timeout", NULL);
3680 [ + - ]: 1 : ereport(FATAL,
3681 : : (errcode(ERRCODE_TRANSACTION_TIMEOUT),
3682 : : errmsg("terminating connection due to transaction timeout")));
3683 : : }
3684 : : }
3685 : :
3686 [ + + ]: 5321 : if (IdleSessionTimeoutPending)
3687 : : {
3688 : : /* As above, ignore the signal if the GUC has been reset to zero. */
3689 : 1 : IdleSessionTimeoutPending = false;
3690 [ + - ]: 1 : if (IdleSessionTimeout > 0)
3691 : : {
3692 : 1 : INJECTION_POINT("idle-session-timeout", NULL);
3693 [ + - ]: 1 : ereport(FATAL,
3694 : : (errcode(ERRCODE_IDLE_SESSION_TIMEOUT),
3695 : : errmsg("terminating connection due to idle-session timeout")));
3696 : : }
3697 : : }
3698 : :
3699 : : /*
3700 : : * If there are pending stats updates and we currently are truly idle
3701 : : * (matching the conditions in PostgresMain()), report stats now.
3702 : : *
3703 : : * Note that a backend that's waiting for a command can briefly start a
3704 : : * transaction to process a sinval catchup or notify interrupt, see
3705 : : * ProcessClientReadInterrupt(). We must not report stats in the middle
3706 : : * of that, not even while the transaction is being started.
3707 : : */
3708 [ + + + + ]: 5320 : if (IdleStatsUpdateTimeoutPending &&
3709 [ + + ]: 600 : DoingCommandRead && IsCompletelyOutOfTransaction())
3710 : : {
3711 : 8 : IdleStatsUpdateTimeoutPending = false;
3712 : 8 : pgstat_report_stat(true);
3713 : : }
3714 : :
3715 [ + + ]: 5320 : if (ProcSignalBarrierPending)
3716 : 2061 : ProcessProcSignalBarrier();
3717 : :
3718 [ + + ]: 5320 : if (ParallelMessagePending)
3719 : 2088 : ProcessParallelMessages();
3720 : :
3721 [ + + ]: 5308 : if (LogMemoryContextPending)
3722 : 11 : ProcessLogMemoryContextInterrupt();
3723 : :
3724 [ + + ]: 5308 : if (ParallelApplyMessagePending)
3725 : 7 : ProcessParallelApplyMessages();
3726 : :
3727 [ + + ]: 5306 : if (SlotSyncShutdownPending)
3728 : 1 : ProcessSlotSyncMessage();
3729 : :
3730 [ + + ]: 5305 : if (RepackMessagePending)
3731 : 13 : ProcessRepackMessages();
3732 : : }
3733 : :
3734 : : /*
3735 : : * GUC check_hook for client_connection_check_interval
3736 : : */
3737 : : bool
3738 : 1404 : check_client_connection_check_interval(int *newval, void **extra, GucSource source)
3739 : : {
3740 [ - + - - ]: 1404 : if (!WaitEventSetCanReportClosed() && *newval != 0)
3741 : : {
3742 : 0 : GUC_check_errdetail("\"client_connection_check_interval\" must be set to 0 on this platform.");
3743 : 0 : return false;
3744 : : }
3745 : 1404 : return true;
3746 : : }
3747 : :
3748 : : /*
3749 : : * GUC check_hook for log_parser_stats, log_planner_stats, log_executor_stats
3750 : : *
3751 : : * This function and check_log_stats interact to prevent their variables from
3752 : : * being set in a disallowed combination. This is a hack that doesn't really
3753 : : * work right; for example it might fail while applying pg_db_role_setting
3754 : : * values even though the final state would have been acceptable. However,
3755 : : * since these variables are legacy settings with little production usage,
3756 : : * we tolerate that.
3757 : : */
3758 : : bool
3759 : 4212 : check_stage_log_stats(bool *newval, void **extra, GucSource source)
3760 : : {
3761 [ - + - - ]: 4212 : if (*newval && log_statement_stats)
3762 : : {
3763 : 0 : GUC_check_errdetail("Cannot enable parameter when \"log_statement_stats\" is true.");
3764 : 0 : return false;
3765 : : }
3766 : 4212 : return true;
3767 : : }
3768 : :
3769 : : /*
3770 : : * GUC check_hook for log_statement_stats
3771 : : */
3772 : : bool
3773 : 1411 : check_log_stats(bool *newval, void **extra, GucSource source)
3774 : : {
3775 [ + + ]: 1411 : if (*newval &&
3776 [ + - + - : 7 : (log_parser_stats || log_planner_stats || log_executor_stats))
- + ]
3777 : : {
3778 : 0 : GUC_check_errdetail("Cannot enable \"log_statement_stats\" when "
3779 : : "\"log_parser_stats\", \"log_planner_stats\", "
3780 : : "or \"log_executor_stats\" is true.");
3781 : 0 : return false;
3782 : : }
3783 : 1411 : return true;
3784 : : }
3785 : :
3786 : : /* GUC assign hook for transaction_timeout */
3787 : : void
3788 : 3902 : assign_transaction_timeout(int newval, void *extra)
3789 : : {
3790 [ + + ]: 3902 : if (IsTransactionState())
3791 : : {
3792 : : /*
3793 : : * If transaction_timeout GUC has changed within the transaction block
3794 : : * enable or disable the timer correspondingly.
3795 : : */
3796 [ + + + - ]: 440 : if (newval > 0 && !get_timeout_active(TRANSACTION_TIMEOUT))
3797 : 1 : enable_timeout_after(TRANSACTION_TIMEOUT, newval);
3798 [ + - - + ]: 439 : else if (newval <= 0 && get_timeout_active(TRANSACTION_TIMEOUT))
3799 : 0 : disable_timeout(TRANSACTION_TIMEOUT, false);
3800 : : }
3801 : 3902 : }
3802 : :
3803 : : /*
3804 : : * GUC check_hook for restrict_nonsystem_relation_kind
3805 : : */
3806 : : bool
3807 : 1658 : check_restrict_nonsystem_relation_kind(char **newval, void **extra, GucSource source)
3808 : : {
3809 : : char *rawstring;
3810 : : List *elemlist;
3811 : : ListCell *l;
3812 : 1658 : int flags = 0;
3813 : :
3814 : : /* Need a modifiable copy of string */
3815 : 1658 : rawstring = pstrdup(*newval);
3816 : :
3817 [ - + ]: 1658 : if (!SplitIdentifierString(rawstring, ',', &elemlist))
3818 : : {
3819 : : /* syntax error in list */
3820 : 0 : GUC_check_errdetail("List syntax is invalid.");
3821 : 0 : pfree(rawstring);
3822 : 0 : list_free(elemlist);
3823 : 0 : return false;
3824 : : }
3825 : :
3826 [ + + + + : 2160 : foreach(l, elemlist)
+ + ]
3827 : : {
3828 : 502 : char *tok = (char *) lfirst(l);
3829 : :
3830 [ + + ]: 502 : if (pg_strcasecmp(tok, "view") == 0)
3831 : 253 : flags |= RESTRICT_RELKIND_VIEW;
3832 [ + - ]: 249 : else if (pg_strcasecmp(tok, "foreign-table") == 0)
3833 : 249 : flags |= RESTRICT_RELKIND_FOREIGN_TABLE;
3834 : : else
3835 : : {
3836 : 0 : GUC_check_errdetail("Unrecognized key word: \"%s\".", tok);
3837 : 0 : pfree(rawstring);
3838 : 0 : list_free(elemlist);
3839 : 0 : return false;
3840 : : }
3841 : : }
3842 : :
3843 : 1658 : pfree(rawstring);
3844 : 1658 : list_free(elemlist);
3845 : :
3846 : : /* Save the flags in *extra, for use by the assign function */
3847 : 1658 : *extra = guc_malloc(LOG, sizeof(int));
3848 [ - + ]: 1658 : if (!*extra)
3849 : 0 : return false;
3850 : 1658 : *((int *) *extra) = flags;
3851 : :
3852 : 1658 : return true;
3853 : : }
3854 : :
3855 : : /*
3856 : : * GUC assign_hook for restrict_nonsystem_relation_kind
3857 : : */
3858 : : void
3859 : 1664 : assign_restrict_nonsystem_relation_kind(const char *newval, void *extra)
3860 : : {
3861 : 1664 : int *flags = (int *) extra;
3862 : :
3863 : 1664 : restrict_nonsystem_relation_kind = *flags;
3864 : 1664 : }
3865 : :
3866 : : /*
3867 : : * set_debug_options --- apply "-d N" command line option
3868 : : *
3869 : : * -d is not quite the same as setting log_min_messages because it enables
3870 : : * other output options.
3871 : : */
3872 : : void
3873 : 0 : set_debug_options(int debug_flag, GucContext context, GucSource source)
3874 : : {
3875 [ # # ]: 0 : if (debug_flag > 0)
3876 : : {
3877 : : char debugstr[64];
3878 : :
3879 : 0 : sprintf(debugstr, "debug%d", debug_flag);
3880 : 0 : SetConfigOption("log_min_messages", debugstr, context, source);
3881 : : }
3882 : : else
3883 : 0 : SetConfigOption("log_min_messages", "notice", context, source);
3884 : :
3885 [ # # # # ]: 0 : if (debug_flag >= 1 && context == PGC_POSTMASTER)
3886 : : {
3887 : 0 : SetConfigOption("log_connections", "all", context, source);
3888 : 0 : SetConfigOption("log_disconnections", "true", context, source);
3889 : : }
3890 [ # # ]: 0 : if (debug_flag >= 2)
3891 : 0 : SetConfigOption("log_statement", "all", context, source);
3892 [ # # ]: 0 : if (debug_flag >= 3)
3893 : : {
3894 : 0 : SetConfigOption("debug_print_raw_parse", "true", context, source);
3895 : 0 : SetConfigOption("debug_print_parse", "true", context, source);
3896 : : }
3897 [ # # ]: 0 : if (debug_flag >= 4)
3898 : 0 : SetConfigOption("debug_print_plan", "true", context, source);
3899 [ # # ]: 0 : if (debug_flag >= 5)
3900 : 0 : SetConfigOption("debug_print_rewritten", "true", context, source);
3901 : 0 : }
3902 : :
3903 : :
3904 : : bool
3905 : 0 : set_plan_disabling_options(const char *arg, GucContext context, GucSource source)
3906 : : {
3907 : 0 : const char *tmp = NULL;
3908 : :
3909 [ # # # # : 0 : switch (arg[0])
# # # #
# ]
3910 : : {
3911 : 0 : case 's': /* seqscan */
3912 : 0 : tmp = "enable_seqscan";
3913 : 0 : break;
3914 : 0 : case 'i': /* indexscan */
3915 : 0 : tmp = "enable_indexscan";
3916 : 0 : break;
3917 : 0 : case 'o': /* indexonlyscan */
3918 : 0 : tmp = "enable_indexonlyscan";
3919 : 0 : break;
3920 : 0 : case 'b': /* bitmapscan */
3921 : 0 : tmp = "enable_bitmapscan";
3922 : 0 : break;
3923 : 0 : case 't': /* tidscan */
3924 : 0 : tmp = "enable_tidscan";
3925 : 0 : break;
3926 : 0 : case 'n': /* nestloop */
3927 : 0 : tmp = "enable_nestloop";
3928 : 0 : break;
3929 : 0 : case 'm': /* mergejoin */
3930 : 0 : tmp = "enable_mergejoin";
3931 : 0 : break;
3932 : 0 : case 'h': /* hashjoin */
3933 : 0 : tmp = "enable_hashjoin";
3934 : 0 : break;
3935 : : }
3936 [ # # ]: 0 : if (tmp)
3937 : : {
3938 : 0 : SetConfigOption(tmp, "false", context, source);
3939 : 0 : return true;
3940 : : }
3941 : : else
3942 : 0 : return false;
3943 : : }
3944 : :
3945 : :
3946 : : const char *
3947 : 0 : get_stats_option_name(const char *arg)
3948 : : {
3949 [ # # # ]: 0 : switch (arg[0])
3950 : : {
3951 : 0 : case 'p':
3952 [ # # ]: 0 : if (arg[1] == 'a') /* "parser" */
3953 : 0 : return "log_parser_stats";
3954 [ # # ]: 0 : else if (arg[1] == 'l') /* "planner" */
3955 : 0 : return "log_planner_stats";
3956 : 0 : break;
3957 : :
3958 : 0 : case 'e': /* "executor" */
3959 : 0 : return "log_executor_stats";
3960 : : break;
3961 : : }
3962 : :
3963 : 0 : return NULL;
3964 : : }
3965 : :
3966 : :
3967 : : /* ----------------------------------------------------------------
3968 : : * process_postgres_switches
3969 : : * Parse command line arguments for backends
3970 : : *
3971 : : * This is called twice, once for the "secure" options coming from the
3972 : : * postmaster or command line, and once for the "insecure" options coming
3973 : : * from the client's startup packet. The latter have the same syntax but
3974 : : * may be restricted in what they can do.
3975 : : *
3976 : : * argv[0] is ignored in either case (it's assumed to be the program name).
3977 : : *
3978 : : * ctx is PGC_POSTMASTER for secure options, PGC_BACKEND for insecure options
3979 : : * coming from the client, or PGC_SU_BACKEND for insecure options coming from
3980 : : * a superuser client.
3981 : : *
3982 : : * If a database name is present in the command line arguments, it's
3983 : : * returned into *dbname (this is allowed only if *dbname is initially NULL).
3984 : : * ----------------------------------------------------------------
3985 : : */
3986 : : void
3987 : 4870 : process_postgres_switches(int argc, char *argv[], GucContext ctx,
3988 : : const char **dbname)
3989 : : {
3990 : 4870 : bool secure = (ctx == PGC_POSTMASTER);
3991 : 4870 : int errs = 0;
3992 : : GucSource gucsource;
3993 : : int flag;
3994 : : pg_getopt_ctx optctx;
3995 : :
3996 [ + + ]: 4870 : if (secure)
3997 : : {
3998 : 85 : gucsource = PGC_S_ARGV; /* switches came from command line */
3999 : :
4000 : : /* Ignore the initial --single argument, if present */
4001 [ + - + - ]: 85 : if (argc > 1 && strcmp(argv[1], "--single") == 0)
4002 : : {
4003 : 85 : argv++;
4004 : 85 : argc--;
4005 : : }
4006 : : }
4007 : : else
4008 : : {
4009 : 4785 : gucsource = PGC_S_CLIENT; /* switches came from client */
4010 : : }
4011 : :
4012 : : /*
4013 : : * Parse command-line options. CAUTION: keep this in sync with
4014 : : * postmaster/postmaster.c (the option sets should not conflict) and with
4015 : : * the common help() function in main/main.c.
4016 : : */
4017 : 4870 : pg_getopt_start(&optctx, argc, argv, "B:bC:c:D:d:EeFf:h:ijk:lN:nOPp:r:S:sTt:v:W:-:");
4018 : :
4019 : : /*
4020 : : * Turn this off because it's either printed to stderr and not the log
4021 : : * where we'd want it, or argv[0] is now "--single", which would make for
4022 : : * a weird error message. We print our own error message below.
4023 : : */
4024 : 4870 : optctx.opterr = 0;
4025 : :
4026 [ + + ]: 11815 : while ((flag = pg_getopt_next(&optctx)) != -1)
4027 : : {
4028 [ - - - + : 6945 : switch (flag)
+ + - - -
+ - - - +
- - - - +
- - - - -
- - - -
- ]
4029 : : {
4030 : 0 : case 'B':
4031 : 0 : SetConfigOption("shared_buffers", optctx.optarg, ctx, gucsource);
4032 : 0 : break;
4033 : :
4034 : 0 : case 'b':
4035 : : /* Undocumented flag used for binary upgrades */
4036 [ # # ]: 0 : if (secure)
4037 : 0 : IsBinaryUpgrade = true;
4038 : 0 : break;
4039 : :
4040 : 0 : case 'C':
4041 : : /* ignored for consistency with the postmaster */
4042 : 0 : break;
4043 : :
4044 : 69 : case '-':
4045 : :
4046 : : /*
4047 : : * Error if the user misplaced a special must-be-first option
4048 : : * for dispatching to a subprogram. parse_dispatch_option()
4049 : : * returns DISPATCH_POSTMASTER if it doesn't find a match, so
4050 : : * error for anything else.
4051 : : */
4052 [ - + ]: 69 : if (parse_dispatch_option(optctx.optarg) != DISPATCH_POSTMASTER)
4053 [ # # ]: 0 : ereport(ERROR,
4054 : : (errcode(ERRCODE_SYNTAX_ERROR),
4055 : : errmsg("--%s must be first argument", optctx.optarg)));
4056 : :
4057 : : pg_fallthrough;
4058 : : case 'c':
4059 : : {
4060 : : char *name,
4061 : : *value;
4062 : :
4063 : 6715 : ParseLongOption(optctx.optarg, &name, &value);
4064 [ - + ]: 6715 : if (!value)
4065 : : {
4066 [ # # ]: 0 : if (flag == '-')
4067 [ # # ]: 0 : ereport(ERROR,
4068 : : (errcode(ERRCODE_SYNTAX_ERROR),
4069 : : errmsg("--%s requires a value",
4070 : : optctx.optarg)));
4071 : : else
4072 [ # # ]: 0 : ereport(ERROR,
4073 : : (errcode(ERRCODE_SYNTAX_ERROR),
4074 : : errmsg("-c %s requires a value",
4075 : : optctx.optarg)));
4076 : : }
4077 : 6715 : SetConfigOption(name, value, ctx, gucsource);
4078 : 6715 : pfree(name);
4079 : 6715 : pfree(value);
4080 : 6715 : break;
4081 : : }
4082 : :
4083 : 24 : case 'D':
4084 [ + - ]: 24 : if (secure)
4085 : 24 : userDoption = strdup(optctx.optarg);
4086 : 24 : break;
4087 : :
4088 : 0 : case 'd':
4089 : 0 : set_debug_options(atoi(optctx.optarg), ctx, gucsource);
4090 : 0 : break;
4091 : :
4092 : 0 : case 'E':
4093 [ # # ]: 0 : if (secure)
4094 : 0 : EchoQuery = true;
4095 : 0 : break;
4096 : :
4097 : 0 : case 'e':
4098 : 0 : SetConfigOption("datestyle", "euro", ctx, gucsource);
4099 : 0 : break;
4100 : :
4101 : 84 : case 'F':
4102 : 84 : SetConfigOption("fsync", "false", ctx, gucsource);
4103 : 84 : break;
4104 : :
4105 : 0 : case 'f':
4106 [ # # ]: 0 : if (!set_plan_disabling_options(optctx.optarg, ctx, gucsource))
4107 : 0 : errs++;
4108 : 0 : break;
4109 : :
4110 : 0 : case 'h':
4111 : 0 : SetConfigOption("listen_addresses", optctx.optarg, ctx, gucsource);
4112 : 0 : break;
4113 : :
4114 : 0 : case 'i':
4115 : 0 : SetConfigOption("listen_addresses", "*", ctx, gucsource);
4116 : 0 : break;
4117 : :
4118 : 61 : case 'j':
4119 [ + - ]: 61 : if (secure)
4120 : 61 : UseSemiNewlineNewline = true;
4121 : 61 : break;
4122 : :
4123 : 0 : case 'k':
4124 : 0 : SetConfigOption("unix_socket_directories", optctx.optarg, ctx, gucsource);
4125 : 0 : break;
4126 : :
4127 : 0 : case 'l':
4128 : 0 : SetConfigOption("ssl", "true", ctx, gucsource);
4129 : 0 : break;
4130 : :
4131 : 0 : case 'N':
4132 : 0 : SetConfigOption("max_connections", optctx.optarg, ctx, gucsource);
4133 : 0 : break;
4134 : :
4135 : 0 : case 'n':
4136 : : /* ignored for consistency with postmaster */
4137 : 0 : break;
4138 : :
4139 : 61 : case 'O':
4140 : 61 : SetConfigOption("allow_system_table_mods", "true", ctx, gucsource);
4141 : 61 : break;
4142 : :
4143 : 0 : case 'P':
4144 : 0 : SetConfigOption("ignore_system_indexes", "true", ctx, gucsource);
4145 : 0 : break;
4146 : :
4147 : 0 : case 'p':
4148 : 0 : SetConfigOption("port", optctx.optarg, ctx, gucsource);
4149 : 0 : break;
4150 : :
4151 : 0 : case 'r':
4152 : : /* send output (stdout and stderr) to the given file */
4153 [ # # ]: 0 : if (secure)
4154 : 0 : strlcpy(OutputFileName, optctx.optarg, MAXPGPATH);
4155 : 0 : break;
4156 : :
4157 : 0 : case 'S':
4158 : 0 : SetConfigOption("work_mem", optctx.optarg, ctx, gucsource);
4159 : 0 : break;
4160 : :
4161 : 0 : case 's':
4162 : 0 : SetConfigOption("log_statement_stats", "true", ctx, gucsource);
4163 : 0 : break;
4164 : :
4165 : 0 : case 'T':
4166 : : /* ignored for consistency with the postmaster */
4167 : 0 : break;
4168 : :
4169 : 0 : case 't':
4170 : : {
4171 : 0 : const char *tmp = get_stats_option_name(optctx.optarg);
4172 : :
4173 [ # # ]: 0 : if (tmp)
4174 : 0 : SetConfigOption(tmp, "true", ctx, gucsource);
4175 : : else
4176 : 0 : errs++;
4177 : 0 : break;
4178 : : }
4179 : :
4180 : 0 : case 'v':
4181 : :
4182 : : /*
4183 : : * -v is no longer used in normal operation, since
4184 : : * FrontendProtocol is already set before we get here. We keep
4185 : : * the switch only for possible use in standalone operation,
4186 : : * in case we ever support using normal FE/BE protocol with a
4187 : : * standalone backend.
4188 : : */
4189 [ # # ]: 0 : if (secure)
4190 : 0 : FrontendProtocol = (ProtocolVersion) atoi(optctx.optarg);
4191 : 0 : break;
4192 : :
4193 : 0 : case 'W':
4194 : 0 : SetConfigOption("post_auth_delay", optctx.optarg, ctx, gucsource);
4195 : 0 : break;
4196 : :
4197 : 0 : default:
4198 : 0 : errs++;
4199 : 0 : break;
4200 : : }
4201 : :
4202 [ - + ]: 6945 : if (errs)
4203 : 0 : break;
4204 : : }
4205 : :
4206 : : /*
4207 : : * Optional database name should be there only if *dbname is NULL.
4208 : : */
4209 [ + - + + : 4870 : if (!errs && dbname && *dbname == NULL && argc - optctx.optind >= 1)
+ - + - ]
4210 : 85 : *dbname = strdup(argv[optctx.optind++]);
4211 : :
4212 [ + - - + ]: 4870 : if (errs || argc != optctx.optind)
4213 : : {
4214 [ # # ]: 0 : if (errs)
4215 : 0 : optctx.optind--; /* complain about the previous argument */
4216 : :
4217 : : /* spell the error message a bit differently depending on context */
4218 [ # # ]: 0 : if (IsUnderPostmaster)
4219 [ # # ]: 0 : ereport(FATAL,
4220 : : errcode(ERRCODE_SYNTAX_ERROR),
4221 : : errmsg("invalid command-line argument for server process: %s", argv[optctx.optind]),
4222 : : errhint("Try \"%s --help\" for more information.", progname));
4223 : : else
4224 [ # # ]: 0 : ereport(FATAL,
4225 : : errcode(ERRCODE_SYNTAX_ERROR),
4226 : : errmsg("%s: invalid command-line argument: %s",
4227 : : progname, argv[optctx.optind]),
4228 : : errhint("Try \"%s --help\" for more information.", progname));
4229 : : }
4230 : 4870 : }
4231 : :
4232 : :
4233 : : /*
4234 : : * PostgresSingleUserMain
4235 : : * Entry point for single user mode. argc/argv are the command line
4236 : : * arguments to be used.
4237 : : *
4238 : : * Performs single user specific setup then calls PostgresMain() to actually
4239 : : * process queries. Single user mode specific setup should go here, rather
4240 : : * than PostgresMain() or InitPostgres() when reasonably possible.
4241 : : */
4242 : : void
4243 : 85 : PostgresSingleUserMain(int argc, char *argv[],
4244 : : const char *username)
4245 : : {
4246 : 85 : const char *dbname = NULL;
4247 : :
4248 : : Assert(!IsUnderPostmaster);
4249 : :
4250 : : /* Initialize startup process environment. */
4251 : 85 : InitStandaloneProcess(argv[0]);
4252 : :
4253 : : /*
4254 : : * Set default values for command-line options.
4255 : : */
4256 : 85 : InitializeGUCOptions();
4257 : :
4258 : : /*
4259 : : * Parse command-line options.
4260 : : */
4261 : 85 : process_postgres_switches(argc, argv, PGC_POSTMASTER, &dbname);
4262 : :
4263 : : /* Must have gotten a database name, or have a default (the username) */
4264 [ - + ]: 85 : if (dbname == NULL)
4265 : : {
4266 : 0 : dbname = username;
4267 [ # # ]: 0 : if (dbname == NULL)
4268 [ # # ]: 0 : ereport(FATAL,
4269 : : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
4270 : : errmsg("%s: no database nor user name specified",
4271 : : progname)));
4272 : : }
4273 : :
4274 : : /* Acquire configuration parameters */
4275 [ - + ]: 85 : if (!SelectConfigFiles(userDoption, progname))
4276 : 0 : proc_exit(1);
4277 : :
4278 : : /*
4279 : : * Validate we have been given a reasonable-looking DataDir and change
4280 : : * into it.
4281 : : */
4282 : 85 : checkDataDir();
4283 : 85 : ChangeToDataDir();
4284 : :
4285 : : /*
4286 : : * Create lockfile for data directory.
4287 : : */
4288 : 85 : CreateDataDirLockFile(false);
4289 : :
4290 : : /* read control file (error checking and contains config ) */
4291 : 84 : LocalProcessControlFile(false);
4292 : :
4293 : : /* Register the shared memory needs of all core subsystems. */
4294 : 84 : RegisterBuiltinShmemCallbacks();
4295 : :
4296 : : /*
4297 : : * process any libraries that should be preloaded at postmaster start
4298 : : */
4299 : 84 : process_shared_preload_libraries();
4300 : :
4301 : : /* Initialize MaxBackends */
4302 : 84 : InitializeMaxBackends();
4303 : :
4304 : : /*
4305 : : * We don't need postmaster child slots in single-user mode, but
4306 : : * initialize them anyway to avoid having special handling.
4307 : : */
4308 : 84 : InitPostmasterChildSlots();
4309 : :
4310 : : /* Initialize size of fast-path lock cache. */
4311 : 84 : InitializeFastPathLocks();
4312 : :
4313 : : /*
4314 : : * Also call any legacy shmem request hooks that might'be been installed
4315 : : * by preloaded libraries.
4316 : : *
4317 : : * Note: this must be done before ShmemCallRequestCallbacks(), because the
4318 : : * hooks may request LWLocks with RequestNamedLWLockTranche(), which in
4319 : : * turn affects the size of the LWLock array calculated in lwlock.c.
4320 : : */
4321 : 84 : process_shmem_requests();
4322 : :
4323 : : /*
4324 : : * Before computing the total size needed, give all subsystems, including
4325 : : * add-ins, a chance to chance to adjust their requested shmem sizes.
4326 : : */
4327 : 84 : ShmemCallRequestCallbacks();
4328 : :
4329 : : /*
4330 : : * Now that loadable modules have had their chance to request additional
4331 : : * shared memory, determine the value of any runtime-computed GUCs that
4332 : : * depend on the amount of shared memory required.
4333 : : */
4334 : 83 : InitializeShmemGUCs();
4335 : :
4336 : : /*
4337 : : * Now that modules have been loaded, we can process any custom resource
4338 : : * managers specified in the wal_consistency_checking GUC.
4339 : : */
4340 : 83 : InitializeWalConsistencyChecking();
4341 : :
4342 : : /*
4343 : : * Create shared memory etc. (Nothing's really "shared" in single-user
4344 : : * mode, but we must have these data structures anyway.)
4345 : : */
4346 : 83 : CreateSharedMemoryAndSemaphores();
4347 : :
4348 : : /*
4349 : : * Estimate number of openable files. This must happen after setting up
4350 : : * semaphores, because on some platforms semaphores count as open files.
4351 : : */
4352 : 82 : set_max_safe_fds();
4353 : :
4354 : : /*
4355 : : * Remember stand-alone backend startup time,roughly at the same point
4356 : : * during startup that postmaster does so.
4357 : : */
4358 : 82 : PgStartTime = GetCurrentTimestamp();
4359 : :
4360 : : /*
4361 : : * Create a per-backend PGPROC struct in shared memory. We must do this
4362 : : * before we can use LWLocks.
4363 : : */
4364 : 82 : InitProcess();
4365 : :
4366 : : /*
4367 : : * Now that sufficient infrastructure has been initialized, PostgresMain()
4368 : : * can do the rest.
4369 : : */
4370 : 82 : PostgresMain(dbname, username);
4371 : : }
4372 : :
4373 : :
4374 : : /* ----------------------------------------------------------------
4375 : : * PostgresMain
4376 : : * postgres main loop -- all backends, interactive or otherwise loop here
4377 : : *
4378 : : * dbname is the name of the database to connect to, username is the
4379 : : * PostgreSQL user name to be used for the session.
4380 : : *
4381 : : * NB: Single user mode specific setup should go to PostgresSingleUserMain()
4382 : : * if reasonably possible.
4383 : : * ----------------------------------------------------------------
4384 : : */
4385 : : void
4386 : 16508 : PostgresMain(const char *dbname, const char *username)
4387 : : {
4388 : : sigjmp_buf local_sigjmp_buf;
4389 : :
4390 : : /* these must be volatile to ensure state is preserved across longjmp: */
4391 : 16508 : volatile bool send_ready_for_query = true;
4392 : 16508 : volatile bool idle_in_transaction_timeout_enabled = false;
4393 : 16508 : volatile bool idle_session_timeout_enabled = false;
4394 : :
4395 : : Assert(dbname != NULL);
4396 : : Assert(username != NULL);
4397 : :
4398 : : Assert(GetProcessingMode() == InitProcessing);
4399 : :
4400 : : /*
4401 : : * Set up signal handlers. (InitPostmasterChild or InitStandaloneProcess
4402 : : * has already set up BlockSig and made that the active signal mask.)
4403 : : *
4404 : : * Note that postmaster blocked all signals before forking child process,
4405 : : * so there is no race condition whereby we might receive a signal before
4406 : : * we have set up the handler.
4407 : : *
4408 : : * Also note: it's best not to use any signals that are SIG_IGNored in the
4409 : : * postmaster. If such a signal arrives before we are able to change the
4410 : : * handler to non-SIG_IGN, it'll get dropped. Instead, make a dummy
4411 : : * handler in the postmaster to reserve the signal. (Of course, this isn't
4412 : : * an issue for signals that are locally generated, such as SIGALRM and
4413 : : * SIGPIPE.)
4414 : : */
4415 [ + + ]: 16508 : if (am_walsender)
4416 : 1504 : WalSndSignals();
4417 : : else
4418 : : {
4419 : 15004 : pqsignal(SIGHUP, SignalHandlerForConfigReload);
4420 : 15004 : pqsignal(SIGINT, StatementCancelHandler); /* cancel current query */
4421 : 15004 : pqsignal(SIGTERM, die); /* cancel current query and exit */
4422 : :
4423 : : /*
4424 : : * In a postmaster child backend, replace SignalHandlerForCrashExit
4425 : : * with quickdie, so we can tell the client we're dying.
4426 : : *
4427 : : * In a standalone backend, SIGQUIT can be generated from the keyboard
4428 : : * easily, while SIGTERM cannot, so we make both signals do die()
4429 : : * rather than quickdie().
4430 : : */
4431 [ + + ]: 15004 : if (IsUnderPostmaster)
4432 : 14922 : pqsignal(SIGQUIT, quickdie); /* hard crash time */
4433 : : else
4434 : 82 : pqsignal(SIGQUIT, die); /* cancel current query and exit */
4435 : 15004 : InitializeTimeouts(); /* establishes SIGALRM handler */
4436 : :
4437 : : /*
4438 : : * Ignore failure to write to frontend. Note: if frontend closes
4439 : : * connection, we will notice it and exit cleanly when control next
4440 : : * returns to outer loop. This seems safer than forcing exit in the
4441 : : * midst of output during who-knows-what operation...
4442 : : */
4443 : 15004 : pqsignal(SIGPIPE, PG_SIG_IGN);
4444 : 15004 : pqsignal(SIGUSR1, procsignal_sigusr1_handler);
4445 : 15004 : pqsignal(SIGUSR2, PG_SIG_IGN);
4446 : 15004 : pqsignal(SIGFPE, FloatExceptionHandler);
4447 : : }
4448 : :
4449 : : /* Early initialization */
4450 : 16508 : BaseInit();
4451 : :
4452 : : /* We need to allow SIGINT, etc during the initial transaction */
4453 : 16508 : sigprocmask(SIG_SETMASK, &UnBlockSig, NULL);
4454 : :
4455 : : /*
4456 : : * Generate a random cancel key, if this is a backend serving a
4457 : : * connection. InitPostgres() will advertise it in shared memory.
4458 : : */
4459 : : Assert(MyCancelKeyLength == 0);
4460 [ + + ]: 16508 : if (whereToSendOutput == DestRemote)
4461 : : {
4462 : : int len;
4463 : :
4464 [ + + ]: 16426 : len = (MyProcPort == NULL || MyProcPort->proto >= PG_PROTOCOL(3, 2))
4465 [ + - ]: 32852 : ? MAX_CANCEL_KEY_LENGTH : 4;
4466 [ - + ]: 16426 : if (!pg_strong_random(&MyCancelKey, len))
4467 : : {
4468 [ # # ]: 0 : ereport(ERROR,
4469 : : (errcode(ERRCODE_INTERNAL_ERROR),
4470 : : errmsg("could not generate random cancel key")));
4471 : : }
4472 : 16426 : MyCancelKeyLength = len;
4473 : : }
4474 : :
4475 : : /*
4476 : : * General initialization.
4477 : : *
4478 : : * NOTE: if you are tempted to add code in this vicinity, consider putting
4479 : : * it inside InitPostgres() instead. In particular, anything that
4480 : : * involves database access should be there, not here.
4481 : : *
4482 : : * Honor session_preload_libraries if not dealing with a WAL sender.
4483 : : */
4484 : 16508 : InitPostgres(dbname, InvalidOid, /* database to connect to */
4485 : : username, InvalidOid, /* role to connect as */
4486 : 16508 : (!am_walsender) ? INIT_PG_LOAD_SESSION_LIBS : 0,
4487 : : NULL); /* no out_dbname */
4488 : :
4489 : : /*
4490 : : * If the PostmasterContext is still around, recycle the space; we don't
4491 : : * need it anymore after InitPostgres completes.
4492 : : */
4493 [ + + ]: 16412 : if (PostmasterContext)
4494 : : {
4495 : 16332 : MemoryContextDelete(PostmasterContext);
4496 : 16332 : PostmasterContext = NULL;
4497 : : }
4498 : :
4499 : 16412 : SetProcessingMode(NormalProcessing);
4500 : :
4501 : : /*
4502 : : * Now all GUC states are fully set up. Report them to client if
4503 : : * appropriate.
4504 : : */
4505 : 16412 : BeginReportingGUCOptions();
4506 : :
4507 : : /*
4508 : : * Also set up handler to log session end; we have to wait till now to be
4509 : : * sure Log_disconnections has its final value.
4510 : : */
4511 [ + + + + ]: 16412 : if (IsUnderPostmaster && Log_disconnections)
4512 : 41 : on_proc_exit(log_disconnections, 0);
4513 : :
4514 : 16412 : pgstat_report_connect(MyDatabaseId);
4515 : :
4516 : : /* Perform initialization specific to a WAL sender process. */
4517 [ + + ]: 16412 : if (am_walsender)
4518 : 1504 : InitWalSender();
4519 : :
4520 : : /*
4521 : : * Send this backend's cancellation info to the frontend.
4522 : : */
4523 [ + + ]: 16412 : if (whereToSendOutput == DestRemote)
4524 : : {
4525 : : StringInfoData buf;
4526 : :
4527 : : Assert(MyCancelKeyLength > 0);
4528 : 16332 : pq_beginmessage(&buf, PqMsg_BackendKeyData);
4529 : 16332 : pq_sendint32(&buf, (int32) MyProcPid);
4530 : :
4531 : 16332 : pq_sendbytes(&buf, MyCancelKey, MyCancelKeyLength);
4532 : 16332 : pq_endmessage(&buf);
4533 : : /* Need not flush since ReadyForQuery will do it. */
4534 : : }
4535 : :
4536 : : /* Welcome banner for standalone case */
4537 [ + + ]: 16412 : if (whereToSendOutput == DestDebug)
4538 : 80 : printf("\nPostgreSQL stand-alone backend %s\n", PG_VERSION);
4539 : :
4540 : : /*
4541 : : * Create the memory context we will use in the main loop.
4542 : : *
4543 : : * MessageContext is reset once per iteration of the main loop, ie, upon
4544 : : * completion of processing of each command message from the client.
4545 : : */
4546 : 16412 : MessageContext = AllocSetContextCreate(TopMemoryContext,
4547 : : "MessageContext",
4548 : : ALLOCSET_DEFAULT_SIZES);
4549 : :
4550 : : /*
4551 : : * Create memory context and buffer used for RowDescription messages. As
4552 : : * SendRowDescriptionMessage(), via exec_describe_statement_message(), is
4553 : : * frequently executed for every single statement, we don't want to
4554 : : * allocate a separate buffer every time.
4555 : : */
4556 : 16412 : row_description_context = AllocSetContextCreate(TopMemoryContext,
4557 : : "RowDescriptionContext",
4558 : : ALLOCSET_DEFAULT_SIZES);
4559 : 16412 : MemoryContextSwitchTo(row_description_context);
4560 : 16412 : initStringInfo(&row_description_buf);
4561 : 16412 : MemoryContextSwitchTo(TopMemoryContext);
4562 : :
4563 : : /* Fire any defined login event triggers, if appropriate */
4564 : 16412 : EventTriggerOnLogin();
4565 : :
4566 : : /*
4567 : : * POSTGRES main processing loop begins here
4568 : : *
4569 : : * If an exception is encountered, processing resumes here so we abort the
4570 : : * current transaction and start a new one.
4571 : : *
4572 : : * You might wonder why this isn't coded as an infinite loop around a
4573 : : * PG_TRY construct. The reason is that this is the bottom of the
4574 : : * exception stack, and so with PG_TRY there would be no exception handler
4575 : : * in force at all during the CATCH part. By leaving the outermost setjmp
4576 : : * always active, we have at least some chance of recovering from an error
4577 : : * during error recovery. (If we get into an infinite loop thereby, it
4578 : : * will soon be stopped by overflow of elog.c's internal state stack.)
4579 : : *
4580 : : * Note that we use sigsetjmp(..., 1), so that this function's signal mask
4581 : : * (to wit, UnBlockSig) will be restored when longjmp'ing to here. This
4582 : : * is essential in case we longjmp'd out of a signal handler on a platform
4583 : : * where that leaves the signal blocked. It's not redundant with the
4584 : : * unblock in AbortTransaction() because the latter is only called if we
4585 : : * were inside a transaction.
4586 : : */
4587 : :
4588 [ + + ]: 16412 : if (sigsetjmp(local_sigjmp_buf, 1) != 0)
4589 : : {
4590 : : /*
4591 : : * NOTE: if you are tempted to add more code in this if-block,
4592 : : * consider the high probability that it should be in
4593 : : * AbortTransaction() instead. The only stuff done directly here
4594 : : * should be stuff that is guaranteed to apply *only* for outer-level
4595 : : * error recovery, such as adjusting the FE/BE protocol status.
4596 : : */
4597 : :
4598 : : /* Since not using PG_TRY, must reset error stack by hand */
4599 : 32140 : error_context_stack = NULL;
4600 : :
4601 : : /* Prevent interrupts while cleaning up */
4602 : 32140 : HOLD_INTERRUPTS();
4603 : :
4604 : : /*
4605 : : * Forget any pending QueryCancel request, since we're returning to
4606 : : * the idle loop anyway, and cancel any active timeout requests. (In
4607 : : * future we might want to allow some timeout requests to survive, but
4608 : : * at minimum it'd be necessary to do reschedule_timeouts(), in case
4609 : : * we got here because of a query cancel interrupting the SIGALRM
4610 : : * interrupt handler.) Note in particular that we must clear the
4611 : : * statement and lock timeout indicators, to prevent any future plain
4612 : : * query cancels from being misreported as timeouts in case we're
4613 : : * forgetting a timeout cancel.
4614 : : */
4615 : 32140 : disable_all_timeouts(false); /* do first to avoid race condition */
4616 : 32140 : QueryCancelPending = false;
4617 : 32140 : idle_in_transaction_timeout_enabled = false;
4618 : 32140 : idle_session_timeout_enabled = false;
4619 : :
4620 : : /* Not reading from the client anymore. */
4621 : 32140 : DoingCommandRead = false;
4622 : :
4623 : : /* Make sure libpq is in a good state */
4624 : 32140 : pq_comm_reset();
4625 : :
4626 : : /* Report the error to the client and/or server log */
4627 : 32140 : EmitErrorReport();
4628 : :
4629 : : /*
4630 : : * If Valgrind noticed something during the erroneous query, print the
4631 : : * query string, assuming we have one.
4632 : : */
4633 : : valgrind_report_error_query(debug_query_string);
4634 : :
4635 : : /*
4636 : : * Make sure debug_query_string gets reset before we possibly clobber
4637 : : * the storage it points at.
4638 : : */
4639 : 32140 : debug_query_string = NULL;
4640 : :
4641 : : /*
4642 : : * Abort the current transaction in order to recover.
4643 : : */
4644 : 32140 : AbortCurrentTransaction();
4645 : :
4646 [ + + ]: 32140 : if (am_walsender)
4647 : 58 : WalSndErrorCleanup();
4648 : :
4649 : 32140 : PortalErrorCleanup();
4650 : :
4651 : : /*
4652 : : * We can't release replication slots inside AbortTransaction() as we
4653 : : * need to be able to start and abort transactions while having a slot
4654 : : * acquired. But we never need to hold them across top level errors,
4655 : : * so releasing here is fine. There also is a before_shmem_exit()
4656 : : * callback ensuring correct cleanup on FATAL errors.
4657 : : */
4658 [ + + ]: 32140 : if (MyReplicationSlot != NULL)
4659 : 25 : ReplicationSlotRelease();
4660 : :
4661 : : /* We also want to cleanup temporary slots on error. */
4662 : 32140 : ReplicationSlotCleanup(false);
4663 : :
4664 : 32140 : jit_reset_after_error();
4665 : :
4666 : : /*
4667 : : * Now return to normal top-level context and clear ErrorContext for
4668 : : * next time.
4669 : : */
4670 : 32140 : MemoryContextSwitchTo(MessageContext);
4671 : 32140 : FlushErrorState();
4672 : :
4673 : : /*
4674 : : * If we were handling an extended-query-protocol message, initiate
4675 : : * skip till next Sync. This also causes us not to issue
4676 : : * ReadyForQuery (until we get Sync).
4677 : : */
4678 [ + + ]: 32140 : if (doing_extended_query_message)
4679 : 141 : ignore_till_sync = true;
4680 : :
4681 : : /* We don't have a transaction command open anymore */
4682 : 32140 : xact_started = false;
4683 : :
4684 : : /*
4685 : : * If an error occurred while we were reading a message from the
4686 : : * client, we have potentially lost track of where the previous
4687 : : * message ends and the next one begins. Even though we have
4688 : : * otherwise recovered from the error, we cannot safely read any more
4689 : : * messages from the client, so there isn't much we can do with the
4690 : : * connection anymore.
4691 : : */
4692 [ + + ]: 32140 : if (pq_is_reading_msg())
4693 [ + - ]: 2 : ereport(FATAL,
4694 : : (errcode(ERRCODE_PROTOCOL_VIOLATION),
4695 : : errmsg("terminating connection because protocol synchronization was lost")));
4696 : :
4697 : : /* Now we can allow interrupts again */
4698 : 32138 : RESUME_INTERRUPTS();
4699 : : }
4700 : :
4701 : : /* We can now handle ereport(ERROR) */
4702 : 48550 : PG_exception_stack = &local_sigjmp_buf;
4703 : :
4704 [ + + ]: 48550 : if (!ignore_till_sync)
4705 : 48411 : send_ready_for_query = true; /* initially, or after error */
4706 : :
4707 : : /*
4708 : : * Non-error queries loop here.
4709 : : */
4710 : :
4711 : : for (;;)
4712 : 472114 : {
4713 : : int firstchar;
4714 : : StringInfoData input_message;
4715 : :
4716 : : /*
4717 : : * At top of loop, reset extended-query-message flag, so that any
4718 : : * errors encountered in "idle" state don't provoke skip.
4719 : : */
4720 : 520664 : doing_extended_query_message = false;
4721 : :
4722 : : /*
4723 : : * For valgrind reporting purposes, the "current query" begins here.
4724 : : */
4725 : : #ifdef USE_VALGRIND
4726 : : old_valgrind_error_count = VALGRIND_COUNT_ERRORS;
4727 : : #endif
4728 : :
4729 : : /*
4730 : : * Release storage left over from prior query cycle, and create a new
4731 : : * query input buffer in the cleared MessageContext.
4732 : : */
4733 : 520664 : MemoryContextSwitchTo(MessageContext);
4734 : 520664 : MemoryContextReset(MessageContext);
4735 : :
4736 : 520664 : initStringInfo(&input_message);
4737 : :
4738 : : /*
4739 : : * Also consider releasing our catalog snapshot if any, so that it's
4740 : : * not preventing advance of global xmin while we wait for the client.
4741 : : */
4742 : 520664 : InvalidateCatalogSnapshotConditionally();
4743 : :
4744 : : /*
4745 : : * (1) If we've reached idle state, tell the frontend we're ready for
4746 : : * a new query.
4747 : : *
4748 : : * Note: this includes fflush()'ing the last of the prior output.
4749 : : *
4750 : : * This is also a good time to flush out collected statistics to the
4751 : : * cumulative stats system, and to update the PS stats display. We
4752 : : * avoid doing those every time through the message loop because it'd
4753 : : * slow down processing of batched messages, and because we don't want
4754 : : * to report uncommitted updates (that confuses autovacuum). The
4755 : : * notification processor wants a call too, if we are not in a
4756 : : * transaction block.
4757 : : *
4758 : : * Also, if an idle timeout is enabled, start the timer for that.
4759 : : */
4760 [ + + ]: 520664 : if (send_ready_for_query)
4761 : : {
4762 [ + + ]: 474770 : if (IsAbortedTransactionBlockState())
4763 : : {
4764 : 1331 : set_ps_display("idle in transaction (aborted)");
4765 : 1331 : pgstat_report_activity(STATE_IDLEINTRANSACTION_ABORTED, NULL);
4766 : :
4767 : : /* Start the idle-in-transaction timer */
4768 [ - + ]: 1331 : if (IdleInTransactionSessionTimeout > 0
4769 [ # # # # ]: 0 : && (IdleInTransactionSessionTimeout < TransactionTimeout || TransactionTimeout == 0))
4770 : : {
4771 : 0 : idle_in_transaction_timeout_enabled = true;
4772 : 0 : enable_timeout_after(IDLE_IN_TRANSACTION_SESSION_TIMEOUT,
4773 : : IdleInTransactionSessionTimeout);
4774 : : }
4775 : : }
4776 [ + + ]: 473439 : else if (IsTransactionOrTransactionBlock())
4777 : : {
4778 : 97086 : set_ps_display("idle in transaction");
4779 : 97086 : pgstat_report_activity(STATE_IDLEINTRANSACTION, NULL);
4780 : :
4781 : : /* Start the idle-in-transaction timer */
4782 [ + + ]: 97086 : if (IdleInTransactionSessionTimeout > 0
4783 [ + - + - ]: 1 : && (IdleInTransactionSessionTimeout < TransactionTimeout || TransactionTimeout == 0))
4784 : : {
4785 : 1 : idle_in_transaction_timeout_enabled = true;
4786 : 1 : enable_timeout_after(IDLE_IN_TRANSACTION_SESSION_TIMEOUT,
4787 : : IdleInTransactionSessionTimeout);
4788 : : }
4789 : : }
4790 : : else
4791 : : {
4792 : : long stats_timeout;
4793 : :
4794 : : /*
4795 : : * Process incoming notifies (including self-notifies), if
4796 : : * any, and send relevant messages to the client. Doing it
4797 : : * here helps ensure stable behavior in tests: if any notifies
4798 : : * were received during the just-finished transaction, they'll
4799 : : * be seen by the client before ReadyForQuery is.
4800 : : */
4801 [ + + ]: 376353 : if (notifyInterruptPending)
4802 : 22 : ProcessNotifyInterrupt(false);
4803 : :
4804 : : /*
4805 : : * Check if we need to report stats. If pgstat_report_stat()
4806 : : * decides it's too soon to flush out pending stats / lock
4807 : : * contention prevented reporting, it'll tell us when we
4808 : : * should try to report stats again (so that stats updates
4809 : : * aren't unduly delayed if the connection goes idle for a
4810 : : * long time). We only enable the timeout if we don't already
4811 : : * have a timeout in progress, because we don't disable the
4812 : : * timeout below. enable_timeout_after() needs to determine
4813 : : * the current timestamp, which can have a negative
4814 : : * performance impact. That's OK because pgstat_report_stat()
4815 : : * won't have us wake up sooner than a prior call.
4816 : : */
4817 : 376353 : stats_timeout = pgstat_report_stat(false);
4818 [ + + ]: 376353 : if (stats_timeout > 0)
4819 : : {
4820 [ + + ]: 353790 : if (!get_timeout_active(IDLE_STATS_UPDATE_TIMEOUT))
4821 : 48991 : enable_timeout_after(IDLE_STATS_UPDATE_TIMEOUT,
4822 : : stats_timeout);
4823 : : }
4824 : : else
4825 : : {
4826 : : /* all stats flushed, no need for the timeout */
4827 [ + + ]: 22563 : if (get_timeout_active(IDLE_STATS_UPDATE_TIMEOUT))
4828 : 2149 : disable_timeout(IDLE_STATS_UPDATE_TIMEOUT, false);
4829 : : }
4830 : :
4831 : 376353 : set_ps_display("idle");
4832 : 376353 : pgstat_report_activity(STATE_IDLE, NULL);
4833 : :
4834 : : /* Start the idle-session timer */
4835 [ + + ]: 376353 : if (IdleSessionTimeout > 0)
4836 : : {
4837 : 1 : idle_session_timeout_enabled = true;
4838 : 1 : enable_timeout_after(IDLE_SESSION_TIMEOUT,
4839 : : IdleSessionTimeout);
4840 : : }
4841 : : }
4842 : :
4843 : : /* Report any recently-changed GUC options */
4844 : 474770 : ReportChangedGUCOptions();
4845 : :
4846 : : /*
4847 : : * The first time this backend is ready for query, log the
4848 : : * durations of the different components of connection
4849 : : * establishment and setup.
4850 : : */
4851 [ + + ]: 474770 : if (conn_timing.ready_for_use == TIMESTAMP_MINUS_INFINITY &&
4852 [ + + ]: 474551 : (log_connections & LOG_CONNECTION_SETUP_DURATIONS) &&
4853 [ - + - - ]: 201 : IsExternalConnectionBackend(MyBackendType))
4854 : : {
4855 : : uint64 total_duration,
4856 : : fork_duration,
4857 : : auth_duration;
4858 : :
4859 : 201 : conn_timing.ready_for_use = GetCurrentTimestamp();
4860 : :
4861 : : total_duration =
4862 : 201 : TimestampDifferenceMicroseconds(conn_timing.socket_create,
4863 : : conn_timing.ready_for_use);
4864 : : fork_duration =
4865 : 201 : TimestampDifferenceMicroseconds(conn_timing.fork_start,
4866 : : conn_timing.fork_end);
4867 : : auth_duration =
4868 : 201 : TimestampDifferenceMicroseconds(conn_timing.auth_start,
4869 : : conn_timing.auth_end);
4870 : :
4871 [ + - ]: 201 : ereport(LOG,
4872 : : errmsg("connection ready: setup total=%.3f ms, fork=%.3f ms, authentication=%.3f ms",
4873 : : (double) total_duration / NS_PER_US,
4874 : : (double) fork_duration / NS_PER_US,
4875 : : (double) auth_duration / NS_PER_US));
4876 : : }
4877 : :
4878 : 474770 : ReadyForQuery(whereToSendOutput);
4879 : 474770 : send_ready_for_query = false;
4880 : : }
4881 : :
4882 : : /*
4883 : : * (2) Allow asynchronous signals to be executed immediately if they
4884 : : * come in while we are waiting for client input. (This must be
4885 : : * conditional since we don't want, say, reads on behalf of COPY FROM
4886 : : * STDIN doing the same thing.)
4887 : : */
4888 : 520664 : DoingCommandRead = true;
4889 : :
4890 : : /*
4891 : : * (3) read a command (loop blocks here)
4892 : : */
4893 : 520664 : firstchar = ReadCommand(&input_message);
4894 : :
4895 : : /*
4896 : : * (4) turn off the idle-in-transaction and idle-session timeouts if
4897 : : * active. We do this before step (5) so that any last-moment timeout
4898 : : * is certain to be detected in step (5).
4899 : : *
4900 : : * At most one of these timeouts will be active, so there's no need to
4901 : : * worry about combining the timeout.c calls into one.
4902 : : */
4903 [ - + ]: 520635 : if (idle_in_transaction_timeout_enabled)
4904 : : {
4905 : 0 : disable_timeout(IDLE_IN_TRANSACTION_SESSION_TIMEOUT, false);
4906 : 0 : idle_in_transaction_timeout_enabled = false;
4907 : : }
4908 [ - + ]: 520635 : if (idle_session_timeout_enabled)
4909 : : {
4910 : 0 : disable_timeout(IDLE_SESSION_TIMEOUT, false);
4911 : 0 : idle_session_timeout_enabled = false;
4912 : : }
4913 : :
4914 : : /*
4915 : : * (5) disable async signal conditions again.
4916 : : *
4917 : : * Query cancel is supposed to be a no-op when there is no query in
4918 : : * progress, so if a query cancel arrived while we were idle, just
4919 : : * reset QueryCancelPending. ProcessInterrupts() has that effect when
4920 : : * it's called when DoingCommandRead is set, so check for interrupts
4921 : : * before resetting DoingCommandRead.
4922 : : */
4923 [ + + ]: 520635 : CHECK_FOR_INTERRUPTS();
4924 : 520634 : DoingCommandRead = false;
4925 : :
4926 : : /*
4927 : : * (6) check for any other interesting events that happened while we
4928 : : * slept.
4929 : : */
4930 [ + + ]: 520634 : if (ConfigReloadPending)
4931 : : {
4932 : 51 : ConfigReloadPending = false;
4933 : 51 : ProcessConfigFile(PGC_SIGHUP);
4934 : : }
4935 : :
4936 : : /*
4937 : : * (7) process the command. But ignore it if we're skipping till
4938 : : * Sync.
4939 : : */
4940 [ + + + - ]: 520634 : if (ignore_till_sync && firstchar != EOF)
4941 : 1026 : continue;
4942 : :
4943 [ + + + + : 519608 : switch (firstchar)
+ + + + +
+ + + - ]
4944 : : {
4945 : 444028 : case PqMsg_Query:
4946 : : {
4947 : : const char *query_string;
4948 : :
4949 : : /* Set statement_timestamp() */
4950 : 444028 : SetCurrentStatementStartTimestamp();
4951 : :
4952 : 444028 : query_string = pq_getmsgstring(&input_message);
4953 : 444028 : pq_getmsgend(&input_message);
4954 : :
4955 [ + + ]: 444028 : if (am_walsender)
4956 : : {
4957 [ + + ]: 6634 : if (!exec_replication_command(query_string))
4958 : 2881 : exec_simple_query(query_string);
4959 : : }
4960 : : else
4961 : 437394 : exec_simple_query(query_string);
4962 : :
4963 : : valgrind_report_error_query(query_string);
4964 : :
4965 : 411559 : send_ready_for_query = true;
4966 : : }
4967 : 411559 : break;
4968 : :
4969 : 6119 : case PqMsg_Parse:
4970 : : {
4971 : : const char *stmt_name;
4972 : : const char *query_string;
4973 : : int numParams;
4974 : 6119 : Oid *paramTypes = NULL;
4975 : :
4976 : 6119 : forbidden_in_wal_sender(firstchar);
4977 : :
4978 : : /* Set statement_timestamp() */
4979 : 6119 : SetCurrentStatementStartTimestamp();
4980 : :
4981 : 6119 : stmt_name = pq_getmsgstring(&input_message);
4982 : 6119 : query_string = pq_getmsgstring(&input_message);
4983 : 6119 : numParams = pq_getmsgint(&input_message, 2);
4984 [ + + ]: 6119 : if (numParams > 0)
4985 : : {
4986 : 47 : paramTypes = palloc_array(Oid, numParams);
4987 [ + + ]: 121 : for (int i = 0; i < numParams; i++)
4988 : 74 : paramTypes[i] = pq_getmsgint(&input_message, 4);
4989 : : }
4990 : 6119 : pq_getmsgend(&input_message);
4991 : :
4992 : 6119 : exec_parse_message(query_string, stmt_name,
4993 : : paramTypes, numParams);
4994 : :
4995 : : valgrind_report_error_query(query_string);
4996 : : }
4997 : 6090 : break;
4998 : :
4999 : 12849 : case PqMsg_Bind:
5000 : 12849 : forbidden_in_wal_sender(firstchar);
5001 : :
5002 : : /* Set statement_timestamp() */
5003 : 12849 : SetCurrentStatementStartTimestamp();
5004 : :
5005 : : /*
5006 : : * this message is complex enough that it seems best to put
5007 : : * the field extraction out-of-line
5008 : : */
5009 : 12849 : exec_bind_message(&input_message);
5010 : :
5011 : : /* exec_bind_message does valgrind_report_error_query */
5012 : 12794 : break;
5013 : :
5014 : 12794 : case PqMsg_Execute:
5015 : : {
5016 : : const char *portal_name;
5017 : : int max_rows;
5018 : :
5019 : 12794 : forbidden_in_wal_sender(firstchar);
5020 : :
5021 : : /* Set statement_timestamp() */
5022 : 12794 : SetCurrentStatementStartTimestamp();
5023 : :
5024 : 12794 : portal_name = pq_getmsgstring(&input_message);
5025 : 12794 : max_rows = pq_getmsgint(&input_message, 4);
5026 : 12794 : pq_getmsgend(&input_message);
5027 : :
5028 : 12794 : exec_execute_message(portal_name, max_rows);
5029 : :
5030 : : /* exec_execute_message does valgrind_report_error_query */
5031 : : }
5032 : 12740 : break;
5033 : :
5034 : 1343 : case PqMsg_FunctionCall:
5035 : 1343 : forbidden_in_wal_sender(firstchar);
5036 : :
5037 : : /* Set statement_timestamp() */
5038 : 1343 : SetCurrentStatementStartTimestamp();
5039 : :
5040 : : /* Report query to various monitoring facilities. */
5041 : 1343 : pgstat_report_activity(STATE_FASTPATH, NULL);
5042 : 1343 : set_ps_display("<FASTPATH>");
5043 : :
5044 : : /* start an xact for this function invocation */
5045 : 1343 : start_xact_command();
5046 : :
5047 : : /*
5048 : : * Note: we may at this point be inside an aborted
5049 : : * transaction. We can't throw error for that until we've
5050 : : * finished reading the function-call message, so
5051 : : * HandleFunctionRequest() must check for it after doing so.
5052 : : * Be careful not to do anything that assumes we're inside a
5053 : : * valid transaction here.
5054 : : */
5055 : :
5056 : : /* switch back to message context */
5057 : 1343 : MemoryContextSwitchTo(MessageContext);
5058 : :
5059 : 1343 : HandleFunctionRequest(&input_message);
5060 : :
5061 : : /* commit the function-invocation transaction */
5062 : 1343 : finish_xact_command();
5063 : :
5064 : : valgrind_report_error_query("fastpath function call");
5065 : :
5066 : 1343 : send_ready_for_query = true;
5067 : 1343 : break;
5068 : :
5069 : 21 : case PqMsg_Close:
5070 : : {
5071 : : int close_type;
5072 : : const char *close_target;
5073 : :
5074 : 21 : forbidden_in_wal_sender(firstchar);
5075 : :
5076 : 21 : close_type = pq_getmsgbyte(&input_message);
5077 : 21 : close_target = pq_getmsgstring(&input_message);
5078 : 21 : pq_getmsgend(&input_message);
5079 : :
5080 [ + + - ]: 21 : switch (close_type)
5081 : : {
5082 : 19 : case 'S':
5083 [ + + ]: 19 : if (close_target[0] != '\0')
5084 : 15 : DropPreparedStatement(close_target, false);
5085 : : else
5086 : : {
5087 : : /* special-case the unnamed statement */
5088 : 4 : drop_unnamed_stmt();
5089 : : }
5090 : 19 : break;
5091 : 2 : case 'P':
5092 : : {
5093 : : Portal portal;
5094 : :
5095 : 2 : portal = GetPortalByName(close_target);
5096 [ + + ]: 2 : if (PortalIsValid(portal))
5097 : 1 : PortalDrop(portal, false);
5098 : : }
5099 : 2 : break;
5100 : 0 : default:
5101 [ # # ]: 0 : ereport(ERROR,
5102 : : (errcode(ERRCODE_PROTOCOL_VIOLATION),
5103 : : errmsg("invalid CLOSE message subtype %d",
5104 : : close_type)));
5105 : : break;
5106 : : }
5107 : :
5108 [ + - ]: 21 : if (whereToSendOutput == DestRemote)
5109 : 21 : pq_putemptymessage(PqMsg_CloseComplete);
5110 : :
5111 : : valgrind_report_error_query("CLOSE message");
5112 : : }
5113 : 21 : break;
5114 : :
5115 : 12877 : case PqMsg_Describe:
5116 : : {
5117 : : int describe_type;
5118 : : const char *describe_target;
5119 : :
5120 : 12877 : forbidden_in_wal_sender(firstchar);
5121 : :
5122 : : /* Set statement_timestamp() (needed for xact) */
5123 : 12877 : SetCurrentStatementStartTimestamp();
5124 : :
5125 : 12877 : describe_type = pq_getmsgbyte(&input_message);
5126 : 12877 : describe_target = pq_getmsgstring(&input_message);
5127 : 12877 : pq_getmsgend(&input_message);
5128 : :
5129 [ + + - ]: 12877 : switch (describe_type)
5130 : : {
5131 : 81 : case 'S':
5132 : 81 : exec_describe_statement_message(describe_target);
5133 : 79 : break;
5134 : 12796 : case 'P':
5135 : 12796 : exec_describe_portal_message(describe_target);
5136 : 12795 : break;
5137 : 0 : default:
5138 [ # # ]: 0 : ereport(ERROR,
5139 : : (errcode(ERRCODE_PROTOCOL_VIOLATION),
5140 : : errmsg("invalid DESCRIBE message subtype %d",
5141 : : describe_type)));
5142 : : break;
5143 : : }
5144 : :
5145 : : valgrind_report_error_query("DESCRIBE message");
5146 : : }
5147 : 12874 : break;
5148 : :
5149 : 39 : case PqMsg_Flush:
5150 : 39 : pq_getmsgend(&input_message);
5151 [ + - ]: 39 : if (whereToSendOutput == DestRemote)
5152 : 39 : pq_flush();
5153 : 39 : break;
5154 : :
5155 : 13489 : case PqMsg_Sync:
5156 : 13489 : pq_getmsgend(&input_message);
5157 : :
5158 : : /*
5159 : : * If pipelining was used, we may be in an implicit
5160 : : * transaction block. Close it before calling
5161 : : * finish_xact_command.
5162 : : */
5163 : 13489 : EndImplicitTransactionBlock();
5164 : 13489 : finish_xact_command();
5165 : : valgrind_report_error_query("SYNC message");
5166 : 13457 : send_ready_for_query = true;
5167 : 13457 : break;
5168 : :
5169 : : /*
5170 : : * PqMsg_Terminate means that the frontend is closing down the
5171 : : * socket. EOF means unexpected loss of frontend connection.
5172 : : * Either way, perform normal shutdown.
5173 : : */
5174 : 116 : case EOF:
5175 : :
5176 : : /* for the cumulative statistics system */
5177 : 116 : pgStatSessionEndCause = DISCONNECT_CLIENT_EOF;
5178 : :
5179 : : pg_fallthrough;
5180 : :
5181 : 15878 : case PqMsg_Terminate:
5182 : :
5183 : : /*
5184 : : * Reset whereToSendOutput to prevent ereport from attempting
5185 : : * to send any more messages to client.
5186 : : */
5187 [ + + ]: 15878 : if (whereToSendOutput == DestRemote)
5188 : 15766 : whereToSendOutput = DestNone;
5189 : :
5190 : : /*
5191 : : * NOTE: if you are tempted to add more code here, DON'T!
5192 : : * Whatever you had in mind to do should be set up as an
5193 : : * on_proc_exit or on_shmem_exit callback, instead. Otherwise
5194 : : * it will fail to be called during other backend-shutdown
5195 : : * scenarios.
5196 : : */
5197 : 15878 : proc_exit(0);
5198 : :
5199 : 171 : case PqMsg_CopyData:
5200 : : case PqMsg_CopyDone:
5201 : : case PqMsg_CopyFail:
5202 : :
5203 : : /*
5204 : : * Accept but ignore these messages, per protocol spec; we
5205 : : * probably got here because a COPY failed, and the frontend
5206 : : * is still sending data.
5207 : : */
5208 : 171 : break;
5209 : :
5210 : 0 : default:
5211 [ # # ]: 0 : ereport(FATAL,
5212 : : (errcode(ERRCODE_PROTOCOL_VIOLATION),
5213 : : errmsg("invalid frontend message type %d",
5214 : : firstchar)));
5215 : : }
5216 : : } /* end of input-reading loop */
5217 : : }
5218 : :
5219 : : /*
5220 : : * Throw an error if we're a WAL sender process.
5221 : : *
5222 : : * This is used to forbid anything else than simple query protocol messages
5223 : : * in a WAL sender process. 'firstchar' specifies what kind of a forbidden
5224 : : * message was received, and is used to construct the error message.
5225 : : */
5226 : : static void
5227 : 46003 : forbidden_in_wal_sender(char firstchar)
5228 : : {
5229 [ - + ]: 46003 : if (am_walsender)
5230 : : {
5231 [ # # ]: 0 : if (firstchar == PqMsg_FunctionCall)
5232 [ # # ]: 0 : ereport(ERROR,
5233 : : (errcode(ERRCODE_PROTOCOL_VIOLATION),
5234 : : errmsg("fastpath function calls not supported in a replication connection")));
5235 : : else
5236 [ # # ]: 0 : ereport(ERROR,
5237 : : (errcode(ERRCODE_PROTOCOL_VIOLATION),
5238 : : errmsg("extended query protocol not supported in a replication connection")));
5239 : : }
5240 : 46003 : }
5241 : :
5242 : :
5243 : : static struct rusage Save_r;
5244 : : static struct timeval Save_t;
5245 : :
5246 : : void
5247 : 10 : ResetUsage(void)
5248 : : {
5249 : 10 : getrusage(RUSAGE_SELF, &Save_r);
5250 : 10 : gettimeofday(&Save_t, NULL);
5251 : 10 : }
5252 : :
5253 : : void
5254 : 10 : ShowUsage(const char *title)
5255 : : {
5256 : : StringInfoData str;
5257 : : struct timeval user,
5258 : : sys;
5259 : : struct timeval elapse_t;
5260 : : struct rusage r;
5261 : :
5262 : 10 : getrusage(RUSAGE_SELF, &r);
5263 : 10 : gettimeofday(&elapse_t, NULL);
5264 : 10 : memcpy(&user, &r.ru_utime, sizeof(user));
5265 : 10 : memcpy(&sys, &r.ru_stime, sizeof(sys));
5266 [ - + ]: 10 : if (elapse_t.tv_usec < Save_t.tv_usec)
5267 : : {
5268 : 0 : elapse_t.tv_sec--;
5269 : 0 : elapse_t.tv_usec += 1000000;
5270 : : }
5271 [ - + ]: 10 : if (r.ru_utime.tv_usec < Save_r.ru_utime.tv_usec)
5272 : : {
5273 : 0 : r.ru_utime.tv_sec--;
5274 : 0 : r.ru_utime.tv_usec += 1000000;
5275 : : }
5276 [ - + ]: 10 : if (r.ru_stime.tv_usec < Save_r.ru_stime.tv_usec)
5277 : : {
5278 : 0 : r.ru_stime.tv_sec--;
5279 : 0 : r.ru_stime.tv_usec += 1000000;
5280 : : }
5281 : :
5282 : : /*
5283 : : * The only stats we don't show here are ixrss, idrss, isrss. It takes
5284 : : * some work to interpret them, and most platforms don't fill them in.
5285 : : */
5286 : 10 : initStringInfo(&str);
5287 : :
5288 : 10 : appendStringInfoString(&str, "! system usage stats:\n");
5289 : 10 : appendStringInfo(&str,
5290 : : "!\t%ld.%06ld s user, %ld.%06ld s system, %ld.%06ld s elapsed\n",
5291 : 10 : (long) (r.ru_utime.tv_sec - Save_r.ru_utime.tv_sec),
5292 : 10 : (long) (r.ru_utime.tv_usec - Save_r.ru_utime.tv_usec),
5293 : 10 : (long) (r.ru_stime.tv_sec - Save_r.ru_stime.tv_sec),
5294 : 10 : (long) (r.ru_stime.tv_usec - Save_r.ru_stime.tv_usec),
5295 : 10 : (long) (elapse_t.tv_sec - Save_t.tv_sec),
5296 : 10 : (long) (elapse_t.tv_usec - Save_t.tv_usec));
5297 : 10 : appendStringInfo(&str,
5298 : : "!\t[%ld.%06ld s user, %ld.%06ld s system total]\n",
5299 : 10 : (long) user.tv_sec,
5300 : 10 : (long) user.tv_usec,
5301 : 10 : (long) sys.tv_sec,
5302 : 10 : (long) sys.tv_usec);
5303 : : #ifndef WIN32
5304 : :
5305 : : /*
5306 : : * The following rusage fields are not defined by POSIX, but they're
5307 : : * present on all current Unix-like systems so we use them without any
5308 : : * special checks. Some of these could be provided in our Windows
5309 : : * emulation in src/port/win32getrusage.c with more work.
5310 : : */
5311 : 10 : appendStringInfo(&str,
5312 : : "!\t%ld kB max resident size\n",
5313 : : #if defined(__darwin__)
5314 : : /* in bytes on macOS */
5315 : : r.ru_maxrss / 1024
5316 : : #else
5317 : : /* in kilobytes on most other platforms */
5318 : : r.ru_maxrss
5319 : : #endif
5320 : : );
5321 : 10 : appendStringInfo(&str,
5322 : : "!\t%ld/%ld [%ld/%ld] filesystem blocks in/out\n",
5323 : 10 : r.ru_inblock - Save_r.ru_inblock,
5324 : : /* they only drink coffee at dec */
5325 : 10 : r.ru_oublock - Save_r.ru_oublock,
5326 : : r.ru_inblock, r.ru_oublock);
5327 : 10 : appendStringInfo(&str,
5328 : : "!\t%ld/%ld [%ld/%ld] page faults/reclaims, %ld [%ld] swaps\n",
5329 : 10 : r.ru_majflt - Save_r.ru_majflt,
5330 : 10 : r.ru_minflt - Save_r.ru_minflt,
5331 : : r.ru_majflt, r.ru_minflt,
5332 : 10 : r.ru_nswap - Save_r.ru_nswap,
5333 : : r.ru_nswap);
5334 : 10 : appendStringInfo(&str,
5335 : : "!\t%ld [%ld] signals rcvd, %ld/%ld [%ld/%ld] messages rcvd/sent\n",
5336 : 10 : r.ru_nsignals - Save_r.ru_nsignals,
5337 : : r.ru_nsignals,
5338 : 10 : r.ru_msgrcv - Save_r.ru_msgrcv,
5339 : 10 : r.ru_msgsnd - Save_r.ru_msgsnd,
5340 : : r.ru_msgrcv, r.ru_msgsnd);
5341 : 10 : appendStringInfo(&str,
5342 : : "!\t%ld/%ld [%ld/%ld] voluntary/involuntary context switches\n",
5343 : 10 : r.ru_nvcsw - Save_r.ru_nvcsw,
5344 : 10 : r.ru_nivcsw - Save_r.ru_nivcsw,
5345 : : r.ru_nvcsw, r.ru_nivcsw);
5346 : : #endif /* !WIN32 */
5347 : :
5348 : : /* remove trailing newline */
5349 [ + - ]: 10 : if (str.data[str.len - 1] == '\n')
5350 : 10 : str.data[--str.len] = '\0';
5351 : :
5352 [ + - ]: 10 : ereport(LOG,
5353 : : (errmsg_internal("%s", title),
5354 : : errdetail_internal("%s", str.data)));
5355 : :
5356 : 10 : pfree(str.data);
5357 : 10 : }
5358 : :
5359 : : /*
5360 : : * on_proc_exit handler to log end of session
5361 : : */
5362 : : static void
5363 : 41 : log_disconnections(int code, Datum arg)
5364 : : {
5365 : 41 : Port *port = MyProcPort;
5366 : : long secs;
5367 : : int usecs;
5368 : : int msecs;
5369 : : int hours,
5370 : : minutes,
5371 : : seconds;
5372 : :
5373 : 41 : TimestampDifference(MyStartTimestamp,
5374 : : GetCurrentTimestamp(),
5375 : : &secs, &usecs);
5376 : 41 : msecs = usecs / 1000;
5377 : :
5378 : 41 : hours = secs / SECS_PER_HOUR;
5379 : 41 : secs %= SECS_PER_HOUR;
5380 : 41 : minutes = secs / SECS_PER_MINUTE;
5381 : 41 : seconds = secs % SECS_PER_MINUTE;
5382 : :
5383 [ + - + + ]: 41 : ereport(LOG,
5384 : : (errmsg("disconnection: session time: %d:%02d:%02d.%03d "
5385 : : "user=%s database=%s host=%s%s%s",
5386 : : hours, minutes, seconds, msecs,
5387 : : port->user_name, port->database_name, port->remote_host,
5388 : : port->remote_port[0] ? " port=" : "", port->remote_port)));
5389 : 41 : }
5390 : :
5391 : : /*
5392 : : * Start statement timeout timer, if enabled.
5393 : : *
5394 : : * If there's already a timeout running, don't restart the timer. That
5395 : : * enables compromises between accuracy of timeouts and cost of starting a
5396 : : * timeout.
5397 : : */
5398 : : static void
5399 : 951713 : enable_statement_timeout(void)
5400 : : {
5401 : : /* must be within an xact */
5402 : : Assert(xact_started);
5403 : :
5404 [ + + ]: 951713 : if (StatementTimeout > 0
5405 [ + - + - ]: 60 : && (StatementTimeout < TransactionTimeout || TransactionTimeout == 0))
5406 : : {
5407 [ + + ]: 82 : if (!get_timeout_active(STATEMENT_TIMEOUT))
5408 : 22 : enable_timeout_after(STATEMENT_TIMEOUT, StatementTimeout);
5409 : : }
5410 : : else
5411 : : {
5412 [ - + ]: 951653 : if (get_timeout_active(STATEMENT_TIMEOUT))
5413 : 0 : disable_timeout(STATEMENT_TIMEOUT, false);
5414 : : }
5415 : 951713 : }
5416 : :
5417 : : /*
5418 : : * Disable statement timeout, if active.
5419 : : */
5420 : : static void
5421 : 870638 : disable_statement_timeout(void)
5422 : : {
5423 [ + + ]: 870638 : if (get_timeout_active(STATEMENT_TIMEOUT))
5424 : 14 : disable_timeout(STATEMENT_TIMEOUT, false);
5425 : 870638 : }
|