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