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