PostgreSQL Source Code git master
Loading...
Searching...
No Matches
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-2026, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
8 *
9 *
10 * IDENTIFICATION
11 * src/backend/tcop/postgres.c
12 *
13 * NOTES
14 * this is the "main" module of the postgres backend and
15 * hence the main module of the "traffic cop".
16 *
17 *-------------------------------------------------------------------------
18 */
19
20#include "postgres.h"
21
22#include <fcntl.h>
23#include <limits.h>
24#include <signal.h>
25#include <unistd.h>
26#include <sys/resource.h>
27#include <sys/socket.h>
28#include <sys/time.h>
29
30#ifdef USE_VALGRIND
31#include <valgrind/valgrind.h>
32#endif
33
34#include "access/parallel.h"
35#include "access/printtup.h"
36#include "access/xact.h"
37#include "catalog/pg_type.h"
38#include "commands/async.h"
41#include "commands/prepare.h"
42#include "common/pg_prng.h"
43#include "jit/jit.h"
44#include "libpq/libpq.h"
45#include "libpq/pqformat.h"
46#include "libpq/pqsignal.h"
47#include "mb/pg_wchar.h"
48#include "mb/stringinfo_mb.h"
49#include "miscadmin.h"
50#include "nodes/print.h"
51#include "optimizer/optimizer.h"
52#include "parser/analyze.h"
53#include "parser/parser.h"
54#include "pg_getopt.h"
55#include "pg_trace.h"
56#include "pgstat.h"
61#include "replication/slot.h"
64#include "storage/bufmgr.h"
65#include "storage/ipc.h"
66#include "storage/pmsignal.h"
67#include "storage/proc.h"
68#include "storage/procsignal.h"
69#include "storage/sinval.h"
71#include "tcop/fastpath.h"
72#include "tcop/pquery.h"
73#include "tcop/tcopprot.h"
74#include "tcop/utility.h"
75#include "utils/guc_hooks.h"
77#include "utils/lsyscache.h"
78#include "utils/memutils.h"
79#include "utils/ps_status.h"
80#include "utils/snapmgr.h"
81#include "utils/timeout.h"
82#include "utils/timestamp.h"
83#include "utils/varlena.h"
84
85/* ----------------
86 * global variables
87 * ----------------
88 */
89const char *debug_query_string; /* client-supplied query string */
90
91/* Note: whereToSendOutput is initialized for the bootstrap/standalone case */
93
94/* flag for logging end of session */
95bool Log_disconnections = false;
96
98
99/* wait N seconds to allow attach from a debugger */
101
102/* Time between checks that the client is still connected. */
104
105/* flags for non-system relation kinds to restrict use */
107
108/* ----------------
109 * private typedefs etc
110 * ----------------
111 */
112
113/* type of argument for bind_param_error_callback */
114typedef struct BindParamCbData
115{
116 const char *portalName;
117 int paramno; /* zero-based param number, or -1 initially */
118 const char *paramval; /* textual input string, if available */
120
121/* ----------------
122 * private variables
123 * ----------------
124 */
125
126/*
127 * Flag to keep track of whether we have started a transaction.
128 * For extended query protocol this has to be remembered across messages.
129 */
130static bool xact_started = false;
131
132/*
133 * Flag to indicate that we are doing the outer loop's read-from-client,
134 * as opposed to any random read from client that might happen within
135 * commands like COPY FROM STDIN.
136 */
137static bool DoingCommandRead = false;
138
139/*
140 * Flags to implement skip-till-Sync-after-error behavior for messages of
141 * the extended query protocol.
142 */
144static bool ignore_till_sync = false;
145
146/*
147 * If an unnamed prepared statement exists, it's stored here.
148 * We keep it separate from the hashtable kept by commands/prepare.c
149 * in order to reduce overhead for short-lived queries.
150 */
152
153/* assorted command-line switches */
154static const char *userDoption = NULL; /* -D switch */
155static bool EchoQuery = false; /* -E switch */
156static bool UseSemiNewlineNewline = false; /* -j switch */
157
158/* whether or not, and why, we were canceled by conflict with recovery */
159static volatile sig_atomic_t RecoveryConflictPending = false;
161
162/* reused buffer to pass to SendRowDescriptionMessage() */
165
166/* ----------------------------------------------------------------
167 * decls for routines only used in this file
168 * ----------------------------------------------------------------
169 */
171static int interactive_getc(void);
172static int SocketBackend(StringInfo inBuf);
173static int ReadCommand(StringInfo inBuf);
174static void forbidden_in_wal_sender(char firstchar);
175static bool check_log_statement(List *stmt_list);
177static int errdetail_params(ParamListInfo params);
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);
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{
207
209 query != NULL)
210 VALGRIND_PRINTF("Valgrind detected %u error(s) during execution of \"%s\"\n",
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
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 */
287 break;
288 }
289 }
290 }
291
292 /* Not newline, or newline treated as regular character */
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())
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 */
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:
400 break;
401
405 break;
406
407 case PqMsg_Terminate:
410 ignore_till_sync = false;
411 break;
412
413 case PqMsg_Bind:
414 case PqMsg_Parse:
417 break;
418
419 case PqMsg_Close:
420 case PqMsg_Describe:
421 case PqMsg_Execute:
422 case PqMsg_Flush:
425 break;
426
427 case PqMsg_Sync:
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:
438 break;
439
440 case PqMsg_CopyDone:
441 case PqMsg_CopyFail:
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 */
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 */
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
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
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{
606
608
610 ResetUsage();
611
613
615 ShowUsage("PARSER STATISTICS");
616
617#ifdef DEBUG_NODE_TESTS_ENABLED
618
619 /* Optional debugging check: pass raw parsetrees through copyObject() */
621 {
623
624 /* This checks both copyObject() and the equal() routines... */
626 elog(WARNING, "copyObject() failed to produce an equal raw parse tree");
627 else
629 }
630
631 /*
632 * Optional debugging check: pass raw parsetrees through
633 * outfuncs/readfuncs
634 */
636 {
639
640 pfree(str);
641 /* This checks both outfuncs/readfuncs and the equal() routines... */
643 elog(WARNING, "outfuncs/readfuncs failed to produce an equal raw parse tree");
644 else
646 }
647
648#endif /* DEBUG_NODE_TESTS_ENABLED */
649
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;
677
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 */
696
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;
716
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)
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 */
749
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;
770
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 */
789
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{
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 */
822 }
823
825 ShowUsage("REWRITER STATISTICS");
826
827#ifdef DEBUG_NODE_TESTS_ENABLED
828
829 /* Optional debugging check: pass querytree through copyObject() */
831 {
832 List *new_list;
833
835 /* This checks both copyObject() and the equal() routines... */
837 elog(WARNING, "copyObject() failed to produce an equal rewritten parse tree");
838 else
840 }
841
842 /* Optional debugging check: pass querytree through outfuncs/readfuncs */
844 {
845 List *new_list = NIL;
846 ListCell *lc;
847
848 foreach(lc, querytree_list)
849 {
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
861 pfree(str);
862 }
863
864 /* This checks both outfuncs/readfuncs and the equal() routines... */
866 elog(WARNING, "outfuncs/readfuncs failed to produce an equal rewritten parse tree");
867 else
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, ExplainState *es)
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
899
901 ResetUsage();
902
903 /* call the optimizer */
904 plan = planner(querytree, query_string, cursorOptions, boundParams, es);
905
907 ShowUsage("PLANNER STATISTICS");
908
909#ifdef DEBUG_NODE_TESTS_ENABLED
910
911 /* Optional debugging check: pass plan tree through copyObject() */
913 {
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 */
931 {
932 char *str;
934
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
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, NULL);
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;
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 */
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 */
1073 {
1074 ereport(LOG,
1075 (errmsg("statement: %s", query_string),
1076 errhidestmt(true),
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 */
1095
1096 /*
1097 * Run through the raw parsetree(s) and process each one.
1098 */
1100 {
1102 bool snapshot_set = false;
1103 CommandTag commandTag;
1104 QueryCompletion qc;
1108 Portal portal;
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, in PortalDefineQuery). Set ps_status and
1120 * do any special start-of-SQL-command processing needed by the
1121 * destination.
1122 */
1123 commandTag = CreateCommandTag(parsetree->stmt);
1125
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,
1142 errmsg("current transaction is aborted, "
1143 "commands ignored until end of transaction block")));
1144
1145 /* Make sure we are in a transaction command */
1147
1148 /*
1149 * If using an implicit transaction block, and we're not already in a
1150 * transaction block, start an implicit block to force this statement
1151 * to be grouped together with any following ones. (We must do this
1152 * each time through the loop; otherwise, a COMMIT/ROLLBACK in the
1153 * list would cause later statements to not be grouped.)
1154 */
1157
1158 /* If we got a cancel signal in parsing or prior command, quit */
1160
1161 /*
1162 * Set up a snapshot if parse analysis/planning will need one.
1163 */
1164 if (analyze_requires_snapshot(parsetree))
1165 {
1167 snapshot_set = true;
1168 }
1169
1170 /*
1171 * OK to analyze, rewrite, and plan this query.
1172 *
1173 * Switch to appropriate context for constructing query and plan trees
1174 * (these can't be in the transaction context, as that will get reset
1175 * when the command is COMMIT/ROLLBACK). If we have multiple
1176 * parsetrees, we use a separate context for each one, so that we can
1177 * free that memory before moving on to the next one. But for the
1178 * last (or only) parsetree, just use MessageContext, which will be
1179 * reset shortly after completion anyway. In event of an error, the
1180 * per_parsetree_context will be deleted when MessageContext is reset.
1181 */
1183 {
1186 "per-parsetree message context",
1189 }
1190 else
1192
1193 querytree_list = pg_analyze_and_rewrite_fixedparams(parsetree, query_string,
1194 NULL, 0, NULL);
1195
1198
1199 /*
1200 * Done with the snapshot used for parsing/planning.
1201 *
1202 * While it looks promising to reuse the same snapshot for query
1203 * execution (at least for simple protocol), unfortunately it causes
1204 * execution to use a snapshot that has been acquired before locking
1205 * any of the tables mentioned in the query. This creates user-
1206 * visible anomalies, so refrain. Refer to
1207 * https://postgr.es/m/flat/5075D8DF.6050500@fuzzy.cz for details.
1208 */
1209 if (snapshot_set)
1211
1212 /* If we got a cancel signal in analysis or planning, quit */
1214
1215 /*
1216 * Create unnamed portal to run the query or queries in. If there
1217 * already is one, silently drop it.
1218 */
1219 portal = CreatePortal("", true, true);
1220 /* Don't display the portal in pg_cursors */
1221 portal->visible = false;
1222
1223 /*
1224 * We don't have to copy anything into the portal, because everything
1225 * we are passing here is in MessageContext or the
1226 * per_parsetree_context, and so will outlive the portal anyway.
1227 */
1228 PortalDefineQuery(portal,
1229 NULL,
1230 query_string,
1231 commandTag,
1233 NULL);
1234
1235 /*
1236 * Start the portal. No parameters here.
1237 */
1238 PortalStart(portal, NULL, 0, InvalidSnapshot);
1239
1240 /*
1241 * Select the appropriate output format: text unless we are doing a
1242 * FETCH from a binary cursor. (Pretty grotty to have to do this here
1243 * --- but it avoids grottiness in other places. Ah, the joys of
1244 * backward compatibility...)
1245 */
1246 format = 0; /* TEXT is default */
1247 if (IsA(parsetree->stmt, FetchStmt))
1248 {
1249 FetchStmt *stmt = (FetchStmt *) parsetree->stmt;
1250
1251 if (!stmt->ismove)
1252 {
1253 Portal fportal = GetPortalByName(stmt->portalname);
1254
1255 if (PortalIsValid(fportal) &&
1256 (fportal->cursorOptions & CURSOR_OPT_BINARY))
1257 format = 1; /* BINARY */
1258 }
1259 }
1260 PortalSetResultFormat(portal, 1, &format);
1261
1262 /*
1263 * Now we can create the destination receiver object.
1264 */
1266 if (dest == DestRemote)
1268
1269 /*
1270 * Switch back to transaction context for execution.
1271 */
1272 MemoryContextSwitchTo(oldcontext);
1273
1274 /*
1275 * Run the portal to completion, and then drop it (and the receiver).
1276 */
1277 (void) PortalRun(portal,
1278 FETCH_ALL,
1279 true, /* always top level */
1280 receiver,
1281 receiver,
1282 &qc);
1283
1284 receiver->rDestroy(receiver);
1285
1286 PortalDrop(portal, false);
1287
1289 {
1290 /*
1291 * If this is the last parsetree of the query string, close down
1292 * transaction statement before reporting command-complete. This
1293 * is so that any end-of-transaction errors are reported before
1294 * the command-complete message is issued, to avoid confusing
1295 * clients who will expect either a command-complete message or an
1296 * error, not one and then the other. Also, if we're using an
1297 * implicit transaction block, we must close that out first.
1298 */
1302 }
1303 else if (IsA(parsetree->stmt, TransactionStmt))
1304 {
1305 /*
1306 * If this was a transaction control statement, commit it. We will
1307 * start a new xact command for the next command.
1308 */
1310 }
1311 else
1312 {
1313 /*
1314 * We had better not see XACT_FLAGS_NEEDIMMEDIATECOMMIT set if
1315 * we're not calling finish_xact_command(). (The implicit
1316 * transaction block should have prevented it from getting set.)
1317 */
1319
1320 /*
1321 * We need a CommandCounterIncrement after every query, except
1322 * those that start or end a transaction block.
1323 */
1325
1326 /*
1327 * Disable statement timeout between queries of a multi-query
1328 * string, so that the timeout applies separately to each query.
1329 * (Our next loop iteration will start a fresh timeout.)
1330 */
1332 }
1333
1334 /*
1335 * Tell client that we're done with this query. Note we emit exactly
1336 * one EndCommand report for each raw parsetree, thus one for each SQL
1337 * command the client sent, regardless of rewriting. (But a command
1338 * aborted by error will not send an EndCommand report at all.)
1339 */
1340 EndCommand(&qc, dest, false);
1341
1342 /* Now we may drop the per-parsetree context, if one was created. */
1345 } /* end loop over parsetrees */
1346
1347 /*
1348 * Close down transaction statement, if one is open. (This will only do
1349 * something if the parsetree list was empty; otherwise the last loop
1350 * iteration already did it.)
1351 */
1353
1354 /*
1355 * If there were no parsetrees, return EmptyQueryResponse message.
1356 */
1357 if (!parsetree_list)
1358 NullCommand(dest);
1359
1360 /*
1361 * Emit duration logging if appropriate.
1362 */
1364 {
1365 case 1:
1366 ereport(LOG,
1367 (errmsg("duration: %s ms", msec_str),
1368 errhidestmt(true)));
1369 break;
1370 case 2:
1371 ereport(LOG,
1372 (errmsg("duration: %s ms statement: %s",
1373 msec_str, query_string),
1374 errhidestmt(true),
1376 break;
1377 }
1378
1380 ShowUsage("QUERY STATISTICS");
1381
1382 TRACE_POSTGRESQL_QUERY_DONE(query_string);
1383
1385}
1386
1387/*
1388 * exec_parse_message
1389 *
1390 * Execute a "Parse" protocol message.
1391 */
1392static void
1393exec_parse_message(const char *query_string, /* string to execute */
1394 const char *stmt_name, /* name for prepared stmt */
1395 Oid *paramTypes, /* parameter types */
1396 int numParams) /* number of parameters */
1397{
1399 MemoryContext oldcontext;
1401 RawStmt *raw_parse_tree;
1404 bool is_named;
1406 char msec_str[32];
1407
1408 /*
1409 * Report query to various monitoring facilities.
1410 */
1411 debug_query_string = query_string;
1412
1414
1415 set_ps_display("PARSE");
1416
1418 ResetUsage();
1419
1421 (errmsg_internal("parse %s: %s",
1422 *stmt_name ? stmt_name : "<unnamed>",
1423 query_string)));
1424
1425 /*
1426 * Start up a transaction command so we can run parse analysis etc. (Note
1427 * that this will normally change current memory context.) Nothing happens
1428 * if we are already in one. This also arms the statement timeout if
1429 * necessary.
1430 */
1432
1433 /*
1434 * Switch to appropriate context for constructing parsetrees.
1435 *
1436 * We have two strategies depending on whether the prepared statement is
1437 * named or not. For a named prepared statement, we do parsing in
1438 * MessageContext and copy the finished trees into the prepared
1439 * statement's plancache entry; then the reset of MessageContext releases
1440 * temporary space used by parsing and rewriting. For an unnamed prepared
1441 * statement, we assume the statement isn't going to hang around long, so
1442 * getting rid of temp space quickly is probably not worth the costs of
1443 * copying parse trees. So in this case, we create the plancache entry's
1444 * query_context here, and do all the parsing work therein.
1445 */
1446 is_named = (stmt_name[0] != '\0');
1447 if (is_named)
1448 {
1449 /* Named prepared statement --- parse in MessageContext */
1451 }
1452 else
1453 {
1454 /* Unnamed prepared statement --- release any prior unnamed stmt */
1456 /* Create context for parsing */
1459 "unnamed prepared statement",
1462 }
1463
1464 /*
1465 * Do basic parsing of the query or queries (this should be safe even if
1466 * we are in aborted transaction state!)
1467 */
1468 parsetree_list = pg_parse_query(query_string);
1469
1470 /*
1471 * We only allow a single user statement in a prepared statement. This is
1472 * mainly to keep the protocol simple --- otherwise we'd need to worry
1473 * about multiple result tupdescs and things like that.
1474 */
1475 if (list_length(parsetree_list) > 1)
1476 ereport(ERROR,
1478 errmsg("cannot insert multiple commands into a prepared statement")));
1479
1480 if (parsetree_list != NIL)
1481 {
1482 bool snapshot_set = false;
1483
1484 raw_parse_tree = linitial_node(RawStmt, parsetree_list);
1485
1486 /*
1487 * If we are in an aborted transaction, reject all commands except
1488 * COMMIT/ROLLBACK. It is important that this test occur before we
1489 * try to do parse analysis, rewrite, or planning, since all those
1490 * phases try to do database accesses, which may fail in abort state.
1491 * (It might be safe to allow some additional utility commands in this
1492 * state, but not many...)
1493 */
1495 !IsTransactionExitStmt(raw_parse_tree->stmt))
1496 ereport(ERROR,
1498 errmsg("current transaction is aborted, "
1499 "commands ignored until end of transaction block")));
1500
1501 /*
1502 * Create the CachedPlanSource before we do parse analysis, since it
1503 * needs to see the unmodified raw parse tree.
1504 */
1505 psrc = CreateCachedPlan(raw_parse_tree, query_string,
1506 CreateCommandTag(raw_parse_tree->stmt));
1507
1508 /*
1509 * Set up a snapshot if parse analysis will need one.
1510 */
1511 if (analyze_requires_snapshot(raw_parse_tree))
1512 {
1514 snapshot_set = true;
1515 }
1516
1517 /*
1518 * Analyze and rewrite the query. Note that the originally specified
1519 * parameter set is not required to be complete, so we have to use
1520 * pg_analyze_and_rewrite_varparams().
1521 */
1523 query_string,
1524 &paramTypes,
1525 &numParams,
1526 NULL);
1527
1528 /* Done with the snapshot used for parsing */
1529 if (snapshot_set)
1531 }
1532 else
1533 {
1534 /* Empty input string. This is legal. */
1535 raw_parse_tree = NULL;
1536 psrc = CreateCachedPlan(raw_parse_tree, query_string,
1539 }
1540
1541 /*
1542 * CachedPlanSource must be a direct child of MessageContext before we
1543 * reparent unnamed_stmt_context under it, else we have a disconnected
1544 * circular subgraph. Klugy, but less so than flipping contexts even more
1545 * above.
1546 */
1549
1550 /* Finish filling in the CachedPlanSource */
1554 paramTypes,
1555 numParams,
1556 NULL,
1557 NULL,
1558 CURSOR_OPT_PARALLEL_OK, /* allow parallel mode */
1559 true); /* fixed result */
1560
1561 /* If we got a cancel signal during analysis, quit */
1563
1564 if (is_named)
1565 {
1566 /*
1567 * Store the query as a prepared statement.
1568 */
1569 StorePreparedStatement(stmt_name, psrc, false);
1570 }
1571 else
1572 {
1573 /*
1574 * We just save the CachedPlanSource into unnamed_stmt_psrc.
1575 */
1578 }
1579
1580 MemoryContextSwitchTo(oldcontext);
1581
1582 /*
1583 * We do NOT close the open transaction command here; that only happens
1584 * when the client sends Sync. Instead, do CommandCounterIncrement just
1585 * in case something happened during parse/plan.
1586 */
1588
1589 /*
1590 * Send ParseComplete.
1591 */
1594
1595 /*
1596 * Emit duration logging if appropriate.
1597 */
1598 switch (check_log_duration(msec_str, false))
1599 {
1600 case 1:
1601 ereport(LOG,
1602 (errmsg("duration: %s ms", msec_str),
1603 errhidestmt(true)));
1604 break;
1605 case 2:
1606 ereport(LOG,
1607 (errmsg("duration: %s ms parse %s: %s",
1608 msec_str,
1609 *stmt_name ? stmt_name : "<unnamed>",
1610 query_string),
1611 errhidestmt(true)));
1612 break;
1613 }
1614
1616 ShowUsage("PARSE MESSAGE STATISTICS");
1617
1619}
1620
1621/*
1622 * exec_bind_message
1623 *
1624 * Process a "Bind" message to create a portal from a prepared statement
1625 */
1626static void
1628{
1629 const char *portal_name;
1630 const char *stmt_name;
1631 int numPFormats;
1632 int16 *pformats = NULL;
1633 int numParams;
1634 int numRFormats;
1635 int16 *rformats = NULL;
1637 CachedPlan *cplan;
1638 Portal portal;
1639 char *query_string;
1640 char *saved_stmt_name;
1641 ParamListInfo params;
1644 bool snapshot_set = false;
1645 char msec_str[32];
1648 ListCell *lc;
1649
1650 /* Get the fixed part of the message */
1652 stmt_name = pq_getmsgstring(input_message);
1653
1655 (errmsg_internal("bind %s to %s",
1656 *portal_name ? portal_name : "<unnamed>",
1657 *stmt_name ? stmt_name : "<unnamed>")));
1658
1659 /* Find prepared statement */
1660 if (stmt_name[0] != '\0')
1661 {
1662 PreparedStatement *pstmt;
1663
1664 pstmt = FetchPreparedStatement(stmt_name, true);
1665 psrc = pstmt->plansource;
1666 }
1667 else
1668 {
1669 /* special-case the unnamed statement */
1671 if (!psrc)
1672 ereport(ERROR,
1674 errmsg("unnamed prepared statement does not exist")));
1675 }
1676
1677 /*
1678 * Report query to various monitoring facilities.
1679 */
1680 debug_query_string = psrc->query_string;
1681
1683
1684 foreach(lc, psrc->query_list)
1685 {
1686 Query *query = lfirst_node(Query, lc);
1687
1688 if (query->queryId != INT64CONST(0))
1689 {
1690 pgstat_report_query_id(query->queryId, false);
1691 break;
1692 }
1693 }
1694
1695 set_ps_display("BIND");
1696
1698 ResetUsage();
1699
1700 /*
1701 * Start up a transaction command so we can call functions etc. (Note that
1702 * this will normally change current memory context.) Nothing happens if
1703 * we are already in one. This also arms the statement timeout if
1704 * necessary.
1705 */
1707
1708 /* Switch back to message context */
1710
1711 /* Get the parameter format codes */
1713 if (numPFormats > 0)
1714 {
1716 for (int i = 0; i < numPFormats; i++)
1718 }
1719
1720 /* Get the parameter value count */
1721 numParams = pq_getmsgint(input_message, 2);
1722
1723 if (numPFormats > 1 && numPFormats != numParams)
1724 ereport(ERROR,
1726 errmsg("bind message has %d parameter formats but %d parameters",
1727 numPFormats, numParams)));
1728
1729 if (numParams != psrc->num_params)
1730 ereport(ERROR,
1732 errmsg("bind message supplies %d parameters, but prepared statement \"%s\" requires %d",
1733 numParams, stmt_name, psrc->num_params)));
1734
1735 /*
1736 * If we are in aborted transaction state, the only portals we can
1737 * actually run are those containing COMMIT or ROLLBACK commands. We
1738 * disallow binding anything else to avoid problems with infrastructure
1739 * that expects to run inside a valid transaction. We also disallow
1740 * binding any parameters, since we can't risk calling user-defined I/O
1741 * functions.
1742 */
1744 (!(psrc->raw_parse_tree &&
1745 IsTransactionExitStmt(psrc->raw_parse_tree->stmt)) ||
1746 numParams != 0))
1747 ereport(ERROR,
1749 errmsg("current transaction is aborted, "
1750 "commands ignored until end of transaction block")));
1751
1752 /*
1753 * Create the portal. Allow silent replacement of an existing portal only
1754 * if the unnamed portal is specified.
1755 */
1756 if (portal_name[0] == '\0')
1757 portal = CreatePortal(portal_name, true, true);
1758 else
1759 portal = CreatePortal(portal_name, false, false);
1760
1761 /*
1762 * Prepare to copy stuff into the portal's memory context. We do all this
1763 * copying first, because it could possibly fail (out-of-memory) and we
1764 * don't want a failure to occur between GetCachedPlan and
1765 * PortalDefineQuery; that would result in leaking our plancache refcount.
1766 */
1768
1769 /* Copy the plan's query string into the portal */
1770 query_string = pstrdup(psrc->query_string);
1771
1772 /* Likewise make a copy of the statement name, unless it's unnamed */
1773 if (stmt_name[0])
1774 saved_stmt_name = pstrdup(stmt_name);
1775 else
1777
1778 /*
1779 * Set a snapshot if we have parameters to fetch (since the input
1780 * functions might need it) or the query isn't a utility command (and
1781 * hence could require redoing parse analysis and planning). We keep the
1782 * snapshot active till we're done, so that plancache.c doesn't have to
1783 * take new ones.
1784 */
1785 if (numParams > 0 ||
1786 (psrc->raw_parse_tree &&
1787 analyze_requires_snapshot(psrc->raw_parse_tree)))
1788 {
1790 snapshot_set = true;
1791 }
1792
1793 /*
1794 * Fetch parameters, if any, and store in the portal's memory context.
1795 */
1796 if (numParams > 0)
1797 {
1798 char **knownTextValues = NULL; /* allocate on first use */
1800
1801 /*
1802 * Set up an error callback so that if there's an error in this phase,
1803 * we can report the specific parameter causing the problem.
1804 */
1805 one_param_data.portalName = portal->name;
1806 one_param_data.paramno = -1;
1807 one_param_data.paramval = NULL;
1812
1813 params = makeParamList(numParams);
1814
1815 for (int paramno = 0; paramno < numParams; paramno++)
1816 {
1817 Oid ptype = psrc->param_types[paramno];
1818 int32 plength;
1819 Datum pval;
1820 bool isNull;
1822 char csave;
1823 int16 pformat;
1824
1825 one_param_data.paramno = paramno;
1826 one_param_data.paramval = NULL;
1827
1829 isNull = (plength == -1);
1830
1831 if (!isNull)
1832 {
1833 char *pvalue;
1834
1835 /*
1836 * Rather than copying data around, we just initialize a
1837 * StringInfo pointing to the correct portion of the message
1838 * buffer. We assume we can scribble on the message buffer to
1839 * add a trailing NUL which is required for the input function
1840 * call.
1841 */
1843 csave = pvalue[plength];
1844 pvalue[plength] = '\0';
1846 }
1847 else
1848 {
1849 pbuf.data = NULL; /* keep compiler quiet */
1850 csave = 0;
1851 }
1852
1853 if (numPFormats > 1)
1854 pformat = pformats[paramno];
1855 else if (numPFormats > 0)
1856 pformat = pformats[0];
1857 else
1858 pformat = 0; /* default = text */
1859
1860 if (pformat == 0) /* text mode */
1861 {
1862 Oid typinput;
1863 Oid typioparam;
1864 char *pstring;
1865
1866 getTypeInputInfo(ptype, &typinput, &typioparam);
1867
1868 /*
1869 * We have to do encoding conversion before calling the
1870 * typinput routine.
1871 */
1872 if (isNull)
1873 pstring = NULL;
1874 else
1876
1877 /* Now we can log the input string in case of error */
1878 one_param_data.paramval = pstring;
1879
1880 pval = OidInputFunctionCall(typinput, pstring, typioparam, -1);
1881
1882 one_param_data.paramval = NULL;
1883
1884 /*
1885 * If we might need to log parameters later, save a copy of
1886 * the converted string in MessageContext; then free the
1887 * result of encoding conversion, if any was done.
1888 */
1889 if (pstring)
1890 {
1892 {
1894
1896
1897 if (knownTextValues == NULL)
1898 knownTextValues = palloc0_array(char *, numParams);
1899
1901 knownTextValues[paramno] = pstrdup(pstring);
1902 else
1903 {
1904 /*
1905 * We can trim the saved string, knowing that we
1906 * won't print all of it. But we must copy at
1907 * least two more full characters than
1908 * BuildParamLogString wants to use; otherwise it
1909 * might fail to include the trailing ellipsis.
1910 */
1911 knownTextValues[paramno] =
1915 }
1916
1918 }
1919 if (pstring != pbuf.data)
1920 pfree(pstring);
1921 }
1922 }
1923 else if (pformat == 1) /* binary mode */
1924 {
1925 Oid typreceive;
1926 Oid typioparam;
1927 StringInfo bufptr;
1928
1929 /*
1930 * Call the parameter type's binary input converter
1931 */
1932 getTypeBinaryInputInfo(ptype, &typreceive, &typioparam);
1933
1934 if (isNull)
1935 bufptr = NULL;
1936 else
1937 bufptr = &pbuf;
1938
1939 pval = OidReceiveFunctionCall(typreceive, bufptr, typioparam, -1);
1940
1941 /* Trouble if it didn't eat the whole buffer */
1942 if (!isNull && pbuf.cursor != pbuf.len)
1943 ereport(ERROR,
1945 errmsg("incorrect binary data format in bind parameter %d",
1946 paramno + 1)));
1947 }
1948 else
1949 {
1950 ereport(ERROR,
1952 errmsg("unsupported format code: %d",
1953 pformat)));
1954 pval = 0; /* keep compiler quiet */
1955 }
1956
1957 /* Restore message buffer contents */
1958 if (!isNull)
1959 pbuf.data[plength] = csave;
1960
1961 params->params[paramno].value = pval;
1962 params->params[paramno].isnull = isNull;
1963
1964 /*
1965 * We mark the params as CONST. This ensures that any custom plan
1966 * makes full use of the parameter values.
1967 */
1968 params->params[paramno].pflags = PARAM_FLAG_CONST;
1969 params->params[paramno].ptype = ptype;
1970 }
1971
1972 /* Pop the per-parameter error callback */
1974
1975 /*
1976 * Once all parameters have been received, prepare for printing them
1977 * in future errors, if configured to do so. (This is saved in the
1978 * portal, so that they'll appear when the query is executed later.)
1979 */
1981 params->paramValuesStr =
1982 BuildParamLogString(params,
1985 }
1986 else
1987 params = NULL;
1988
1989 /* Done storing stuff in portal's context */
1991
1992 /*
1993 * Set up another error callback so that all the parameters are logged if
1994 * we get an error during the rest of the BIND processing.
1995 */
1996 params_data.portalName = portal->name;
1997 params_data.params = params;
2002
2003 /* Get the result format codes */
2005 if (numRFormats > 0)
2006 {
2008 for (int i = 0; i < numRFormats; i++)
2010 }
2011
2013
2014 /*
2015 * Obtain a plan from the CachedPlanSource. Any cruft from (re)planning
2016 * will be generated in MessageContext. The plan refcount will be
2017 * assigned to the Portal, so it will be released at portal destruction.
2018 */
2019 cplan = GetCachedPlan(psrc, params, NULL, NULL);
2020
2021 /*
2022 * Now we can define the portal.
2023 *
2024 * DO NOT put any code that could possibly throw an error between the
2025 * above GetCachedPlan call and here.
2026 */
2027 PortalDefineQuery(portal,
2029 query_string,
2031 cplan->stmt_list,
2032 cplan);
2033
2034 /* Portal is defined, set the plan ID based on its contents. */
2035 foreach(lc, portal->stmts)
2036 {
2038
2039 if (plan->planId != INT64CONST(0))
2040 {
2041 pgstat_report_plan_id(plan->planId, false);
2042 break;
2043 }
2044 }
2045
2046 /* Done with the snapshot used for parameter I/O and parsing/planning */
2047 if (snapshot_set)
2049
2050 /*
2051 * And we're ready to start portal execution.
2052 */
2053 PortalStart(portal, params, 0, InvalidSnapshot);
2054
2055 /*
2056 * Apply the result format requests to the portal.
2057 */
2059
2060 /*
2061 * Done binding; remove the parameters error callback. Entries emitted
2062 * later determine independently whether to log the parameters or not.
2063 */
2065
2066 /*
2067 * Send BindComplete.
2068 */
2071
2072 /*
2073 * Emit duration logging if appropriate.
2074 */
2075 switch (check_log_duration(msec_str, false))
2076 {
2077 case 1:
2078 ereport(LOG,
2079 (errmsg("duration: %s ms", msec_str),
2080 errhidestmt(true)));
2081 break;
2082 case 2:
2083 ereport(LOG,
2084 (errmsg("duration: %s ms bind %s%s%s: %s",
2085 msec_str,
2086 *stmt_name ? stmt_name : "<unnamed>",
2087 *portal_name ? "/" : "",
2088 *portal_name ? portal_name : "",
2089 psrc->query_string),
2090 errhidestmt(true),
2091 errdetail_params(params)));
2092 break;
2093 }
2094
2096 ShowUsage("BIND MESSAGE STATISTICS");
2097
2099
2101}
2102
2103/*
2104 * exec_execute_message
2105 *
2106 * Process an "Execute" message for a portal
2107 */
2108static void
2110{
2111 CommandDest dest;
2113 Portal portal;
2114 bool completed;
2115 QueryCompletion qc;
2116 const char *sourceText;
2117 const char *prepStmtName;
2118 ParamListInfo portalParams;
2120 bool is_xact_command;
2121 bool execute_is_fetch;
2122 bool was_logged = false;
2123 char msec_str[32];
2126 const char *cmdtagname;
2127 size_t cmdtaglen;
2128 ListCell *lc;
2129
2130 /* Adjust destination to tell printtup.c what to do */
2131 dest = whereToSendOutput;
2132 if (dest == DestRemote)
2133 dest = DestRemoteExecute;
2134
2135 portal = GetPortalByName(portal_name);
2136 if (!PortalIsValid(portal))
2137 ereport(ERROR,
2139 errmsg("portal \"%s\" does not exist", portal_name)));
2140
2141 /*
2142 * If the original query was a null string, just return
2143 * EmptyQueryResponse.
2144 */
2145 if (portal->commandTag == CMDTAG_UNKNOWN)
2146 {
2147 Assert(portal->stmts == NIL);
2148 NullCommand(dest);
2149 return;
2150 }
2151
2152 /* Does the portal contain a transaction command? */
2154
2155 /*
2156 * We must copy the sourceText and prepStmtName into MessageContext in
2157 * case the portal is destroyed during finish_xact_command. We do not
2158 * make a copy of the portalParams though, preferring to just not print
2159 * them in that case.
2160 */
2161 sourceText = pstrdup(portal->sourceText);
2162 if (portal->prepStmtName)
2163 prepStmtName = pstrdup(portal->prepStmtName);
2164 else
2165 prepStmtName = "<unnamed>";
2166 portalParams = portal->portalParams;
2167
2168 /*
2169 * Report query to various monitoring facilities.
2170 */
2171 debug_query_string = sourceText;
2172
2174
2175 foreach(lc, portal->stmts)
2176 {
2178
2179 if (stmt->queryId != INT64CONST(0))
2180 {
2181 pgstat_report_query_id(stmt->queryId, false);
2182 break;
2183 }
2184 }
2185
2186 foreach(lc, portal->stmts)
2187 {
2189
2190 if (stmt->planId != INT64CONST(0))
2191 {
2192 pgstat_report_plan_id(stmt->planId, false);
2193 break;
2194 }
2195 }
2196
2198
2200
2202 ResetUsage();
2203
2204 BeginCommand(portal->commandTag, dest);
2205
2206 /*
2207 * Create dest receiver in MessageContext (we don't want it in transaction
2208 * context, because that may get deleted if portal contains VACUUM).
2209 */
2211 if (dest == DestRemoteExecute)
2213
2214 /*
2215 * Ensure we are in a transaction command (this should normally be the
2216 * case already due to prior BIND).
2217 */
2219
2220 /*
2221 * If we re-issue an Execute protocol request against an existing portal,
2222 * then we are only fetching more rows rather than completely re-executing
2223 * the query from the start. atStart is never reset for a v3 portal, so we
2224 * are safe to use this check.
2225 */
2226 execute_is_fetch = !portal->atStart;
2227
2228 /* Log immediately if dictated by log_statement */
2229 if (check_log_statement(portal->stmts))
2230 {
2231 ereport(LOG,
2232 (errmsg("%s %s%s%s: %s",
2234 _("execute fetch from") :
2235 _("execute"),
2236 prepStmtName,
2237 *portal_name ? "/" : "",
2238 *portal_name ? portal_name : "",
2239 sourceText),
2240 errhidestmt(true),
2241 errdetail_params(portalParams)));
2242 was_logged = true;
2243 }
2244
2245 /*
2246 * If we are in aborted transaction state, the only portals we can
2247 * actually run are those containing COMMIT or ROLLBACK commands.
2248 */
2251 ereport(ERROR,
2253 errmsg("current transaction is aborted, "
2254 "commands ignored until end of transaction block")));
2255
2256 /* Check for cancel signal before we start execution */
2258
2259 /*
2260 * Okay to run the portal. Set the error callback so that parameters are
2261 * logged. The parameters must have been saved during the bind phase.
2262 */
2263 params_data.portalName = portal->name;
2264 params_data.params = portalParams;
2269
2270 if (max_rows <= 0)
2272
2273 completed = PortalRun(portal,
2274 max_rows,
2275 true, /* always top level */
2276 receiver,
2277 receiver,
2278 &qc);
2279
2280 receiver->rDestroy(receiver);
2281
2282 /* Done executing; remove the params error callback */
2284
2285 if (completed)
2286 {
2288 {
2289 /*
2290 * If this was a transaction control statement, commit it. We
2291 * will start a new xact command for the next command (if any).
2292 * Likewise if the statement required immediate commit. Without
2293 * this provision, we wouldn't force commit until Sync is
2294 * received, which creates a hazard if the client tries to
2295 * pipeline immediate-commit statements.
2296 */
2298
2299 /*
2300 * These commands typically don't have any parameters, and even if
2301 * one did we couldn't print them now because the storage went
2302 * away during finish_xact_command. So pretend there were none.
2303 */
2304 portalParams = NULL;
2305 }
2306 else
2307 {
2308 /*
2309 * We need a CommandCounterIncrement after every query, except
2310 * those that start or end a transaction block.
2311 */
2313
2314 /*
2315 * Set XACT_FLAGS_PIPELINING whenever we complete an Execute
2316 * message without immediately committing the transaction.
2317 */
2319
2320 /*
2321 * Disable statement timeout whenever we complete an Execute
2322 * message. The next protocol message will start a fresh timeout.
2323 */
2325 }
2326
2327 /* Send appropriate CommandComplete to client */
2328 EndCommand(&qc, dest, false);
2329 }
2330 else
2331 {
2332 /* Portal run not complete, so send PortalSuspended */
2335
2336 /*
2337 * Set XACT_FLAGS_PIPELINING whenever we suspend an Execute message,
2338 * too.
2339 */
2341 }
2342
2343 /*
2344 * Emit duration logging if appropriate.
2345 */
2347 {
2348 case 1:
2349 ereport(LOG,
2350 (errmsg("duration: %s ms", msec_str),
2351 errhidestmt(true)));
2352 break;
2353 case 2:
2354 ereport(LOG,
2355 (errmsg("duration: %s ms %s %s%s%s: %s",
2356 msec_str,
2358 _("execute fetch from") :
2359 _("execute"),
2360 prepStmtName,
2361 *portal_name ? "/" : "",
2362 *portal_name ? portal_name : "",
2363 sourceText),
2364 errhidestmt(true),
2365 errdetail_params(portalParams)));
2366 break;
2367 }
2368
2370 ShowUsage("EXECUTE MESSAGE STATISTICS");
2371
2373
2375}
2376
2377/*
2378 * check_log_statement
2379 * Determine whether command should be logged because of log_statement
2380 *
2381 * stmt_list can be either raw grammar output or a list of planned
2382 * statements
2383 */
2384static bool
2386{
2388
2390 return false;
2392 return true;
2393
2394 /* Else we have to inspect the statement(s) to see whether to log */
2395 foreach(stmt_item, stmt_list)
2396 {
2397 Node *stmt = (Node *) lfirst(stmt_item);
2398
2400 return true;
2401 }
2402
2403 return false;
2404}
2405
2406/*
2407 * check_log_duration
2408 * Determine whether current command's duration should be logged
2409 * We also check if this statement in this transaction must be logged
2410 * (regardless of its duration).
2411 *
2412 * Returns:
2413 * 0 if no logging is needed
2414 * 1 if just the duration should be logged
2415 * 2 if duration and query details should be logged
2416 *
2417 * If logging is needed, the duration in msec is formatted into msec_str[],
2418 * which must be a 32-byte buffer.
2419 *
2420 * was_logged should be true if caller already logged query details (this
2421 * essentially prevents 2 from being returned).
2422 */
2423int
2425{
2428 {
2429 long secs;
2430 int usecs;
2431 int msecs;
2432 bool exceeded_duration;
2434 bool in_sample = false;
2435
2438 &secs, &usecs);
2439 msecs = usecs / 1000;
2440
2441 /*
2442 * This odd-looking test for log_min_duration_* being exceeded is
2443 * designed to avoid integer overflow with very long durations: don't
2444 * compute secs * 1000 until we've verified it will fit in int.
2445 */
2448 (secs > log_min_duration_statement / 1000 ||
2449 secs * 1000 + msecs >= log_min_duration_statement)));
2450
2453 (secs > log_min_duration_sample / 1000 ||
2454 secs * 1000 + msecs >= log_min_duration_sample)));
2455
2456 /*
2457 * Do not log if log_statement_sample_rate = 0. Log a sample if
2458 * log_statement_sample_rate <= 1 and avoid unnecessary PRNG call if
2459 * log_statement_sample_rate = 1.
2460 */
2465
2467 {
2468 snprintf(msec_str, 32, "%ld.%03d",
2469 secs * 1000 + msecs, usecs % 1000);
2471 return 2;
2472 else
2473 return 1;
2474 }
2475 }
2476
2477 return 0;
2478}
2479
2480/*
2481 * errdetail_execute
2482 *
2483 * Add an errdetail() line showing the query referenced by an EXECUTE, if any.
2484 * The argument is the raw parsetree list.
2485 */
2486static int
2488{
2490
2492 {
2494
2495 if (IsA(parsetree->stmt, ExecuteStmt))
2496 {
2497 ExecuteStmt *stmt = (ExecuteStmt *) parsetree->stmt;
2498 PreparedStatement *pstmt;
2499
2500 pstmt = FetchPreparedStatement(stmt->name, false);
2501 if (pstmt)
2502 {
2503 errdetail("prepare: %s", pstmt->plansource->query_string);
2504 return 0;
2505 }
2506 }
2507 }
2508
2509 return 0;
2510}
2511
2512/*
2513 * errdetail_params
2514 *
2515 * Add an errdetail() line showing bind-parameter data, if available.
2516 * Note that this is only used for statement logging, so it is controlled
2517 * by log_parameter_max_length not log_parameter_max_length_on_error.
2518 */
2519static int
2521{
2522 if (params && params->numParams > 0 && log_parameter_max_length != 0)
2523 {
2524 char *str;
2525
2527 if (str && str[0] != '\0')
2528 errdetail("Parameters: %s", str);
2529 }
2530
2531 return 0;
2532}
2533
2534/*
2535 * errdetail_recovery_conflict
2536 *
2537 * Add an errdetail() line showing conflict source.
2538 */
2539static int
2541{
2542 switch (reason)
2543 {
2545 errdetail("User was holding shared buffer pin for too long.");
2546 break;
2548 errdetail("User was holding a relation lock for too long.");
2549 break;
2551 errdetail("User was or might have been using tablespace that must be dropped.");
2552 break;
2554 errdetail("User query might have needed to see row versions that must be removed.");
2555 break;
2557 errdetail("User was using a logical replication slot that must be invalidated.");
2558 break;
2560 errdetail("User transaction caused buffer deadlock with recovery.");
2561 break;
2563 errdetail("User was connected to a database that must be dropped.");
2564 break;
2565 default:
2566 break;
2567 /* no errdetail */
2568 }
2569
2570 return 0;
2571}
2572
2573/*
2574 * bind_param_error_callback
2575 *
2576 * Error context callback used while parsing parameters in a Bind message
2577 */
2578static void
2580{
2583 char *quotedval;
2584
2585 if (data->paramno < 0)
2586 return;
2587
2588 /* If we have a textual value, quote it, and trim if necessary */
2589 if (data->paramval)
2590 {
2594 quotedval = buf.data;
2595 }
2596 else
2597 quotedval = NULL;
2598
2599 if (data->portalName && data->portalName[0] != '\0')
2600 {
2601 if (quotedval)
2602 errcontext("portal \"%s\" parameter $%d = %s",
2603 data->portalName, data->paramno + 1, quotedval);
2604 else
2605 errcontext("portal \"%s\" parameter $%d",
2606 data->portalName, data->paramno + 1);
2607 }
2608 else
2609 {
2610 if (quotedval)
2611 errcontext("unnamed portal parameter $%d = %s",
2612 data->paramno + 1, quotedval);
2613 else
2614 errcontext("unnamed portal parameter $%d",
2615 data->paramno + 1);
2616 }
2617
2618 if (quotedval)
2620}
2621
2622/*
2623 * exec_describe_statement_message
2624 *
2625 * Process a "Describe" message for a prepared statement
2626 */
2627static void
2629{
2631
2632 /*
2633 * Start up a transaction command. (Note that this will normally change
2634 * current memory context.) Nothing happens if we are already in one.
2635 */
2637
2638 /* Switch back to message context */
2640
2641 /* Find prepared statement */
2642 if (stmt_name[0] != '\0')
2643 {
2644 PreparedStatement *pstmt;
2645
2646 pstmt = FetchPreparedStatement(stmt_name, true);
2647 psrc = pstmt->plansource;
2648 }
2649 else
2650 {
2651 /* special-case the unnamed statement */
2653 if (!psrc)
2654 ereport(ERROR,
2656 errmsg("unnamed prepared statement does not exist")));
2657 }
2658
2659 /* Prepared statements shouldn't have changeable result descs */
2660 Assert(psrc->fixed_result);
2661
2662 /*
2663 * If we are in aborted transaction state, we can't run
2664 * SendRowDescriptionMessage(), because that needs catalog accesses.
2665 * Hence, refuse to Describe statements that return data. (We shouldn't
2666 * just refuse all Describes, since that might break the ability of some
2667 * clients to issue COMMIT or ROLLBACK commands, if they use code that
2668 * blindly Describes whatever it does.) We can Describe parameters
2669 * without doing anything dangerous, so we don't restrict that.
2670 */
2672 psrc->resultDesc)
2673 ereport(ERROR,
2675 errmsg("current transaction is aborted, "
2676 "commands ignored until end of transaction block")));
2677
2679 return; /* can't actually do anything... */
2680
2681 /*
2682 * First describe the parameters...
2683 */
2685 pq_sendint16(&row_description_buf, psrc->num_params);
2686
2687 for (int i = 0; i < psrc->num_params; i++)
2688 {
2689 Oid ptype = psrc->param_types[i];
2690
2691 pq_sendint32(&row_description_buf, (int) ptype);
2692 }
2694
2695 /*
2696 * Next send RowDescription or NoData to describe the result...
2697 */
2698 if (psrc->resultDesc)
2699 {
2700 List *tlist;
2701
2702 /* Get the plan's primary targetlist */
2704
2706 psrc->resultDesc,
2707 tlist,
2708 NULL);
2709 }
2710 else
2712}
2713
2714/*
2715 * exec_describe_portal_message
2716 *
2717 * Process a "Describe" message for a portal
2718 */
2719static void
2721{
2722 Portal portal;
2723
2724 /*
2725 * Start up a transaction command. (Note that this will normally change
2726 * current memory context.) Nothing happens if we are already in one.
2727 */
2729
2730 /* Switch back to message context */
2732
2733 portal = GetPortalByName(portal_name);
2734 if (!PortalIsValid(portal))
2735 ereport(ERROR,
2737 errmsg("portal \"%s\" does not exist", portal_name)));
2738
2739 /*
2740 * If we are in aborted transaction state, we can't run
2741 * SendRowDescriptionMessage(), because that needs catalog accesses.
2742 * Hence, refuse to Describe portals that return data. (We shouldn't just
2743 * refuse all Describes, since that might break the ability of some
2744 * clients to issue COMMIT or ROLLBACK commands, if they use code that
2745 * blindly Describes whatever it does.)
2746 */
2748 portal->tupDesc)
2749 ereport(ERROR,
2751 errmsg("current transaction is aborted, "
2752 "commands ignored until end of transaction block")));
2753
2755 return; /* can't actually do anything... */
2756
2757 if (portal->tupDesc)
2759 portal->tupDesc,
2760 FetchPortalTargetList(portal),
2761 portal->formats);
2762 else
2764}
2765
2766
2767/*
2768 * Convenience routines for starting/committing a single command.
2769 */
2770static void
2772{
2773 if (!xact_started)
2774 {
2776
2777 xact_started = true;
2778 }
2780 {
2781 /*
2782 * When the first Execute message is completed, following commands
2783 * will be done in an implicit transaction block created via
2784 * pipelining. The transaction state needs to be updated to an
2785 * implicit block if we're not already in a transaction block (like
2786 * one started by an explicit BEGIN).
2787 */
2789 }
2790
2791 /*
2792 * Start statement timeout if necessary. Note that this'll intentionally
2793 * not reset the clock on an already started timeout, to avoid the timing
2794 * overhead when start_xact_command() is invoked repeatedly, without an
2795 * interceding finish_xact_command() (e.g. parse/bind/execute). If that's
2796 * not desired, the timeout has to be disabled explicitly.
2797 */
2799
2800 /* Start timeout for checking if the client has gone away if necessary. */
2803 MyProcPort &&
2807}
2808
2809static void
2811{
2812 /* cancel active statement timeout after each command */
2814
2815 if (xact_started)
2816 {
2818
2819#ifdef MEMORY_CONTEXT_CHECKING
2820 /* Check all memory contexts that weren't freed during commit */
2821 /* (those that were, were checked before being deleted) */
2823#endif
2824
2825#ifdef SHOW_MEMORY_STATS
2826 /* Print mem stats after each commit for leak tracking */
2828#endif
2829
2830 xact_started = false;
2831 }
2832}
2833
2834
2835/*
2836 * Convenience routines for checking whether a statement is one of the
2837 * ones that we allow in transaction-aborted state.
2838 */
2839
2840/* Test a bare parsetree */
2841static bool
2843{
2844 if (parsetree && IsA(parsetree, TransactionStmt))
2845 {
2846 TransactionStmt *stmt = (TransactionStmt *) parsetree;
2847
2848 if (stmt->kind == TRANS_STMT_COMMIT ||
2849 stmt->kind == TRANS_STMT_PREPARE ||
2850 stmt->kind == TRANS_STMT_ROLLBACK ||
2852 return true;
2853 }
2854 return false;
2855}
2856
2857/* Test a list that contains PlannedStmt nodes */
2858static bool
2860{
2861 if (list_length(pstmts) == 1)
2862 {
2864
2865 if (pstmt->commandType == CMD_UTILITY &&
2867 return true;
2868 }
2869 return false;
2870}
2871
2872/* Test a list that contains PlannedStmt nodes */
2873static bool
2875{
2876 if (list_length(pstmts) == 1)
2877 {
2879
2880 if (pstmt->commandType == CMD_UTILITY &&
2882 return true;
2883 }
2884 return false;
2885}
2886
2887/* Release any existing unnamed prepared statement */
2888static void
2890{
2891 /* paranoia to avoid a dangling pointer in case of error */
2893 {
2895
2898 }
2899}
2900
2901
2902/* --------------------------------
2903 * signal handler routines used in PostgresMain()
2904 * --------------------------------
2905 */
2906
2907/*
2908 * quickdie() occurs when signaled SIGQUIT by the postmaster.
2909 *
2910 * Either some backend has bought the farm, or we've been told to shut down
2911 * "immediately"; so we need to stop what we're doing and exit.
2912 */
2913void
2915{
2916 sigaddset(&BlockSig, SIGQUIT); /* prevent nested calls */
2918
2919 /*
2920 * Prevent interrupts while exiting; though we just blocked signals that
2921 * would queue new interrupts, one may have been pending. We don't want a
2922 * quickdie() downgraded to a mere query cancel.
2923 */
2925
2926 /*
2927 * If we're aborting out of client auth, don't risk trying to send
2928 * anything to the client; we will likely violate the protocol, not to
2929 * mention that we may have interrupted the guts of OpenSSL or some
2930 * authentication library.
2931 */
2934
2935 /*
2936 * Notify the client before exiting, to give a clue on what happened.
2937 *
2938 * It's dubious to call ereport() from a signal handler. It is certainly
2939 * not async-signal safe. But it seems better to try, than to disconnect
2940 * abruptly and leave the client wondering what happened. It's remotely
2941 * possible that we crash or hang while trying to send the message, but
2942 * receiving a SIGQUIT is a sign that something has already gone badly
2943 * wrong, so there's not much to lose. Assuming the postmaster is still
2944 * running, it will SIGKILL us soon if we get stuck for some reason.
2945 *
2946 * One thing we can do to make this a tad safer is to clear the error
2947 * context stack, so that context callbacks are not called. That's a lot
2948 * less code that could be reached here, and the context info is unlikely
2949 * to be very relevant to a SIGQUIT report anyway.
2950 */
2952
2953 /*
2954 * When responding to a postmaster-issued signal, we send the message only
2955 * to the client; sending to the server log just creates log spam, plus
2956 * it's more code that we need to hope will work in a signal handler.
2957 *
2958 * Ideally these should be ereport(FATAL), but then we'd not get control
2959 * back to force the correct type of process exit.
2960 */
2961 switch (GetQuitSignalReason())
2962 {
2963 case PMQUIT_NOT_SENT:
2964 /* Hmm, SIGQUIT arrived out of the blue */
2967 errmsg("terminating connection because of unexpected SIGQUIT signal")));
2968 break;
2969 case PMQUIT_FOR_CRASH:
2970 /* A crash-and-restart cycle is in progress */
2973 errmsg("terminating connection because of crash of another server process"),
2974 errdetail("The postmaster has commanded this server process to roll back"
2975 " the current transaction and exit, because another"
2976 " server process exited abnormally and possibly corrupted"
2977 " shared memory."),
2978 errhint("In a moment you should be able to reconnect to the"
2979 " database and repeat your command.")));
2980 break;
2981 case PMQUIT_FOR_STOP:
2982 /* Immediate-mode stop */
2985 errmsg("terminating connection due to immediate shutdown command")));
2986 break;
2987 }
2988
2989 /*
2990 * We DO NOT want to run proc_exit() or atexit() callbacks -- we're here
2991 * because shared memory may be corrupted, so we don't want to try to
2992 * clean up our transaction. Just nail the windows shut and get out of
2993 * town. The callbacks wouldn't be safe to run from a signal handler,
2994 * anyway.
2995 *
2996 * Note we do _exit(2) not _exit(0). This is to force the postmaster into
2997 * a system reset cycle if someone sends a manual SIGQUIT to a random
2998 * backend. This is necessary precisely because we don't clean up our
2999 * shared memory state. (The "dead man switch" mechanism in pmsignal.c
3000 * should ensure the postmaster sees this as a crash, too, but no harm in
3001 * being doubly sure.)
3002 */
3003 _exit(2);
3004}
3005
3006/*
3007 * Shutdown signal from postmaster: abort transaction and exit
3008 * at soonest convenient time
3009 */
3010void
3012{
3013 /* Don't joggle the elbow of proc_exit */
3015 {
3016 InterruptPending = true;
3017 ProcDiePending = true;
3018 }
3019
3020 /* for the cumulative stats system */
3022
3023 /* If we're still here, waken anything waiting on the process latch */
3025
3026 /*
3027 * If we're in single user mode, we want to quit immediately - we can't
3028 * rely on latches as they wouldn't work when stdin/stdout is a file.
3029 * Rather ugly, but it's unlikely to be worthwhile to invest much more
3030 * effort just for the benefit of single user mode.
3031 */
3034}
3035
3036/*
3037 * Query-cancel signal from postmaster: abort current transaction
3038 * at soonest convenient time
3039 */
3040void
3042{
3043 /*
3044 * Don't joggle the elbow of proc_exit
3045 */
3047 {
3048 InterruptPending = true;
3049 QueryCancelPending = true;
3050 }
3051
3052 /* If we're still here, waken anything waiting on the process latch */
3054}
3055
3056/* signal handler for floating point exception */
3057void
3059{
3060 /* We're not returning, so no need to save errno */
3061 ereport(ERROR,
3063 errmsg("floating-point exception"),
3064 errdetail("An invalid floating-point operation was signaled. "
3065 "This probably means an out-of-range result or an "
3066 "invalid operation, such as division by zero.")));
3067}
3068
3069/*
3070 * Tell the next CHECK_FOR_INTERRUPTS() to check for a particular type of
3071 * recovery conflict. Runs in a SIGUSR1 handler.
3072 */
3073void
3075{
3076 RecoveryConflictPendingReasons[reason] = true;
3078 InterruptPending = true;
3079 /* latch will be set by procsignal_sigusr1_handler */
3080}
3081
3082/*
3083 * Check one individual conflict reason.
3084 */
3085static void
3087{
3088 switch (reason)
3089 {
3091
3092 /*
3093 * If we aren't waiting for a lock we can never deadlock.
3094 */
3095 if (GetAwaitedLock() == NULL)
3096 return;
3097
3098 /* Intentional fall through to check wait for pin */
3099 /* FALLTHROUGH */
3100
3102
3103 /*
3104 * If PROCSIG_RECOVERY_CONFLICT_BUFFERPIN is requested but we
3105 * aren't blocking the Startup process there is nothing more to
3106 * do.
3107 *
3108 * When PROCSIG_RECOVERY_CONFLICT_STARTUP_DEADLOCK is requested,
3109 * if we're waiting for locks and the startup process is not
3110 * waiting for buffer pin (i.e., also waiting for locks), we set
3111 * the flag so that ProcSleep() will check for deadlocks.
3112 */
3114 {
3118 return;
3119 }
3120
3121 /* Intentional fall through to error handling */
3122 /* FALLTHROUGH */
3123
3127
3128 /*
3129 * If we aren't in a transaction any longer then ignore.
3130 */
3132 return;
3133
3134 /* FALLTHROUGH */
3135
3137
3138 /*
3139 * If we're not in a subtransaction then we are OK to throw an
3140 * ERROR to resolve the conflict. Otherwise drop through to the
3141 * FATAL case.
3142 *
3143 * PROCSIG_RECOVERY_CONFLICT_LOGICALSLOT is a special case that
3144 * always throws an ERROR (ie never promotes to FATAL), though it
3145 * still has to respect QueryCancelHoldoffCount, so it shares this
3146 * code path. Logical decoding slots are only acquired while
3147 * performing logical decoding. During logical decoding no user
3148 * controlled code is run. During [sub]transaction abort, the
3149 * slot is released. Therefore user controlled code cannot
3150 * intercept an error before the replication slot is released.
3151 *
3152 * XXX other times that we can throw just an ERROR *may* be
3153 * PROCSIG_RECOVERY_CONFLICT_LOCK if no locks are held in parent
3154 * transactions
3155 *
3156 * PROCSIG_RECOVERY_CONFLICT_SNAPSHOT if no snapshots are held by
3157 * parent transactions and the transaction is not
3158 * transaction-snapshot mode
3159 *
3160 * PROCSIG_RECOVERY_CONFLICT_TABLESPACE if no temp files or
3161 * cursors open in parent transactions
3162 */
3165 {
3166 /*
3167 * If we already aborted then we no longer need to cancel. We
3168 * do this here since we do not wish to ignore aborted
3169 * subtransactions, which must cause FATAL, currently.
3170 */
3172 return;
3173
3174 /*
3175 * If a recovery conflict happens while we are waiting for
3176 * input from the client, the client is presumably just
3177 * sitting idle in a transaction, preventing recovery from
3178 * making progress. We'll drop through to the FATAL case
3179 * below to dislodge it, in that case.
3180 */
3181 if (!DoingCommandRead)
3182 {
3183 /* Avoid losing sync in the FE/BE protocol. */
3184 if (QueryCancelHoldoffCount != 0)
3185 {
3186 /*
3187 * Re-arm and defer this interrupt until later. See
3188 * similar code in ProcessInterrupts().
3189 */
3190 RecoveryConflictPendingReasons[reason] = true;
3192 InterruptPending = true;
3193 return;
3194 }
3195
3196 /*
3197 * We are cleared to throw an ERROR. Either it's the
3198 * logical slot case, or we have a top-level transaction
3199 * that we can abort and a conflict that isn't inherently
3200 * non-retryable.
3201 */
3204 ereport(ERROR,
3206 errmsg("canceling statement due to conflict with recovery"),
3208 break;
3209 }
3210 }
3211
3212 /*
3213 * We couldn't resolve the conflict with ERROR, so terminate the
3214 * whole session.
3215 */
3217 ereport(FATAL,
3219 errmsg("terminating connection due to conflict with recovery"),
3221 errhint("In a moment you should be able to reconnect to the"
3222 " database and repeat your command.")));
3223 break;
3224
3226
3227 /* The database is being dropped; terminate the session */
3229 ereport(FATAL,
3231 errmsg("terminating connection due to conflict with recovery"),
3233 break;
3234
3235 default:
3236 elog(FATAL, "unrecognized conflict mode: %d", (int) reason);
3237 }
3238}
3239
3240/*
3241 * Check each possible recovery conflict reason.
3242 */
3243static void
3245{
3246 /*
3247 * We don't need to worry about joggling the elbow of proc_exit, because
3248 * proc_exit_prepare() holds interrupts, so ProcessInterrupts() won't call
3249 * us.
3250 */
3254
3256
3259 reason++)
3260 {
3262 {
3263 RecoveryConflictPendingReasons[reason] = false;
3265 }
3266 }
3267}
3268
3269/*
3270 * ProcessInterrupts: out-of-line portion of CHECK_FOR_INTERRUPTS() macro
3271 *
3272 * If an interrupt condition is pending, and it's safe to service it,
3273 * then clear the flag and accept the interrupt. Called only when
3274 * InterruptPending is true.
3275 *
3276 * Note: if INTERRUPTS_CAN_BE_PROCESSED() is true, then ProcessInterrupts
3277 * is guaranteed to clear the InterruptPending flag before returning.
3278 * (This is not the same as guaranteeing that it's still clear when we
3279 * return; another interrupt could have arrived. But we promise that
3280 * any pre-existing one will have been serviced.)
3281 */
3282void
3284{
3285 /* OK to accept any interrupts now? */
3286 if (InterruptHoldoffCount != 0 || CritSectionCount != 0)
3287 return;
3288 InterruptPending = false;
3289
3290 if (ProcDiePending)
3291 {
3292 ProcDiePending = false;
3293 QueryCancelPending = false; /* ProcDie trumps QueryCancel */
3295 /* As in quickdie, don't risk sending to client during auth */
3299 ereport(FATAL,
3301 errmsg("canceling authentication due to timeout")));
3302 else if (AmAutoVacuumWorkerProcess())
3303 ereport(FATAL,
3305 errmsg("terminating autovacuum process due to administrator command")));
3306 else if (IsLogicalWorker())
3307 ereport(FATAL,
3309 errmsg("terminating logical replication worker due to administrator command")));
3310 else if (IsLogicalLauncher())
3311 {
3313 (errmsg_internal("logical replication launcher shutting down")));
3314
3315 /*
3316 * The logical replication launcher can be stopped at any time.
3317 * Use exit status 1 so the background worker is restarted.
3318 */
3319 proc_exit(1);
3320 }
3321 else if (AmWalReceiverProcess())
3322 ereport(FATAL,
3324 errmsg("terminating walreceiver process due to administrator command")));
3325 else if (AmBackgroundWorkerProcess())
3326 ereport(FATAL,
3328 errmsg("terminating background worker \"%s\" due to administrator command",
3330 else if (AmIoWorkerProcess())
3331 {
3333 (errmsg_internal("io worker shutting down due to administrator command")));
3334
3335 proc_exit(0);
3336 }
3337 else
3338 ereport(FATAL,
3340 errmsg("terminating connection due to administrator command")));
3341 }
3342
3344 {
3346
3347 /*
3348 * Check for lost connection and re-arm, if still configured, but not
3349 * if we've arrived back at DoingCommandRead state. We don't want to
3350 * wake up idle sessions, and they already know how to detect lost
3351 * connections.
3352 */
3354 {
3355 if (!pq_check_connection())
3356 ClientConnectionLost = true;
3357 else
3360 }
3361 }
3362
3364 {
3365 QueryCancelPending = false; /* lost connection trumps QueryCancel */
3367 /* don't send to client, we already know the connection to be dead. */
3369 ereport(FATAL,
3371 errmsg("connection to client lost")));
3372 }
3373
3374 /*
3375 * Don't allow query cancel interrupts while reading input from the
3376 * client, because we might lose sync in the FE/BE protocol. (Die
3377 * interrupts are OK, because we won't read any further messages from the
3378 * client in that case.)
3379 *
3380 * See similar logic in ProcessRecoveryConflictInterrupts().
3381 */
3383 {
3384 /*
3385 * Re-arm InterruptPending so that we process the cancel request as
3386 * soon as we're done reading the message. (XXX this is seriously
3387 * ugly: it complicates INTERRUPTS_CAN_BE_PROCESSED(), and it means we
3388 * can't use that macro directly as the initial test in this function,
3389 * meaning that this code also creates opportunities for other bugs to
3390 * appear.)
3391 */
3392 InterruptPending = true;
3393 }
3394 else if (QueryCancelPending)
3395 {
3398
3399 QueryCancelPending = false;
3400
3401 /*
3402 * If LOCK_TIMEOUT and STATEMENT_TIMEOUT indicators are both set, we
3403 * need to clear both, so always fetch both.
3404 */
3407
3408 /*
3409 * If both were set, we want to report whichever timeout completed
3410 * earlier; this ensures consistent behavior if the machine is slow
3411 * enough that the second timeout triggers before we get here. A tie
3412 * is arbitrarily broken in favor of reporting a lock timeout.
3413 */
3416 lock_timeout_occurred = false; /* report stmt timeout */
3417
3419 {
3421 ereport(ERROR,
3423 errmsg("canceling statement due to lock timeout")));
3424 }
3426 {
3428 ereport(ERROR,
3430 errmsg("canceling statement due to statement timeout")));
3431 }
3433 {
3435 ereport(ERROR,
3437 errmsg("canceling autovacuum task")));
3438 }
3439
3440 /*
3441 * If we are reading a command from the client, just ignore the cancel
3442 * request --- sending an extra error message won't accomplish
3443 * anything. Otherwise, go ahead and throw the error.
3444 */
3445 if (!DoingCommandRead)
3446 {
3448 ereport(ERROR,
3450 errmsg("canceling statement due to user request")));
3451 }
3452 }
3453
3456
3458 {
3459 /*
3460 * If the GUC has been reset to zero, ignore the signal. This is
3461 * important because the GUC update itself won't disable any pending
3462 * interrupt. We need to unset the flag before the injection point,
3463 * otherwise we could loop in interrupts checking.
3464 */
3467 {
3468 INJECTION_POINT("idle-in-transaction-session-timeout", NULL);
3469 ereport(FATAL,
3471 errmsg("terminating connection due to idle-in-transaction timeout")));
3472 }
3473 }
3474
3476 {
3477 /* As above, ignore the signal if the GUC has been reset to zero. */
3479 if (TransactionTimeout > 0)
3480 {
3481 INJECTION_POINT("transaction-timeout", NULL);
3482 ereport(FATAL,
3484 errmsg("terminating connection due to transaction timeout")));
3485 }
3486 }
3487
3489 {
3490 /* As above, ignore the signal if the GUC has been reset to zero. */
3492 if (IdleSessionTimeout > 0)
3493 {
3494 INJECTION_POINT("idle-session-timeout", NULL);
3495 ereport(FATAL,
3497 errmsg("terminating connection due to idle-session timeout")));
3498 }
3499 }
3500
3501 /*
3502 * If there are pending stats updates and we currently are truly idle
3503 * (matching the conditions in PostgresMain(), report stats now.
3504 */
3507 {
3509 pgstat_report_stat(true);
3510 }
3511
3514
3517
3520
3523}
3524
3525/*
3526 * GUC check_hook for client_connection_check_interval
3527 */
3528bool
3530{
3531 if (!WaitEventSetCanReportClosed() && *newval != 0)
3532 {
3533 GUC_check_errdetail("\"client_connection_check_interval\" must be set to 0 on this platform.");
3534 return false;
3535 }
3536 return true;
3537}
3538
3539/*
3540 * GUC check_hook for log_parser_stats, log_planner_stats, log_executor_stats
3541 *
3542 * This function and check_log_stats interact to prevent their variables from
3543 * being set in a disallowed combination. This is a hack that doesn't really
3544 * work right; for example it might fail while applying pg_db_role_setting
3545 * values even though the final state would have been acceptable. However,
3546 * since these variables are legacy settings with little production usage,
3547 * we tolerate that.
3548 */
3549bool
3551{
3553 {
3554 GUC_check_errdetail("Cannot enable parameter when \"log_statement_stats\" is true.");
3555 return false;
3556 }
3557 return true;
3558}
3559
3560/*
3561 * GUC check_hook for log_statement_stats
3562 */
3563bool
3565{
3566 if (*newval &&
3568 {
3569 GUC_check_errdetail("Cannot enable \"log_statement_stats\" when "
3570 "\"log_parser_stats\", \"log_planner_stats\", "
3571 "or \"log_executor_stats\" is true.");
3572 return false;
3573 }
3574 return true;
3575}
3576
3577/* GUC assign hook for transaction_timeout */
3578void
3580{
3581 if (IsTransactionState())
3582 {
3583 /*
3584 * If transaction_timeout GUC has changed within the transaction block
3585 * enable or disable the timer correspondingly.
3586 */
3591 }
3592}
3593
3594/*
3595 * GUC check_hook for restrict_nonsystem_relation_kind
3596 */
3597bool
3599{
3600 char *rawstring;
3601 List *elemlist;
3602 ListCell *l;
3603 int flags = 0;
3604
3605 /* Need a modifiable copy of string */
3607
3609 {
3610 /* syntax error in list */
3611 GUC_check_errdetail("List syntax is invalid.");
3614 return false;
3615 }
3616
3617 foreach(l, elemlist)
3618 {
3619 char *tok = (char *) lfirst(l);
3620
3621 if (pg_strcasecmp(tok, "view") == 0)
3622 flags |= RESTRICT_RELKIND_VIEW;
3623 else if (pg_strcasecmp(tok, "foreign-table") == 0)
3625 else
3626 {
3627 GUC_check_errdetail("Unrecognized key word: \"%s\".", tok);
3630 return false;
3631 }
3632 }
3633
3636
3637 /* Save the flags in *extra, for use by the assign function */
3638 *extra = guc_malloc(LOG, sizeof(int));
3639 if (!*extra)
3640 return false;
3641 *((int *) *extra) = flags;
3642
3643 return true;
3644}
3645
3646/*
3647 * GUC assign_hook for restrict_nonsystem_relation_kind
3648 */
3649void
3651{
3652 int *flags = (int *) extra;
3653
3655}
3656
3657/*
3658 * set_debug_options --- apply "-d N" command line option
3659 *
3660 * -d is not quite the same as setting log_min_messages because it enables
3661 * other output options.
3662 */
3663void
3665{
3666 if (debug_flag > 0)
3667 {
3668 char debugstr[64];
3669
3670 sprintf(debugstr, "debug%d", debug_flag);
3671 SetConfigOption("log_min_messages", debugstr, context, source);
3672 }
3673 else
3674 SetConfigOption("log_min_messages", "notice", context, source);
3675
3676 if (debug_flag >= 1 && context == PGC_POSTMASTER)
3677 {
3678 SetConfigOption("log_connections", "all", context, source);
3679 SetConfigOption("log_disconnections", "true", context, source);
3680 }
3681 if (debug_flag >= 2)
3682 SetConfigOption("log_statement", "all", context, source);
3683 if (debug_flag >= 3)
3684 {
3685 SetConfigOption("debug_print_raw_parse", "true", context, source);
3686 SetConfigOption("debug_print_parse", "true", context, source);
3687 }
3688 if (debug_flag >= 4)
3689 SetConfigOption("debug_print_plan", "true", context, source);
3690 if (debug_flag >= 5)
3691 SetConfigOption("debug_print_rewritten", "true", context, source);
3692}
3693
3694
3695bool
3697{
3698 const char *tmp = NULL;
3699
3700 switch (arg[0])
3701 {
3702 case 's': /* seqscan */
3703 tmp = "enable_seqscan";
3704 break;
3705 case 'i': /* indexscan */
3706 tmp = "enable_indexscan";
3707 break;
3708 case 'o': /* indexonlyscan */
3709 tmp = "enable_indexonlyscan";
3710 break;
3711 case 'b': /* bitmapscan */
3712 tmp = "enable_bitmapscan";
3713 break;
3714 case 't': /* tidscan */
3715 tmp = "enable_tidscan";
3716 break;
3717 case 'n': /* nestloop */
3718 tmp = "enable_nestloop";
3719 break;
3720 case 'm': /* mergejoin */
3721 tmp = "enable_mergejoin";
3722 break;
3723 case 'h': /* hashjoin */
3724 tmp = "enable_hashjoin";
3725 break;
3726 }
3727 if (tmp)
3728 {
3729 SetConfigOption(tmp, "false", context, source);
3730 return true;
3731 }
3732 else
3733 return false;
3734}
3735
3736
3737const char *
3739{
3740 switch (arg[0])
3741 {
3742 case 'p':
3743 if (optarg[1] == 'a') /* "parser" */
3744 return "log_parser_stats";
3745 else if (optarg[1] == 'l') /* "planner" */
3746 return "log_planner_stats";
3747 break;
3748
3749 case 'e': /* "executor" */
3750 return "log_executor_stats";
3751 break;
3752 }
3753
3754 return NULL;
3755}
3756
3757
3758/* ----------------------------------------------------------------
3759 * process_postgres_switches
3760 * Parse command line arguments for backends
3761 *
3762 * This is called twice, once for the "secure" options coming from the
3763 * postmaster or command line, and once for the "insecure" options coming
3764 * from the client's startup packet. The latter have the same syntax but
3765 * may be restricted in what they can do.
3766 *
3767 * argv[0] is ignored in either case (it's assumed to be the program name).
3768 *
3769 * ctx is PGC_POSTMASTER for secure options, PGC_BACKEND for insecure options
3770 * coming from the client, or PGC_SU_BACKEND for insecure options coming from
3771 * a superuser client.
3772 *
3773 * If a database name is present in the command line arguments, it's
3774 * returned into *dbname (this is allowed only if *dbname is initially NULL).
3775 * ----------------------------------------------------------------
3776 */
3777void
3778process_postgres_switches(int argc, char *argv[], GucContext ctx,
3779 const char **dbname)
3780{
3781 bool secure = (ctx == PGC_POSTMASTER);
3782 int errs = 0;
3784 int flag;
3785
3786 if (secure)
3787 {
3788 gucsource = PGC_S_ARGV; /* switches came from command line */
3789
3790 /* Ignore the initial --single argument, if present */
3791 if (argc > 1 && strcmp(argv[1], "--single") == 0)
3792 {
3793 argv++;
3794 argc--;
3795 }
3796 }
3797 else
3798 {
3799 gucsource = PGC_S_CLIENT; /* switches came from client */
3800 }
3801
3802#ifdef HAVE_INT_OPTERR
3803
3804 /*
3805 * Turn this off because it's either printed to stderr and not the log
3806 * where we'd want it, or argv[0] is now "--single", which would make for
3807 * a weird error message. We print our own error message below.
3808 */
3809 opterr = 0;
3810#endif
3811
3812 /*
3813 * Parse command-line options. CAUTION: keep this in sync with
3814 * postmaster/postmaster.c (the option sets should not conflict) and with
3815 * the common help() function in main/main.c.
3816 */
3817 while ((flag = getopt(argc, argv, "B:bC:c:D:d:EeFf:h:ijk:lN:nOPp:r:S:sTt:v:W:-:")) != -1)
3818 {
3819 switch (flag)
3820 {
3821 case 'B':
3822 SetConfigOption("shared_buffers", optarg, ctx, gucsource);
3823 break;
3824
3825 case 'b':
3826 /* Undocumented flag used for binary upgrades */
3827 if (secure)
3828 IsBinaryUpgrade = true;
3829 break;
3830
3831 case 'C':
3832 /* ignored for consistency with the postmaster */
3833 break;
3834
3835 case '-':
3836
3837 /*
3838 * Error if the user misplaced a special must-be-first option
3839 * for dispatching to a subprogram. parse_dispatch_option()
3840 * returns DISPATCH_POSTMASTER if it doesn't find a match, so
3841 * error for anything else.
3842 */
3844 ereport(ERROR,
3846 errmsg("--%s must be first argument", optarg)));
3847
3848 /* FALLTHROUGH */
3849 case 'c':
3850 {
3851 char *name,
3852 *value;
3853
3855 if (!value)
3856 {
3857 if (flag == '-')
3858 ereport(ERROR,
3860 errmsg("--%s requires a value",
3861 optarg)));
3862 else
3863 ereport(ERROR,
3865 errmsg("-c %s requires a value",
3866 optarg)));
3867 }
3869 pfree(name);
3870 pfree(value);
3871 break;
3872 }
3873
3874 case 'D':
3875 if (secure)
3877 break;
3878
3879 case 'd':
3881 break;
3882
3883 case 'E':
3884 if (secure)
3885 EchoQuery = true;
3886 break;
3887
3888 case 'e':
3889 SetConfigOption("datestyle", "euro", ctx, gucsource);
3890 break;
3891
3892 case 'F':
3893 SetConfigOption("fsync", "false", ctx, gucsource);
3894 break;
3895
3896 case 'f':
3898 errs++;
3899 break;
3900
3901 case 'h':
3902 SetConfigOption("listen_addresses", optarg, ctx, gucsource);
3903 break;
3904
3905 case 'i':
3906 SetConfigOption("listen_addresses", "*", ctx, gucsource);
3907 break;
3908
3909 case 'j':
3910 if (secure)
3911 UseSemiNewlineNewline = true;
3912 break;
3913
3914 case 'k':
3915 SetConfigOption("unix_socket_directories", optarg, ctx, gucsource);
3916 break;
3917
3918 case 'l':
3919 SetConfigOption("ssl", "true", ctx, gucsource);
3920 break;
3921
3922 case 'N':
3923 SetConfigOption("max_connections", optarg, ctx, gucsource);
3924 break;
3925
3926 case 'n':
3927 /* ignored for consistency with postmaster */
3928 break;
3929
3930 case 'O':
3931 SetConfigOption("allow_system_table_mods", "true", ctx, gucsource);
3932 break;
3933
3934 case 'P':
3935 SetConfigOption("ignore_system_indexes", "true", ctx, gucsource);
3936 break;
3937
3938 case 'p':
3939 SetConfigOption("port", optarg, ctx, gucsource);
3940 break;
3941
3942 case 'r':
3943 /* send output (stdout and stderr) to the given file */
3944 if (secure)
3946 break;
3947
3948 case 'S':
3949 SetConfigOption("work_mem", optarg, ctx, gucsource);
3950 break;
3951
3952 case 's':
3953 SetConfigOption("log_statement_stats", "true", ctx, gucsource);
3954 break;
3955
3956 case 'T':
3957 /* ignored for consistency with the postmaster */
3958 break;
3959
3960 case 't':
3961 {
3962 const char *tmp = get_stats_option_name(optarg);
3963
3964 if (tmp)
3965 SetConfigOption(tmp, "true", ctx, gucsource);
3966 else
3967 errs++;
3968 break;
3969 }
3970
3971 case 'v':
3972
3973 /*
3974 * -v is no longer used in normal operation, since
3975 * FrontendProtocol is already set before we get here. We keep
3976 * the switch only for possible use in standalone operation,
3977 * in case we ever support using normal FE/BE protocol with a
3978 * standalone backend.
3979 */
3980 if (secure)
3982 break;
3983
3984 case 'W':
3985 SetConfigOption("post_auth_delay", optarg, ctx, gucsource);
3986 break;
3987
3988 default:
3989 errs++;
3990 break;
3991 }
3992
3993 if (errs)
3994 break;
3995 }
3996
3997 /*
3998 * Optional database name should be there only if *dbname is NULL.
3999 */
4000 if (!errs && dbname && *dbname == NULL && argc - optind >= 1)
4001 *dbname = strdup(argv[optind++]);
4002
4003 if (errs || argc != optind)
4004 {
4005 if (errs)
4006 optind--; /* complain about the previous argument */
4007
4008 /* spell the error message a bit differently depending on context */
4010 ereport(FATAL,
4012 errmsg("invalid command-line argument for server process: %s", argv[optind]),
4013 errhint("Try \"%s --help\" for more information.", progname));
4014 else
4015 ereport(FATAL,
4017 errmsg("%s: invalid command-line argument: %s",
4018 progname, argv[optind]),
4019 errhint("Try \"%s --help\" for more information.", progname));
4020 }
4021
4022 /*
4023 * Reset getopt(3) library so that it will work correctly in subprocesses
4024 * or when this function is called a second time with another array.
4025 */
4026 optind = 1;
4027#ifdef HAVE_INT_OPTRESET
4028 optreset = 1; /* some systems need this too */
4029#endif
4030}
4031
4032
4033/*
4034 * PostgresSingleUserMain
4035 * Entry point for single user mode. argc/argv are the command line
4036 * arguments to be used.
4037 *
4038 * Performs single user specific setup then calls PostgresMain() to actually
4039 * process queries. Single user mode specific setup should go here, rather
4040 * than PostgresMain() or InitPostgres() when reasonably possible.
4041 */
4042void
4043PostgresSingleUserMain(int argc, char *argv[],
4044 const char *username)
4045{
4046 const char *dbname = NULL;
4047
4049
4050 /* Initialize startup process environment. */
4051 InitStandaloneProcess(argv[0]);
4052
4053 /*
4054 * Set default values for command-line options.
4055 */
4057
4058 /*
4059 * Parse command-line options.
4060 */
4062
4063 /* Must have gotten a database name, or have a default (the username) */
4064 if (dbname == NULL)
4065 {
4066 dbname = username;
4067 if (dbname == NULL)
4068 ereport(FATAL,
4070 errmsg("%s: no database nor user name specified",
4071 progname)));
4072 }
4073
4074 /* Acquire configuration parameters */
4076 proc_exit(1);
4077
4078 /*
4079 * Validate we have been given a reasonable-looking DataDir and change
4080 * into it.
4081 */
4082 checkDataDir();
4084
4085 /*
4086 * Create lockfile for data directory.
4087 */
4088 CreateDataDirLockFile(false);
4089
4090 /* read control file (error checking and contains config ) */
4092
4093 /*
4094 * process any libraries that should be preloaded at postmaster start
4095 */
4097
4098 /* Initialize MaxBackends */
4100
4101 /*
4102 * We don't need postmaster child slots in single-user mode, but
4103 * initialize them anyway to avoid having special handling.
4104 */
4106
4107 /* Initialize size of fast-path lock cache. */
4109
4110 /*
4111 * Give preloaded libraries a chance to request additional shared memory.
4112 */
4114
4115 /*
4116 * Now that loadable modules have had their chance to request additional
4117 * shared memory, determine the value of any runtime-computed GUCs that
4118 * depend on the amount of shared memory required.
4119 */
4121
4122 /*
4123 * Now that modules have been loaded, we can process any custom resource
4124 * managers specified in the wal_consistency_checking GUC.
4125 */
4127
4128 /*
4129 * Create shared memory etc. (Nothing's really "shared" in single-user
4130 * mode, but we must have these data structures anyway.)
4131 */
4133
4134 /*
4135 * Estimate number of openable files. This must happen after setting up
4136 * semaphores, because on some platforms semaphores count as open files.
4137 */
4139
4140 /*
4141 * Remember stand-alone backend startup time,roughly at the same point
4142 * during startup that postmaster does so.
4143 */
4145
4146 /*
4147 * Create a per-backend PGPROC struct in shared memory. We must do this
4148 * before we can use LWLocks.
4149 */
4150 InitProcess();
4151
4152 /*
4153 * Now that sufficient infrastructure has been initialized, PostgresMain()
4154 * can do the rest.
4155 */
4157}
4158
4159
4160/* ----------------------------------------------------------------
4161 * PostgresMain
4162 * postgres main loop -- all backends, interactive or otherwise loop here
4163 *
4164 * dbname is the name of the database to connect to, username is the
4165 * PostgreSQL user name to be used for the session.
4166 *
4167 * NB: Single user mode specific setup should go to PostgresSingleUserMain()
4168 * if reasonably possible.
4169 * ----------------------------------------------------------------
4170 */
4171void
4172PostgresMain(const char *dbname, const char *username)
4173{
4175
4176 /* these must be volatile to ensure state is preserved across longjmp: */
4177 volatile bool send_ready_for_query = true;
4178 volatile bool idle_in_transaction_timeout_enabled = false;
4179 volatile bool idle_session_timeout_enabled = false;
4180
4181 Assert(dbname != NULL);
4182 Assert(username != NULL);
4183
4185
4186 /*
4187 * Set up signal handlers. (InitPostmasterChild or InitStandaloneProcess
4188 * has already set up BlockSig and made that the active signal mask.)
4189 *
4190 * Note that postmaster blocked all signals before forking child process,
4191 * so there is no race condition whereby we might receive a signal before
4192 * we have set up the handler.
4193 *
4194 * Also note: it's best not to use any signals that are SIG_IGNored in the
4195 * postmaster. If such a signal arrives before we are able to change the
4196 * handler to non-SIG_IGN, it'll get dropped. Instead, make a dummy
4197 * handler in the postmaster to reserve the signal. (Of course, this isn't
4198 * an issue for signals that are locally generated, such as SIGALRM and
4199 * SIGPIPE.)
4200 */
4201 if (am_walsender)
4202 WalSndSignals();
4203 else
4204 {
4206 pqsignal(SIGINT, StatementCancelHandler); /* cancel current query */
4207 pqsignal(SIGTERM, die); /* cancel current query and exit */
4208
4209 /*
4210 * In a postmaster child backend, replace SignalHandlerForCrashExit
4211 * with quickdie, so we can tell the client we're dying.
4212 *
4213 * In a standalone backend, SIGQUIT can be generated from the keyboard
4214 * easily, while SIGTERM cannot, so we make both signals do die()
4215 * rather than quickdie().
4216 */
4218 pqsignal(SIGQUIT, quickdie); /* hard crash time */
4219 else
4220 pqsignal(SIGQUIT, die); /* cancel current query and exit */
4221 InitializeTimeouts(); /* establishes SIGALRM handler */
4222
4223 /*
4224 * Ignore failure to write to frontend. Note: if frontend closes
4225 * connection, we will notice it and exit cleanly when control next
4226 * returns to outer loop. This seems safer than forcing exit in the
4227 * midst of output during who-knows-what operation...
4228 */
4233
4234 /*
4235 * Reset some signals that are accepted by postmaster but not by
4236 * backend
4237 */
4238 pqsignal(SIGCHLD, SIG_DFL); /* system() requires this on some
4239 * platforms */
4240 }
4241
4242 /* Early initialization */
4243 BaseInit();
4244
4245 /* We need to allow SIGINT, etc during the initial transaction */
4247
4248 /*
4249 * Generate a random cancel key, if this is a backend serving a
4250 * connection. InitPostgres() will advertise it in shared memory.
4251 */
4254 {
4255 int len;
4256
4257 len = (MyProcPort == NULL || MyProcPort->proto >= PG_PROTOCOL(3, 2))
4260 {
4261 ereport(ERROR,
4263 errmsg("could not generate random cancel key")));
4264 }
4266 }
4267
4268 /*
4269 * General initialization.
4270 *
4271 * NOTE: if you are tempted to add code in this vicinity, consider putting
4272 * it inside InitPostgres() instead. In particular, anything that
4273 * involves database access should be there, not here.
4274 *
4275 * Honor session_preload_libraries if not dealing with a WAL sender.
4276 */
4277 InitPostgres(dbname, InvalidOid, /* database to connect to */
4278 username, InvalidOid, /* role to connect as */
4280 NULL); /* no out_dbname */
4281
4282 /*
4283 * If the PostmasterContext is still around, recycle the space; we don't
4284 * need it anymore after InitPostgres completes.
4285 */
4287 {
4290 }
4291
4293
4294 /*
4295 * Now all GUC states are fully set up. Report them to client if
4296 * appropriate.
4297 */
4299
4300 /*
4301 * Also set up handler to log session end; we have to wait till now to be
4302 * sure Log_disconnections has its final value.
4303 */
4306
4308
4309 /* Perform initialization specific to a WAL sender process. */
4310 if (am_walsender)
4311 InitWalSender();
4312
4313 /*
4314 * Send this backend's cancellation info to the frontend.
4315 */
4317 {
4319
4323
4326 /* Need not flush since ReadyForQuery will do it. */
4327 }
4328
4329 /* Welcome banner for standalone case */
4331 printf("\nPostgreSQL stand-alone backend %s\n", PG_VERSION);
4332
4333 /*
4334 * Create the memory context we will use in the main loop.
4335 *
4336 * MessageContext is reset once per iteration of the main loop, ie, upon
4337 * completion of processing of each command message from the client.
4338 */
4340 "MessageContext",
4342
4343 /*
4344 * Create memory context and buffer used for RowDescription messages. As
4345 * SendRowDescriptionMessage(), via exec_describe_statement_message(), is
4346 * frequently executed for every single statement, we don't want to
4347 * allocate a separate buffer every time.
4348 */
4350 "RowDescriptionContext",
4355
4356 /* Fire any defined login event triggers, if appropriate */
4358
4359 /*
4360 * POSTGRES main processing loop begins here
4361 *
4362 * If an exception is encountered, processing resumes here so we abort the
4363 * current transaction and start a new one.
4364 *
4365 * You might wonder why this isn't coded as an infinite loop around a
4366 * PG_TRY construct. The reason is that this is the bottom of the
4367 * exception stack, and so with PG_TRY there would be no exception handler
4368 * in force at all during the CATCH part. By leaving the outermost setjmp
4369 * always active, we have at least some chance of recovering from an error
4370 * during error recovery. (If we get into an infinite loop thereby, it
4371 * will soon be stopped by overflow of elog.c's internal state stack.)
4372 *
4373 * Note that we use sigsetjmp(..., 1), so that this function's signal mask
4374 * (to wit, UnBlockSig) will be restored when longjmp'ing to here. This
4375 * is essential in case we longjmp'd out of a signal handler on a platform
4376 * where that leaves the signal blocked. It's not redundant with the
4377 * unblock in AbortTransaction() because the latter is only called if we
4378 * were inside a transaction.
4379 */
4380
4381 if (sigsetjmp(local_sigjmp_buf, 1) != 0)
4382 {
4383 /*
4384 * NOTE: if you are tempted to add more code in this if-block,
4385 * consider the high probability that it should be in
4386 * AbortTransaction() instead. The only stuff done directly here
4387 * should be stuff that is guaranteed to apply *only* for outer-level
4388 * error recovery, such as adjusting the FE/BE protocol status.
4389 */
4390
4391 /* Since not using PG_TRY, must reset error stack by hand */
4393
4394 /* Prevent interrupts while cleaning up */
4396
4397 /*
4398 * Forget any pending QueryCancel request, since we're returning to
4399 * the idle loop anyway, and cancel any active timeout requests. (In
4400 * future we might want to allow some timeout requests to survive, but
4401 * at minimum it'd be necessary to do reschedule_timeouts(), in case
4402 * we got here because of a query cancel interrupting the SIGALRM
4403 * interrupt handler.) Note in particular that we must clear the
4404 * statement and lock timeout indicators, to prevent any future plain
4405 * query cancels from being misreported as timeouts in case we're
4406 * forgetting a timeout cancel.
4407 */
4408 disable_all_timeouts(false); /* do first to avoid race condition */
4409 QueryCancelPending = false;
4412
4413 /* Not reading from the client anymore. */
4414 DoingCommandRead = false;
4415
4416 /* Make sure libpq is in a good state */
4417 pq_comm_reset();
4418
4419 /* Report the error to the client and/or server log */
4421
4422 /*
4423 * If Valgrind noticed something during the erroneous query, print the
4424 * query string, assuming we have one.
4425 */
4427
4428 /*
4429 * Make sure debug_query_string gets reset before we possibly clobber
4430 * the storage it points at.
4431 */
4433
4434 /*
4435 * Abort the current transaction in order to recover.
4436 */
4438
4439 if (am_walsender)
4441
4443
4444 /*
4445 * We can't release replication slots inside AbortTransaction() as we
4446 * need to be able to start and abort transactions while having a slot
4447 * acquired. But we never need to hold them across top level errors,
4448 * so releasing here is fine. There also is a before_shmem_exit()
4449 * callback ensuring correct cleanup on FATAL errors.
4450 */
4451 if (MyReplicationSlot != NULL)
4453
4454 /* We also want to cleanup temporary slots on error. */
4456
4458
4459 /*
4460 * Now return to normal top-level context and clear ErrorContext for
4461 * next time.
4462 */
4465
4466 /*
4467 * If we were handling an extended-query-protocol message, initiate
4468 * skip till next Sync. This also causes us not to issue
4469 * ReadyForQuery (until we get Sync).
4470 */
4472 ignore_till_sync = true;
4473
4474 /* We don't have a transaction command open anymore */
4475 xact_started = false;
4476
4477 /*
4478 * If an error occurred while we were reading a message from the
4479 * client, we have potentially lost track of where the previous
4480 * message ends and the next one begins. Even though we have
4481 * otherwise recovered from the error, we cannot safely read any more
4482 * messages from the client, so there isn't much we can do with the
4483 * connection anymore.
4484 */
4485 if (pq_is_reading_msg())
4486 ereport(FATAL,
4488 errmsg("terminating connection because protocol synchronization was lost")));
4489
4490 /* Now we can allow interrupts again */
4492 }
4493
4494 /* We can now handle ereport(ERROR) */
4496
4497 if (!ignore_till_sync)
4498 send_ready_for_query = true; /* initially, or after error */
4499
4500 /*
4501 * Non-error queries loop here.
4502 */
4503
4504 for (;;)
4505 {
4506 int firstchar;
4508
4509 /*
4510 * At top of loop, reset extended-query-message flag, so that any
4511 * errors encountered in "idle" state don't provoke skip.
4512 */
4514
4515 /*
4516 * For valgrind reporting purposes, the "current query" begins here.
4517 */
4518#ifdef USE_VALGRIND
4520#endif
4521
4522 /*
4523 * Release storage left over from prior query cycle, and create a new
4524 * query input buffer in the cleared MessageContext.
4525 */
4528
4530
4531 /*
4532 * Also consider releasing our catalog snapshot if any, so that it's
4533 * not preventing advance of global xmin while we wait for the client.
4534 */
4536
4537 /*
4538 * (1) If we've reached idle state, tell the frontend we're ready for
4539 * a new query.
4540 *
4541 * Note: this includes fflush()'ing the last of the prior output.
4542 *
4543 * This is also a good time to flush out collected statistics to the
4544 * cumulative stats system, and to update the PS stats display. We
4545 * avoid doing those every time through the message loop because it'd
4546 * slow down processing of batched messages, and because we don't want
4547 * to report uncommitted updates (that confuses autovacuum). The
4548 * notification processor wants a call too, if we are not in a
4549 * transaction block.
4550 *
4551 * Also, if an idle timeout is enabled, start the timer for that.
4552 */
4554 {
4556 {
4557 set_ps_display("idle in transaction (aborted)");
4559
4560 /* Start the idle-in-transaction timer */
4563 {
4567 }
4568 }
4570 {
4571 set_ps_display("idle in transaction");
4573
4574 /* Start the idle-in-transaction timer */
4577 {
4581 }
4582 }
4583 else
4584 {
4585 long stats_timeout;
4586
4587 /*
4588 * Process incoming notifies (including self-notifies), if
4589 * any, and send relevant messages to the client. Doing it
4590 * here helps ensure stable behavior in tests: if any notifies
4591 * were received during the just-finished transaction, they'll
4592 * be seen by the client before ReadyForQuery is.
4593 */
4596
4597 /*
4598 * Check if we need to report stats. If pgstat_report_stat()
4599 * decides it's too soon to flush out pending stats / lock
4600 * contention prevented reporting, it'll tell us when we
4601 * should try to report stats again (so that stats updates
4602 * aren't unduly delayed if the connection goes idle for a
4603 * long time). We only enable the timeout if we don't already
4604 * have a timeout in progress, because we don't disable the
4605 * timeout below. enable_timeout_after() needs to determine
4606 * the current timestamp, which can have a negative
4607 * performance impact. That's OK because pgstat_report_stat()
4608 * won't have us wake up sooner than a prior call.
4609 */
4611 if (stats_timeout > 0)
4612 {
4616 }
4617 else
4618 {
4619 /* all stats flushed, no need for the timeout */
4622 }
4623
4624 set_ps_display("idle");
4626
4627 /* Start the idle-session timer */
4628 if (IdleSessionTimeout > 0)
4629 {
4633 }
4634 }
4635
4636 /* Report any recently-changed GUC options */
4638
4639 /*
4640 * The first time this backend is ready for query, log the
4641 * durations of the different components of connection
4642 * establishment and setup.
4643 */
4647 {
4651
4653
4663
4664 ereport(LOG,
4665 errmsg("connection ready: setup total=%.3f ms, fork=%.3f ms, authentication=%.3f ms",
4666 (double) total_duration / NS_PER_US,
4667 (double) fork_duration / NS_PER_US,
4668 (double) auth_duration / NS_PER_US));
4669 }
4670
4672 send_ready_for_query = false;
4673 }
4674
4675 /*
4676 * (2) Allow asynchronous signals to be executed immediately if they
4677 * come in while we are waiting for client input. (This must be
4678 * conditional since we don't want, say, reads on behalf of COPY FROM
4679 * STDIN doing the same thing.)
4680 */
4681 DoingCommandRead = true;
4682
4683 /*
4684 * (3) read a command (loop blocks here)
4685 */
4687
4688 /*
4689 * (4) turn off the idle-in-transaction and idle-session timeouts if
4690 * active. We do this before step (5) so that any last-moment timeout
4691 * is certain to be detected in step (5).
4692 *
4693 * At most one of these timeouts will be active, so there's no need to
4694 * worry about combining the timeout.c calls into one.
4695 */
4697 {
4700 }
4702 {
4705 }
4706
4707 /*
4708 * (5) disable async signal conditions again.
4709 *
4710 * Query cancel is supposed to be a no-op when there is no query in
4711 * progress, so if a query cancel arrived while we were idle, just
4712 * reset QueryCancelPending. ProcessInterrupts() has that effect when
4713 * it's called when DoingCommandRead is set, so check for interrupts
4714 * before resetting DoingCommandRead.
4715 */
4717 DoingCommandRead = false;
4718
4719 /*
4720 * (6) check for any other interesting events that happened while we
4721 * slept.
4722 */
4724 {
4725 ConfigReloadPending = false;
4727 }
4728
4729 /*
4730 * (7) process the command. But ignore it if we're skipping till
4731 * Sync.
4732 */
4733 if (ignore_till_sync && firstchar != EOF)
4734 continue;
4735
4736 switch (firstchar)
4737 {
4738 case PqMsg_Query:
4739 {
4740 const char *query_string;
4741
4742 /* Set statement_timestamp() */
4744
4745 query_string = pq_getmsgstring(&input_message);
4747
4748 if (am_walsender)
4749 {
4750 if (!exec_replication_command(query_string))
4751 exec_simple_query(query_string);
4752 }
4753 else
4754 exec_simple_query(query_string);
4755
4756 valgrind_report_error_query(query_string);
4757
4758 send_ready_for_query = true;
4759 }
4760 break;
4761
4762 case PqMsg_Parse:
4763 {
4764 const char *stmt_name;
4765 const char *query_string;
4766 int numParams;
4767 Oid *paramTypes = NULL;
4768
4770
4771 /* Set statement_timestamp() */
4773
4774 stmt_name = pq_getmsgstring(&input_message);
4775 query_string = pq_getmsgstring(&input_message);
4776 numParams = pq_getmsgint(&input_message, 2);
4777 if (numParams > 0)
4778 {
4779 paramTypes = palloc_array(Oid, numParams);
4780 for (int i = 0; i < numParams; i++)
4781 paramTypes[i] = pq_getmsgint(&input_message, 4);
4782 }
4784
4785 exec_parse_message(query_string, stmt_name,
4786 paramTypes, numParams);
4787
4788 valgrind_report_error_query(query_string);
4789 }
4790 break;
4791
4792 case PqMsg_Bind:
4794
4795 /* Set statement_timestamp() */
4797
4798 /*
4799 * this message is complex enough that it seems best to put
4800 * the field extraction out-of-line
4801 */
4803
4804 /* exec_bind_message does valgrind_report_error_query */
4805 break;
4806
4807 case PqMsg_Execute:
4808 {
4809 const char *portal_name;
4810 int max_rows;
4811
4813
4814 /* Set statement_timestamp() */
4816
4820
4822
4823 /* exec_execute_message does valgrind_report_error_query */
4824 }
4825 break;
4826
4827 case PqMsg_FunctionCall:
4829
4830 /* Set statement_timestamp() */
4832
4833 /* Report query to various monitoring facilities. */
4835 set_ps_display("<FASTPATH>");
4836
4837 /* start an xact for this function invocation */
4839
4840 /*
4841 * Note: we may at this point be inside an aborted
4842 * transaction. We can't throw error for that until we've
4843 * finished reading the function-call message, so
4844 * HandleFunctionRequest() must check for it after doing so.
4845 * Be careful not to do anything that assumes we're inside a
4846 * valid transaction here.
4847 */
4848
4849 /* switch back to message context */
4851
4853
4854 /* commit the function-invocation transaction */
4856
4857 valgrind_report_error_query("fastpath function call");
4858
4859 send_ready_for_query = true;
4860 break;
4861
4862 case PqMsg_Close:
4863 {
4864 int close_type;
4865 const char *close_target;
4866
4868
4872
4873 switch (close_type)
4874 {
4875 case 'S':
4876 if (close_target[0] != '\0')
4878 else
4879 {
4880 /* special-case the unnamed statement */
4882 }
4883 break;
4884 case 'P':
4885 {
4886 Portal portal;
4887
4888 portal = GetPortalByName(close_target);
4889 if (PortalIsValid(portal))
4890 PortalDrop(portal, false);
4891 }
4892 break;
4893 default:
4894 ereport(ERROR,
4896 errmsg("invalid CLOSE message subtype %d",
4897 close_type)));
4898 break;
4899 }
4900
4903
4904 valgrind_report_error_query("CLOSE message");
4905 }
4906 break;
4907
4908 case PqMsg_Describe:
4909 {
4910 int describe_type;
4911 const char *describe_target;
4912
4914
4915 /* Set statement_timestamp() (needed for xact) */
4917
4921
4922 switch (describe_type)
4923 {
4924 case 'S':
4926 break;
4927 case 'P':
4929 break;
4930 default:
4931 ereport(ERROR,
4933 errmsg("invalid DESCRIBE message subtype %d",
4934 describe_type)));
4935 break;
4936 }
4937
4938 valgrind_report_error_query("DESCRIBE message");
4939 }
4940 break;
4941
4942 case PqMsg_Flush:
4945 pq_flush();
4946 break;
4947
4948 case PqMsg_Sync:
4950
4951 /*
4952 * If pipelining was used, we may be in an implicit
4953 * transaction block. Close it before calling
4954 * finish_xact_command.
4955 */
4958 valgrind_report_error_query("SYNC message");
4959 send_ready_for_query = true;
4960 break;
4961
4962 /*
4963 * PqMsg_Terminate means that the frontend is closing down the
4964 * socket. EOF means unexpected loss of frontend connection.
4965 * Either way, perform normal shutdown.
4966 */
4967 case EOF:
4968
4969 /* for the cumulative statistics system */
4971
4972 /* FALLTHROUGH */
4973
4974 case PqMsg_Terminate:
4975
4976 /*
4977 * Reset whereToSendOutput to prevent ereport from attempting
4978 * to send any more messages to client.
4979 */
4982
4983 /*
4984 * NOTE: if you are tempted to add more code here, DON'T!
4985 * Whatever you had in mind to do should be set up as an
4986 * on_proc_exit or on_shmem_exit callback, instead. Otherwise
4987 * it will fail to be called during other backend-shutdown
4988 * scenarios.
4989 */
4990 proc_exit(0);
4991
4992 case PqMsg_CopyData:
4993 case PqMsg_CopyDone:
4994 case PqMsg_CopyFail:
4995
4996 /*
4997 * Accept but ignore these messages, per protocol spec; we
4998 * probably got here because a COPY failed, and the frontend
4999 * is still sending data.
5000 */
5001 break;
5002
5003 default:
5004 ereport(FATAL,
5006 errmsg("invalid frontend message type %d",
5007 firstchar)));
5008 }
5009 } /* end of input-reading loop */
5010}
5011
5012/*
5013 * Throw an error if we're a WAL sender process.
5014 *
5015 * This is used to forbid anything else than simple query protocol messages
5016 * in a WAL sender process. 'firstchar' specifies what kind of a forbidden
5017 * message was received, and is used to construct the error message.
5018 */
5019static void
5021{
5022 if (am_walsender)
5023 {
5025 ereport(ERROR,
5027 errmsg("fastpath function calls not supported in a replication connection")));
5028 else
5029 ereport(ERROR,
5031 errmsg("extended query protocol not supported in a replication connection")));
5032 }
5033}
5034
5035
5036static struct rusage Save_r;
5037static struct timeval Save_t;
5038
5039void
5041{
5044}
5045
5046void
5047ShowUsage(const char *title)
5048{
5050 struct timeval user,
5051 sys;
5052 struct timeval elapse_t;
5053 struct rusage r;
5054
5057 memcpy(&user, &r.ru_utime, sizeof(user));
5058 memcpy(&sys, &r.ru_stime, sizeof(sys));
5059 if (elapse_t.tv_usec < Save_t.tv_usec)
5060 {
5061 elapse_t.tv_sec--;
5062 elapse_t.tv_usec += 1000000;
5063 }
5064 if (r.ru_utime.tv_usec < Save_r.ru_utime.tv_usec)
5065 {
5066 r.ru_utime.tv_sec--;
5067 r.ru_utime.tv_usec += 1000000;
5068 }
5069 if (r.ru_stime.tv_usec < Save_r.ru_stime.tv_usec)
5070 {
5071 r.ru_stime.tv_sec--;
5072 r.ru_stime.tv_usec += 1000000;
5073 }
5074
5075 /*
5076 * The only stats we don't show here are ixrss, idrss, isrss. It takes
5077 * some work to interpret them, and most platforms don't fill them in.
5078 */
5080
5081 appendStringInfoString(&str, "! system usage stats:\n");
5083 "!\t%ld.%06ld s user, %ld.%06ld s system, %ld.%06ld s elapsed\n",
5084 (long) (r.ru_utime.tv_sec - Save_r.ru_utime.tv_sec),
5085 (long) (r.ru_utime.tv_usec - Save_r.ru_utime.tv_usec),
5086 (long) (r.ru_stime.tv_sec - Save_r.ru_stime.tv_sec),
5087 (long) (r.ru_stime.tv_usec - Save_r.ru_stime.tv_usec),
5088 (long) (elapse_t.tv_sec - Save_t.tv_sec),
5089 (long) (elapse_t.tv_usec - Save_t.tv_usec));
5091 "!\t[%ld.%06ld s user, %ld.%06ld s system total]\n",
5092 (long) user.tv_sec,
5093 (long) user.tv_usec,
5094 (long) sys.tv_sec,
5095 (long) sys.tv_usec);
5096#ifndef WIN32
5097
5098 /*
5099 * The following rusage fields are not defined by POSIX, but they're
5100 * present on all current Unix-like systems so we use them without any
5101 * special checks. Some of these could be provided in our Windows
5102 * emulation in src/port/win32getrusage.c with more work.
5103 */
5105 "!\t%ld kB max resident size\n",
5107 /* in bytes on macOS */
5108 r.ru_maxrss / 1024
5109#else
5110 /* in kilobytes on most other platforms */
5111 r.ru_maxrss
5112#endif
5113 );
5115 "!\t%ld/%ld [%ld/%ld] filesystem blocks in/out\n",
5116 r.ru_inblock - Save_r.ru_inblock,
5117 /* they only drink coffee at dec */
5118 r.ru_oublock - Save_r.ru_oublock,
5119 r.ru_inblock, r.ru_oublock);
5121 "!\t%ld/%ld [%ld/%ld] page faults/reclaims, %ld [%ld] swaps\n",
5122 r.ru_majflt - Save_r.ru_majflt,
5123 r.ru_minflt - Save_r.ru_minflt,
5124 r.ru_majflt, r.ru_minflt,
5125 r.ru_nswap - Save_r.ru_nswap,
5126 r.ru_nswap);
5128 "!\t%ld [%ld] signals rcvd, %ld/%ld [%ld/%ld] messages rcvd/sent\n",
5129 r.ru_nsignals - Save_r.ru_nsignals,
5130 r.ru_nsignals,
5131 r.ru_msgrcv - Save_r.ru_msgrcv,
5132 r.ru_msgsnd - Save_r.ru_msgsnd,
5133 r.ru_msgrcv, r.ru_msgsnd);
5135 "!\t%ld/%ld [%ld/%ld] voluntary/involuntary context switches\n",
5136 r.ru_nvcsw - Save_r.ru_nvcsw,
5137 r.ru_nivcsw - Save_r.ru_nivcsw,
5138 r.ru_nvcsw, r.ru_nivcsw);
5139#endif /* !WIN32 */
5140
5141 /* remove trailing newline */
5142 if (str.data[str.len - 1] == '\n')
5143 str.data[--str.len] = '\0';
5144
5145 ereport(LOG,
5146 (errmsg_internal("%s", title),
5147 errdetail_internal("%s", str.data)));
5148
5149 pfree(str.data);
5150}
5151
5152/*
5153 * on_proc_exit handler to log end of session
5154 */
5155static void
5157{
5158 Port *port = MyProcPort;
5159 long secs;
5160 int usecs;
5161 int msecs;
5162 int hours,
5163 minutes,
5164 seconds;
5165
5168 &secs, &usecs);
5169 msecs = usecs / 1000;
5170
5175
5176 ereport(LOG,
5177 (errmsg("disconnection: session time: %d:%02d:%02d.%03d "
5178 "user=%s database=%s host=%s%s%s",
5180 port->user_name, port->database_name, port->remote_host,
5181 port->remote_port[0] ? " port=" : "", port->remote_port)));
5182}
5183
5184/*
5185 * Start statement timeout timer, if enabled.
5186 *
5187 * If there's already a timeout running, don't restart the timer. That
5188 * enables compromises between accuracy of timeouts and cost of starting a
5189 * timeout.
5190 */
5191static void
5193{
5194 /* must be within an xact */
5196
5197 if (StatementTimeout > 0
5199 {
5202 }
5203 else
5204 {
5207 }
5208}
5209
5210/*
5211 * Disable statement timeout, if active.
5212 */
5213static void
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:2572
volatile sig_atomic_t notifyInterruptPending
Definition async.c:537
void ProcessParallelMessages(void)
Definition parallel.c:1055
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:6004
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:6674
#define INT64CONST(x)
Definition c.h:560
#define unconstify(underlying_type, expr)
Definition c.h:1240
#define SIGNAL_ARGS
Definition c.h:1363
#define Assert(condition)
Definition c.h:873
int16_t int16
Definition c.h:541
int32_t int32
Definition c.h:542
uint64_t uint64
Definition c.h:547
#define unlikely(x)
Definition c.h:412
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:1170
int errhidestmt(bool hide_stmt)
Definition elog.c:1445
void EmitErrorReport(void)
Definition elog.c:1704
int errdetail_internal(const char *fmt,...)
Definition elog.c:1243
int errdetail(const char *fmt,...)
Definition elog.c:1216
ErrorContextCallback * error_context_stack
Definition elog.c:95
void FlushErrorState(void)
Definition elog.c:1884
int errhint(const char *fmt,...)
Definition elog.c:1330
int errcode(int sqlerrcode)
Definition elog.c:863
int errmsg(const char *fmt,...)
Definition elog.c:1080
#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:1044
#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:1772
Datum OidInputFunctionCall(Oid functionId, char *str, Oid typioparam, int32 typmod)
Definition fmgr.c:1754
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:2421
void SetConfigOption(const char *name, const char *value, GucContext context, GucSource source)
Definition guc.c:4196
void * guc_malloc(int elevel, size_t size)
Definition guc.c:636
#define newval
bool SelectConfigFiles(const char *userDoption, const char *progname)
Definition guc.c:1655
void ParseLongOption(const char *string, char **name, char **value)
Definition guc.c:6205
void InitializeGUCOptions(void)
Definition guc.c:1407
void ReportChangedGUCOptions(void)
Definition guc.c:2471
#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:532
bool Debug_print_plan
Definition guc_tables.c:517
bool Debug_print_raw_parse
Definition guc_tables.c:519
bool log_parser_stats
Definition guc_tables.c:529
bool Debug_pretty_print
Definition guc_tables.c:521
int log_parameter_max_length_on_error
Definition guc_tables.c:554
int log_min_duration_statement
Definition guc_tables.c:552
int log_min_duration_sample
Definition guc_tables.c:551
bool log_planner_stats
Definition guc_tables.c:530
bool Debug_print_rewritten
Definition guc_tables.c:520
bool Debug_print_parse
Definition guc_tables.c:518
int log_parameter_max_length
Definition guc_tables.c:553
double log_statement_sample_rate
Definition guc_tables.c:556
bool log_duration
Definition guc_tables.c:516
bool log_executor_stats
Definition guc_tables.c:531
const char * str
#define stmt
static struct @172 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:316
bool proc_exit_inprogress
Definition ipc.c:41
void proc_exit(int code)
Definition ipc.c:105
void InitializeShmemGUCs(void)
Definition ipci.c:340
void CreateSharedMemoryAndSemaphores(void)
Definition ipci.c:191
int i
Definition isn.c:77
void jit_reset_after_error(void)
Definition jit.c:127
void SetLatch(Latch *latch)
Definition latch.c:290
bool IsLogicalLauncher(void)
Definition launcher.c:1587
#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:3024
void getTypeBinaryInputInfo(Oid type, Oid *typReceive, Oid *typIOParam)
Definition lsyscache.c:3090
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:663
MemoryContext MessageContext
Definition mcxt.c:170
void MemoryContextReset(MemoryContext context)
Definition mcxt.c:403
char * pstrdup(const char *in)
Definition mcxt.c:1781
void MemoryContextSetParent(MemoryContext context, MemoryContext new_parent)
Definition mcxt.c:686
void pfree(void *pointer)
Definition mcxt.c:1616
MemoryContext TopMemoryContext
Definition mcxt.c:166
char * pnstrdup(const char *in, Size len)
Definition mcxt.c:1792
void MemoryContextStats(MemoryContext context)
Definition mcxt.c:863
MemoryContext PostmasterContext
Definition mcxt.c:168
void ProcessLogMemoryContextInterrupt(void)
Definition mcxt.c:1340
void MemoryContextDelete(MemoryContext context)
Definition mcxt.c:472
#define AllocSetContextCreate
Definition memutils.h:129
#define ALLOCSET_DEFAULT_SIZES
Definition memutils.h:160
#define RESUME_INTERRUPTS()
Definition miscadmin.h:136
@ NormalProcessing
Definition miscadmin.h:472
@ InitProcessing
Definition miscadmin.h:471
#define IsExternalConnectionBackend(backend_type)
Definition miscadmin.h:405
#define GetProcessingMode()
Definition miscadmin.h:481
#define HOLD_CANCEL_INTERRUPTS()
Definition miscadmin.h:142
#define INIT_PG_LOAD_SESSION_LIBS
Definition miscadmin.h:499
#define AmAutoVacuumWorkerProcess()
Definition miscadmin.h:383
#define RESUME_CANCEL_INTERRUPTS()
Definition miscadmin.h:144
#define AmBackgroundWorkerProcess()
Definition miscadmin.h:384
#define CHECK_FOR_INTERRUPTS()
Definition miscadmin.h:123
#define HOLD_INTERRUPTS()
Definition miscadmin.h:134
#define SetProcessingMode(mode)
Definition miscadmin.h:483
#define AmWalReceiverProcess()
Definition miscadmin.h:391
#define AmIoWorkerProcess()
Definition miscadmin.h:394
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:808
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:333
void ParamsErrorCallback(void *arg)
Definition params.c:405
#define PARAM_FLAG_CONST
Definition params.h:87
void(* ParserSetupHook)(ParseState *pstate, void *arg)
Definition params.h:107
@ TRANS_STMT_ROLLBACK_TO
@ TRANS_STMT_ROLLBACK
@ TRANS_STMT_COMMIT
@ TRANS_STMT_PREPARE
#define FETCH_ALL
#define CURSOR_OPT_PARALLEL_OK
#define CURSOR_OPT_BINARY
Query * parse_analyze_withcb(RawStmt *parseTree, const char *sourceText, ParserSetupHook parserSetup, void *parserSetupArg, QueryEnvironment *queryEnv)
Definition analyze.c:198
bool analyze_requires_snapshot(RawStmt *parseTree)
Definition analyze.c:503
Query * parse_analyze_fixedparams(RawStmt *parseTree, const char *sourceText, const Oid *paramTypes, int numParams, QueryEnvironment *queryEnv)
Definition analyze.c:117
Query * parse_analyze_varparams(RawStmt *parseTree, const char *sourceText, Oid **paramTypes, int *numParams, QueryEnvironment *queryEnv)
Definition analyze.c:157
@ 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[DEFAULT_XLOG_SEG_SIZE]
#define die(msg)
#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:704
@ DISCONNECT_KILLED
Definition pgstat.h:60
@ DISCONNECT_CLIENT_EOF
Definition pgstat.h:58
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:1777
PlannedStmt * planner(Query *parse, const char *query_string, int cursorOptions, ParamListInfo boundParams, ExplainState *es)
Definition planner.c:315
@ 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:547
bool pg_strong_random(void *buf, size_t len)
int pg_strcasecmp(const char *s1, const char *s2)
#define sprintf
Definition port.h:262
#define snprintf
Definition port.h:260
#define printf(...)
Definition port.h:266
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:467
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:2540
static void disable_statement_timeout(void)
Definition postgres.c:5214
int log_statement
Definition postgres.c:97
static bool IsTransactionStmtList(List *pstmts)
Definition postgres.c:2874
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:3579
List * pg_parse_query(const char *query_string)
Definition postgres.c:603
static bool check_log_statement(List *stmt_list)
Definition postgres.c:2385
static void exec_describe_statement_message(const char *stmt_name)
Definition postgres.c:2628
void assign_restrict_nonsystem_relation_kind(const char *newval, void *extra)
Definition postgres.c:3650
void process_postgres_switches(int argc, char *argv[], GucContext ctx, const char **dbname)
Definition postgres.c:3778
int PostAuthDelay
Definition postgres.c:100
PlannedStmt * pg_plan_query(Query *querytree, const char *query_string, int cursorOptions, ParamListInfo boundParams, ExplainState *es)
Definition postgres.c:886
void quickdie(SIGNAL_ARGS)
Definition postgres.c:2914
static bool IsTransactionExitStmtList(List *pstmts)
Definition postgres.c:2859
static void log_disconnections(int code, Datum arg)
Definition postgres.c:5156
static void forbidden_in_wal_sender(char firstchar)
Definition postgres.c:5020
static void exec_execute_message(const char *portal_name, long max_rows)
Definition postgres.c:2109
void PostgresSingleUserMain(int argc, char *argv[], const char *username)
Definition postgres.c:4043
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:3664
static bool UseSemiNewlineNewline
Definition postgres.c:156
static CachedPlanSource * unnamed_stmt_psrc
Definition postgres.c:151
void FloatExceptionHandler(SIGNAL_ARGS)
Definition postgres.c:3058
int client_connection_check_interval
Definition postgres.c:103
bool check_log_stats(bool *newval, void **extra, GucSource source)
Definition postgres.c:3564
static bool EchoQuery
Definition postgres.c:155
void StatementCancelHandler(SIGNAL_ARGS)
Definition postgres.c:3041
CommandDest whereToSendOutput
Definition postgres.c:92
static bool ignore_till_sync
Definition postgres.c:144
static void finish_xact_command(void)
Definition postgres.c:2810
bool set_plan_disabling_options(const char *arg, GucContext context, GucSource source)
Definition postgres.c:3696
static void enable_statement_timeout(void)
Definition postgres.c:5192
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:2424
static struct timeval Save_t
Definition postgres.c:5037
const char * debug_query_string
Definition postgres.c:89
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:3738
void HandleRecoveryConflictInterrupt(ProcSignalReason reason)
Definition postgres.c:3074
List * pg_rewrite_query(Query *query)
Definition postgres.c:802
static volatile sig_atomic_t RecoveryConflictPendingReasons[NUM_PROCSIGNALS]
Definition postgres.c:160
static int errdetail_execute(List *raw_parsetree_list)
Definition postgres.c:2487
void ShowUsage(const char *title)
Definition postgres.c:5047
static void exec_parse_message(const char *query_string, const char *stmt_name, Oid *paramTypes, int numParams)
Definition postgres.c:1393
int restrict_nonsystem_relation_kind
Definition postgres.c:106
static const char * userDoption
Definition postgres.c:154
static volatile sig_atomic_t RecoveryConflictPending
Definition postgres.c:159
static void exec_bind_message(StringInfo input_message)
Definition postgres.c:1627
static bool DoingCommandRead
Definition postgres.c:137
static bool xact_started
Definition postgres.c:130
static int interactive_getc(void)
Definition postgres.c:324
static int errdetail_params(ParamListInfo params)
Definition postgres.c:2520
static void ProcessRecoveryConflictInterrupts(void)
Definition postgres.c:3244
static int SocketBackend(StringInfo inBuf)
Definition postgres.c:352
void ProcessClientReadInterrupt(bool blocked)
Definition postgres.c:501
void ProcessInterrupts(void)
Definition postgres.c:3283
static void bind_param_error_callback(void *arg)
Definition postgres.c:2579
static bool IsTransactionExitStmt(Node *parsetree)
Definition postgres.c:2842
void PostgresMain(const char *dbname, const char *username)
Definition postgres.c:4172
static MemoryContext row_description_context
Definition postgres.c:163
static int InteractiveBackend(StringInfo inBuf)
Definition postgres.c:236
static void ProcessRecoveryConflictInterrupt(ProcSignalReason reason)
Definition postgres.c:3086
static struct rusage Save_r
Definition postgres.c:5036
bool check_client_connection_check_interval(int *newval, void **extra, GucSource source)
Definition postgres.c:3529
static StringInfoData row_description_buf
Definition postgres.c:164
void ProcessClientWriteInterrupt(bool blocked)
Definition postgres.c:547
static bool doing_extended_query_message
Definition postgres.c:143
void ResetUsage(void)
Definition postgres.c:5040
static void start_xact_command(void)
Definition postgres.c:2771
bool check_restrict_nonsystem_relation_kind(char **newval, void **extra, GucSource source)
Definition postgres.c:3598
static void exec_describe_portal_message(const char *portal_name)
Definition postgres.c:2720
bool Log_disconnections
Definition postgres.c:95
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:2889
#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:3550
uint64_t Datum
Definition postgres.h:70
#define InvalidOid
unsigned int Oid
void InitializeMaxBackends(void)
Definition postinit.c:550
void BaseInit(void)
Definition postinit.c:607
void InitializeFastPathLocks(void)
Definition postinit.c:575
void InitPostgres(const char *in_dbname, Oid dboid, const char *username, Oid useroid, bits32 flags, char *out_dbname)
Definition postinit.c:710
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:132
#define PG_PROTOCOL(m, n)
Definition pqcomm.h:89
unsigned int pq_getmsgint(StringInfo msg, int b)
Definition pqformat.c:414
void pq_sendbytes(StringInfo buf, const void *data, int datalen)
Definition pqformat.c:126
void pq_getmsgend(StringInfo msg)
Definition pqformat.c:634
const char * pq_getmsgstring(StringInfo msg)
Definition pqformat.c:578
void pq_putemptymessage(char msgtype)
Definition pqformat.c:387
void pq_endmessage(StringInfo buf)
Definition pqformat.c:296
int pq_getmsgbyte(StringInfo msg)
Definition pqformat.c:398
void pq_beginmessage(StringInfo buf, char msgtype)
Definition pqformat.c:88
const char * pq_getmsgbytes(StringInfo msg, int datalen)
Definition pqformat.c:507
void pq_beginmessage_reuse(StringInfo buf, char msgtype)
Definition pqformat.c:109
void pq_endmessage_reuse(StringInfo buf)
Definition pqformat.c:313
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:619
void PortalStart(Portal portal, ParamListInfo params, int eflags, Snapshot snapshot)
Definition pquery.c:429
List * FetchPortalTargetList(Portal portal)
Definition pquery.c:322
bool PortalRun(Portal portal, long count, bool isTopLevel, DestReceiver *dest, DestReceiver *altdest, QueryCompletion *qc)
Definition pquery.c:680
char * c
static int fb(int x)
void SetRemoteDestReceiverParams(DestReceiver *self, Portal portal)
Definition printtup.c:101
void SendRowDescriptionMessage(StringInfo buf, TupleDesc typeinfo, List *targetlist, int16 *formats)
Definition printtup.c:167
void ProcessProcSignalBarrier(void)
Definition procsignal.c:499
void procsignal_sigusr1_handler(SIGNAL_ARGS)
Definition procsignal.c:677
#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:69
#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:758
void ReplicationSlotCleanup(bool synced_only)
Definition slot.c:857
Snapshot GetTransactionSnapshot(void)
Definition snapmgr.c:272
void PushActiveSnapshot(Snapshot snapshot)
Definition snapmgr.c:682
bool ActiveSnapshotSet(void)
Definition snapmgr.c:812
void InvalidateCatalogSnapshotConditionally(void)
Definition snapmgr.c:477
void PopActiveSnapshot(void)
Definition snapmgr.c:775
#define InvalidSnapshot
Definition snapshot.h:119
int IdleSessionTimeout
Definition proc.c:63
int StatementTimeout
Definition proc.c:59
int IdleInTransactionSessionTimeout
Definition proc.c:61
int GetStartupBufferPinWaitBufId(void)
Definition proc.c:770
int TransactionTimeout
Definition proc.c:62
void LockErrorCleanup(void)
Definition proc.c:817
void InitProcess(void)
Definition proc.c:395
void CheckDeadLockAlert(void)
Definition proc.c:1878
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)
char bgw_type[BGW_MAXLEN]
Definition bgworker.h:99
const char * portalName
Definition postgres.c:116
const char * paramval
Definition postgres.c:118
const char * query_string
Definition plancache.h:110
List * stmt_list
Definition plancache.h:162
TimestampTz ready_for_use
TimestampTz auth_start
TimestampTz socket_create
TimestampTz fork_start
struct ErrorContextCallback * previous
Definition elog.h:297
void(* callback)(void *arg)
Definition elog.h:298
Definition pg_list.h:54
Definition nodes.h:135
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
CmdType commandType
Definition plannodes.h:68
Node * utilityStmt
Definition plannodes.h:150
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
CachedPlanSource * plansource
Definition prepare.h:32
CmdType commandType
Definition parsenodes.h:121
Node * utilityStmt
Definition parsenodes.h:141
ParseLoc stmt_location
Definition parsenodes.h:255
Node * stmt
struct timeval ru_utime
Definition resource.h:14
struct timeval ru_stime
Definition resource.h:15
#define RESTRICT_RELKIND_FOREIGN_TABLE
Definition tcopprot.h:45
#define RESTRICT_RELKIND_VIEW
Definition tcopprot.h:44
@ LOGSTMT_NONE
Definition tcopprot.h:34
@ LOGSTMT_ALL
Definition tcopprot.h:37
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:2369
LogStmtLevel GetCommandLogLevel(Node *parsetree)
Definition utility.c:3260
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:2730
const char * name
bool WaitEventSetCanReportClosed(void)
void WalSndErrorCleanup(void)
Definition walsender.c:348
bool am_walsender
Definition walsender.c:123
bool exec_replication_command(const char *cmd_string)
Definition walsender.c:2010
void InitWalSender(void)
Definition walsender.c:301
void WalSndSignals(void)
Definition walsender.c:3734
#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:5011
void BeginImplicitTransactionBlock(void)
Definition xact.c:4348
bool IsTransactionState(void)
Definition xact.c:388
void CommandCounterIncrement(void)
Definition xact.c:1101
void StartTransactionCommand(void)
Definition xact.c:3080
bool IsAbortedTransactionBlockState(void)
Definition xact.c:408
void EndImplicitTransactionBlock(void)
Definition xact.c:4373
bool IsSubTransaction(void)
Definition xact.c:5066
void SetCurrentStatementStartTimestamp(void)
Definition xact.c:915
TimestampTz GetCurrentStatementStartTimestamp(void)
Definition xact.c:880
void CommitTransactionCommand(void)
Definition xact.c:3178
bool xact_is_sampled
Definition xact.c:297
int MyXactFlags
Definition xact.c:137
void AbortCurrentTransaction(void)
Definition xact.c:3472
#define XACT_FLAGS_PIPELINING
Definition xact.h:122
#define XACT_FLAGS_NEEDIMMEDIATECOMMIT
Definition xact.h:115
void InitializeWalConsistencyChecking(void)
Definition xlog.c:4858
void LocalProcessControlFile(bool reset)
Definition xlog.c:4939