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