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