Thanks to visit codestin.com
Credit goes to doxygen.postgresql.org

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