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