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