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