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