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