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