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