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