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