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