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 as errdetail when available (SA_SIGINFO).
115 * The caller must supply the (already-captured) pid and uid values.
116 */
117#define ERRDETAIL_SIGNAL_SENDER(pid, uid) \
118 ((pid) == 0 ? 0 : \
119 errdetail("Signal sent by PID %d, UID %d.", (int) (pid), (int) (uid)))
120
121/* ----------------
122 * private typedefs etc
123 * ----------------
124 */
125
126/* type of argument for bind_param_error_callback */
127typedef struct BindParamCbData
128{
129 const char *portalName;
130 int paramno; /* zero-based param number, or -1 initially */
131 const char *paramval; /* textual input string, if available */
133
134/* ----------------
135 * private variables
136 * ----------------
137 */
138
139/*
140 * Flag to keep track of whether we have started a transaction.
141 * For extended query protocol this has to be remembered across messages.
142 */
143static bool xact_started = false;
144
145/*
146 * Flag to indicate that we are doing the outer loop's read-from-client,
147 * as opposed to any random read from client that might happen within
148 * commands like COPY FROM STDIN.
149 */
150static bool DoingCommandRead = false;
151
152/*
153 * Flags to implement skip-till-Sync-after-error behavior for messages of
154 * the extended query protocol.
155 */
157static bool ignore_till_sync = false;
158
159/*
160 * If an unnamed prepared statement exists, it's stored here.
161 * We keep it separate from the hashtable kept by commands/prepare.c
162 * in order to reduce overhead for short-lived queries.
163 */
165
166/* assorted command-line switches */
167static const char *userDoption = NULL; /* -D switch */
168static bool EchoQuery = false; /* -E switch */
169static bool UseSemiNewlineNewline = false; /* -j switch */
170
171/* reused buffer to pass to SendRowDescriptionMessage() */
174
175/* ----------------------------------------------------------------
176 * decls for routines only used in this file
177 * ----------------------------------------------------------------
178 */
180static int interactive_getc(void);
181static int SocketBackend(StringInfo inBuf);
182static int ReadCommand(StringInfo inBuf);
183static void forbidden_in_wal_sender(char firstchar);
184static bool check_log_statement(List *stmt_list);
186static int errdetail_params(ParamListInfo params);
187static void bind_param_error_callback(void *arg);
188static void start_xact_command(void);
189static void finish_xact_command(void);
190static bool IsTransactionExitStmt(Node *parsetree);
192static bool IsTransactionStmtList(List *pstmts);
193static void drop_unnamed_stmt(void);
194static void ProcessRecoveryConflictInterrupts(void);
197static void log_disconnections(int code, Datum arg);
198static void enable_statement_timeout(void);
199static void disable_statement_timeout(void);
200
201
202/* ----------------------------------------------------------------
203 * infrastructure for valgrind debugging
204 * ----------------------------------------------------------------
205 */
206#ifdef USE_VALGRIND
207/* This variable should be set at the top of the main loop. */
208static unsigned int old_valgrind_error_count;
209
210/*
211 * If Valgrind detected any errors since old_valgrind_error_count was updated,
212 * report the current query as the cause. This should be called at the end
213 * of message processing.
214 */
215static void
216valgrind_report_error_query(const char *query)
217{
219
221 query != NULL)
222 VALGRIND_PRINTF("Valgrind detected %u error(s) during execution of \"%s\"\n",
224 query);
225}
226
227#else /* !USE_VALGRIND */
228#define valgrind_report_error_query(query) ((void) 0)
229#endif /* USE_VALGRIND */
230
231
232/* ----------------------------------------------------------------
233 * routines to obtain user input
234 * ----------------------------------------------------------------
235 */
236
237/* ----------------
238 * InteractiveBackend() is called for user interactive connections
239 *
240 * the string entered by the user is placed in its parameter inBuf,
241 * and we act like a Q message was received.
242 *
243 * EOF is returned if end-of-file input is seen; time to shut down.
244 * ----------------
245 */
246
247static int
249{
250 int c; /* character read from getc() */
251
252 /*
253 * display a prompt and obtain input from the user
254 */
255 printf("backend> ");
256 fflush(stdout);
257
259
260 /*
261 * Read characters until EOF or the appropriate delimiter is seen.
262 */
263 while ((c = interactive_getc()) != EOF)
264 {
265 if (c == '\n')
266 {
268 {
269 /*
270 * In -j mode, semicolon followed by two newlines ends the
271 * command; otherwise treat newline as regular character.
272 */
273 if (inBuf->len > 1 &&
274 inBuf->data[inBuf->len - 1] == '\n' &&
275 inBuf->data[inBuf->len - 2] == ';')
276 {
277 /* might as well drop the second newline */
278 break;
279 }
280 }
281 else
282 {
283 /*
284 * In plain mode, newline ends the command unless preceded by
285 * backslash.
286 */
287 if (inBuf->len > 0 &&
288 inBuf->data[inBuf->len - 1] == '\\')
289 {
290 /* discard backslash from inBuf */
291 inBuf->data[--inBuf->len] = '\0';
292 /* discard newline too */
293 continue;
294 }
295 else
296 {
297 /* keep the newline character, but end the command */
299 break;
300 }
301 }
302 }
303
304 /* Not newline, or newline treated as regular character */
306 }
307
308 /* No input before EOF signal means time to quit. */
309 if (c == EOF && inBuf->len == 0)
310 return EOF;
311
312 /*
313 * otherwise we have a user query so process it.
314 */
315
316 /* Add '\0' to make it look the same as message case. */
317 appendStringInfoChar(inBuf, (char) '\0');
318
319 /*
320 * if the query echo flag was given, print the query..
321 */
322 if (EchoQuery)
323 printf("statement: %s\n", inBuf->data);
324 fflush(stdout);
325
326 return PqMsg_Query;
327}
328
329/*
330 * interactive_getc -- collect one character from stdin
331 *
332 * Even though we are not reading from a "client" process, we still want to
333 * respond to signals, particularly SIGTERM/SIGQUIT.
334 */
335static int
337{
338 int c;
339
340 /*
341 * This will not process catchup interrupts or notifications while
342 * reading. But those can't really be relevant for a standalone backend
343 * anyway. To properly handle SIGTERM there's a hack in die() that
344 * directly processes interrupts at this stage...
345 */
347
348 c = getc(stdin);
349
351
352 return c;
353}
354
355/* ----------------
356 * SocketBackend() Is called for frontend-backend connections
357 *
358 * Returns the message type code, and loads message body data into inBuf.
359 *
360 * EOF is returned if the connection is lost.
361 * ----------------
362 */
363static int
365{
366 int qtype;
367 int maxmsglen;
368
369 /*
370 * Get message type code from the frontend.
371 */
374 qtype = pq_getbyte();
375
376 if (qtype == EOF) /* frontend disconnected */
377 {
378 if (IsTransactionState())
381 errmsg("unexpected EOF on client connection with an open transaction")));
382 else
383 {
384 /*
385 * Can't send DEBUG log messages to client at this point. Since
386 * we're disconnecting right away, we don't need to restore
387 * whereToSendOutput.
388 */
392 errmsg_internal("unexpected EOF on client connection")));
393 }
394 return qtype;
395 }
396
397 /*
398 * Validate message type code before trying to read body; if we have lost
399 * sync, better to say "command unknown" than to run out of memory because
400 * we used garbage as a length word. We can also select a type-dependent
401 * limit on what a sane length word could be. (The limit could be chosen
402 * more granularly, but it's not clear it's worth fussing over.)
403 *
404 * This also gives us a place to set the doing_extended_query_message flag
405 * as soon as possible.
406 */
407 switch (qtype)
408 {
409 case PqMsg_Query:
412 break;
413
417 break;
418
419 case PqMsg_Terminate:
422 ignore_till_sync = false;
423 break;
424
425 case PqMsg_Bind:
426 case PqMsg_Parse:
429 break;
430
431 case PqMsg_Close:
432 case PqMsg_Describe:
433 case PqMsg_Execute:
434 case PqMsg_Flush:
437 break;
438
439 case PqMsg_Sync:
441 /* stop any active skip-till-Sync */
442 ignore_till_sync = false;
443 /* mark not-extended, so that a new error doesn't begin skip */
445 break;
446
447 case PqMsg_CopyData:
450 break;
451
452 case PqMsg_CopyDone:
453 case PqMsg_CopyFail:
456 break;
457
458 default:
459
460 /*
461 * Otherwise we got garbage from the frontend. We treat this as
462 * fatal because we have probably lost message boundary sync, and
463 * there's no good way to recover.
464 */
467 errmsg("invalid frontend message type %d", qtype)));
468 maxmsglen = 0; /* keep compiler quiet */
469 break;
470 }
471
472 /*
473 * In protocol version 3, all frontend messages have a length word next
474 * after the type code; we can read the message contents independently of
475 * the type.
476 */
478 return EOF; /* suitable message already logged */
480
481 return qtype;
482}
483
484/* ----------------
485 * ReadCommand reads a command from either the frontend or
486 * standard input, places it in inBuf, and returns the
487 * message type code (first byte of the message).
488 * EOF is returned if end of file.
489 * ----------------
490 */
491static int
493{
494 int result;
495
498 else
500 return result;
501}
502
503/*
504 * ProcessClientReadInterrupt() - Process interrupts specific to client reads
505 *
506 * This is called just before and after low-level reads.
507 * 'blocked' is true if no data was available to read and we plan to retry,
508 * false if about to read or done reading.
509 *
510 * Must preserve errno!
511 */
512void
514{
515 int save_errno = errno;
516
518 {
519 /* Check for general interrupts that arrived before/while reading */
521
522 /* Process sinval catchup interrupts, if any */
525
526 /* Process notify interrupts, if any */
529 }
530 else if (ProcDiePending)
531 {
532 /*
533 * We're dying. If there is no data available to read, then it's safe
534 * (and sane) to handle that now. If we haven't tried to read yet,
535 * make sure the process latch is set, so that if there is no data
536 * then we'll come back here and die. If we're done reading, also
537 * make sure the process latch is set, as we might've undesirably
538 * cleared it while reading.
539 */
540 if (blocked)
542 else
544 }
545
547}
548
549/*
550 * ProcessClientWriteInterrupt() - Process interrupts specific to client writes
551 *
552 * This is called just before and after low-level writes.
553 * 'blocked' is true if no data could be written and we plan to retry,
554 * false if about to write or done writing.
555 *
556 * Must preserve errno!
557 */
558void
560{
561 int save_errno = errno;
562
563 if (ProcDiePending)
564 {
565 /*
566 * We're dying. If it's not possible to write, then we should handle
567 * that immediately, else a stuck client could indefinitely delay our
568 * response to the signal. If we haven't tried to write yet, make
569 * sure the process latch is set, so that if the write would block
570 * then we'll come back here and die. If we're done writing, also
571 * make sure the process latch is set, as we might've undesirably
572 * cleared it while writing.
573 */
574 if (blocked)
575 {
576 /*
577 * Don't mess with whereToSendOutput if ProcessInterrupts wouldn't
578 * service ProcDiePending.
579 */
581 {
582 /*
583 * We don't want to send the client the error message, as a)
584 * that would possibly block again, and b) it would likely
585 * lead to loss of protocol sync because we may have already
586 * sent a partial protocol message.
587 */
590
592 }
593 }
594 else
596 }
597
599}
600
601/*
602 * Do raw parsing (only).
603 *
604 * A list of parsetrees (RawStmt nodes) is returned, since there might be
605 * multiple commands in the given string.
606 *
607 * NOTE: for interactive queries, it is important to keep this routine
608 * separate from the analysis & rewrite stages. Analysis and rewriting
609 * cannot be done in an aborted transaction, since they require access to
610 * database tables. So, we rely on the raw parser to determine whether
611 * we've seen a COMMIT or ABORT command; when we are in abort state, other
612 * commands are not processed any further than the raw parse stage.
613 */
614List *
615pg_parse_query(const char *query_string)
616{
618
620
622 ResetUsage();
623
625
627 ShowUsage("PARSER STATISTICS");
628
629#ifdef DEBUG_NODE_TESTS_ENABLED
630
631 /* Optional debugging check: pass raw parsetrees through copyObject() */
633 {
635
636 /* This checks both copyObject() and the equal() routines... */
638 elog(WARNING, "copyObject() failed to produce an equal raw parse tree");
639 else
641 }
642
643 /*
644 * Optional debugging check: pass raw parsetrees through
645 * outfuncs/readfuncs
646 */
648 {
651
652 pfree(str);
653 /* This checks both outfuncs/readfuncs and the equal() routines... */
655 elog(WARNING, "outfuncs/readfuncs failed to produce an equal raw parse tree");
656 else
658 }
659
660#endif /* DEBUG_NODE_TESTS_ENABLED */
661
663
665 elog_node_display(LOG, "raw parse tree", raw_parsetree_list,
667
668 return raw_parsetree_list;
669}
670
671/*
672 * Given a raw parsetree (gram.y output), and optionally information about
673 * types of parameter symbols ($n), perform parse analysis and rule rewriting.
674 *
675 * A list of Query nodes is returned, since either the analyzer or the
676 * rewriter might expand one query to several.
677 *
678 * NOTE: for reasons mentioned above, this must be separate from raw parsing.
679 */
680List *
682 const char *query_string,
683 const Oid *paramTypes,
684 int numParams,
685 QueryEnvironment *queryEnv)
686{
687 Query *query;
689
691
692 /*
693 * (1) Perform parse analysis.
694 */
696 ResetUsage();
697
698 query = parse_analyze_fixedparams(parsetree, query_string, paramTypes, numParams,
699 queryEnv);
700
702 ShowUsage("PARSE ANALYSIS STATISTICS");
703
704 /*
705 * (2) Rewrite the queries, as necessary
706 */
708
710
711 return querytree_list;
712}
713
714/*
715 * Do parse analysis and rewriting. This is the same as
716 * pg_analyze_and_rewrite_fixedparams except that it's okay to deduce
717 * information about $n symbol datatypes from context.
718 */
719List *
721 const char *query_string,
722 Oid **paramTypes,
723 int *numParams,
724 QueryEnvironment *queryEnv)
725{
726 Query *query;
728
730
731 /*
732 * (1) Perform parse analysis.
733 */
735 ResetUsage();
736
737 query = parse_analyze_varparams(parsetree, query_string, paramTypes, numParams,
738 queryEnv);
739
740 /*
741 * Check all parameter types got determined.
742 */
743 for (int i = 0; i < *numParams; i++)
744 {
745 Oid ptype = (*paramTypes)[i];
746
747 if (ptype == InvalidOid || ptype == UNKNOWNOID)
750 errmsg("could not determine data type of parameter $%d",
751 i + 1)));
752 }
753
755 ShowUsage("PARSE ANALYSIS STATISTICS");
756
757 /*
758 * (2) Rewrite the queries, as necessary
759 */
761
763
764 return querytree_list;
765}
766
767/*
768 * Do parse analysis and rewriting. This is the same as
769 * pg_analyze_and_rewrite_fixedparams except that, instead of a fixed list of
770 * parameter datatypes, a parser callback is supplied that can do
771 * external-parameter resolution and possibly other things.
772 */
773List *
775 const char *query_string,
776 ParserSetupHook parserSetup,
777 void *parserSetupArg,
778 QueryEnvironment *queryEnv)
779{
780 Query *query;
782
784
785 /*
786 * (1) Perform parse analysis.
787 */
789 ResetUsage();
790
791 query = parse_analyze_withcb(parsetree, query_string, parserSetup, parserSetupArg,
792 queryEnv);
793
795 ShowUsage("PARSE ANALYSIS STATISTICS");
796
797 /*
798 * (2) Rewrite the queries, as necessary
799 */
801
803
804 return querytree_list;
805}
806
807/*
808 * Perform rewriting of a query produced by parse analysis.
809 *
810 * Note: query must just have come from the parser, because we do not do
811 * AcquireRewriteLocks() on it.
812 */
813List *
815{
817
819 elog_node_display(LOG, "parse tree", query,
821
823 ResetUsage();
824
825 if (query->commandType == CMD_UTILITY)
826 {
827 /* don't rewrite utilities, just dump 'em into result list */
828 querytree_list = list_make1(query);
829 }
830 else
831 {
832 /* rewrite regular queries */
834 }
835
837 ShowUsage("REWRITER STATISTICS");
838
839#ifdef DEBUG_NODE_TESTS_ENABLED
840
841 /* Optional debugging check: pass querytree through copyObject() */
843 {
844 List *new_list;
845
847 /* This checks both copyObject() and the equal() routines... */
849 elog(WARNING, "copyObject() failed to produce an equal rewritten parse tree");
850 else
852 }
853
854 /* Optional debugging check: pass querytree through outfuncs/readfuncs */
856 {
857 List *new_list = NIL;
858 ListCell *lc;
859
860 foreach(lc, querytree_list)
861 {
865
866 /*
867 * queryId is not saved in stored rules, but we must preserve it
868 * here to avoid breaking pg_stat_statements.
869 */
870 new_query->queryId = curr_query->queryId;
871
873 pfree(str);
874 }
875
876 /* This checks both outfuncs/readfuncs and the equal() routines... */
878 elog(WARNING, "outfuncs/readfuncs failed to produce an equal rewritten parse tree");
879 else
881 }
882
883#endif /* DEBUG_NODE_TESTS_ENABLED */
884
886 elog_node_display(LOG, "rewritten parse tree", querytree_list,
888
889 return querytree_list;
890}
891
892
893/*
894 * Generate a plan for a single already-rewritten query.
895 * This is a thin wrapper around planner() and takes the same parameters.
896 */
898pg_plan_query(Query *querytree, const char *query_string, int cursorOptions,
899 ParamListInfo boundParams, ExplainState *es)
900{
902
903 /* Utility commands have no plans. */
904 if (querytree->commandType == CMD_UTILITY)
905 return NULL;
906
907 /* Planner must have a snapshot in case it calls user-defined functions. */
909
911
913 ResetUsage();
914
915 /* call the optimizer */
916 plan = planner(querytree, query_string, cursorOptions, boundParams, es);
917
919 ShowUsage("PLANNER STATISTICS");
920
921#ifdef DEBUG_NODE_TESTS_ENABLED
922
923 /* Optional debugging check: pass plan tree through copyObject() */
925 {
927
928 /*
929 * equal() currently does not have routines to compare Plan nodes, so
930 * don't try to test equality here. Perhaps fix someday?
931 */
932#ifdef NOT_USED
933 /* This checks both copyObject() and the equal() routines... */
934 if (!equal(new_plan, plan))
935 elog(WARNING, "copyObject() failed to produce an equal plan tree");
936 else
937#endif
938 plan = new_plan;
939 }
940
941 /* Optional debugging check: pass plan tree through outfuncs/readfuncs */
943 {
944 char *str;
946
949 pfree(str);
950
951 /*
952 * equal() currently does not have routines to compare Plan nodes, so
953 * don't try to test equality here. Perhaps fix someday?
954 */
955#ifdef NOT_USED
956 /* This checks both outfuncs/readfuncs and the equal() routines... */
957 if (!equal(new_plan, plan))
958 elog(WARNING, "outfuncs/readfuncs failed to produce an equal plan tree");
959 else
960#endif
961 plan = new_plan;
962 }
963
964#endif /* DEBUG_NODE_TESTS_ENABLED */
965
966 /*
967 * Print plan if debugging.
968 */
971
973
974 return plan;
975}
976
977/*
978 * Generate plans for a list of already-rewritten queries.
979 *
980 * For normal optimizable statements, invoke the planner. For utility
981 * statements, just make a wrapper PlannedStmt node.
982 *
983 * The result is a list of PlannedStmt nodes.
984 */
985List *
986pg_plan_queries(List *querytrees, const char *query_string, int cursorOptions,
987 ParamListInfo boundParams)
988{
989 List *stmt_list = NIL;
990 ListCell *query_list;
991
992 foreach(query_list, querytrees)
993 {
994 Query *query = lfirst_node(Query, query_list);
996
997 if (query->commandType == CMD_UTILITY)
998 {
999 /* Utility commands require no planning. */
1001 stmt->commandType = CMD_UTILITY;
1002 stmt->canSetTag = query->canSetTag;
1003 stmt->utilityStmt = query->utilityStmt;
1004 stmt->stmt_location = query->stmt_location;
1005 stmt->stmt_len = query->stmt_len;
1006 stmt->queryId = query->queryId;
1007 stmt->planOrigin = PLAN_STMT_INTERNAL;
1008 }
1009 else
1010 {
1011 stmt = pg_plan_query(query, query_string, cursorOptions,
1012 boundParams, NULL);
1013 }
1014
1015 stmt_list = lappend(stmt_list, stmt);
1016 }
1017
1018 return stmt_list;
1019}
1020
1021
1022/*
1023 * exec_simple_query
1024 *
1025 * Execute a "simple Query" protocol message.
1026 */
1027static void
1028exec_simple_query(const char *query_string)
1029{
1031 MemoryContext oldcontext;
1035 bool was_logged = false;
1036 bool use_implicit_block;
1037 char msec_str[32];
1038
1039 /*
1040 * Report query to various monitoring facilities.
1041 */
1042 debug_query_string = query_string;
1043
1045
1046 TRACE_POSTGRESQL_QUERY_START(query_string);
1047
1048 /*
1049 * We use save_log_statement_stats so ShowUsage doesn't report incorrect
1050 * results because ResetUsage wasn't called.
1051 */
1053 ResetUsage();
1054
1055 /*
1056 * Start up a transaction command. All queries generated by the
1057 * query_string will be in this same command block, *unless* we find a
1058 * BEGIN/COMMIT/ABORT statement; we have to force a new xact command after
1059 * one of those, else bad things will happen in xact.c. (Note that this
1060 * will normally change current memory context.)
1061 */
1063
1064 /*
1065 * Zap any pre-existing unnamed statement. (While not strictly necessary,
1066 * it seems best to define simple-Query mode as if it used the unnamed
1067 * statement and portal; this ensures we recover any storage used by prior
1068 * unnamed operations.)
1069 */
1071
1072 /*
1073 * Switch to appropriate context for constructing parsetrees.
1074 */
1076
1077 /*
1078 * Do basic parsing of the query or queries (this should be safe even if
1079 * we are in aborted transaction state!)
1080 */
1081 parsetree_list = pg_parse_query(query_string);
1082
1083 /* Log immediately if dictated by log_statement */
1085 {
1086 ereport(LOG,
1087 (errmsg("statement: %s", query_string),
1088 errhidestmt(true),
1090 was_logged = true;
1091 }
1092
1093 /*
1094 * Switch back to transaction context to enter the loop.
1095 */
1096 MemoryContextSwitchTo(oldcontext);
1097
1098 /*
1099 * For historical reasons, if multiple SQL statements are given in a
1100 * single "simple Query" message, we execute them as a single transaction,
1101 * unless explicit transaction control commands are included to make
1102 * portions of the list be separate transactions. To represent this
1103 * behavior properly in the transaction machinery, we use an "implicit"
1104 * transaction block.
1105 */
1107
1108 /*
1109 * Run through the raw parsetree(s) and process each one.
1110 */
1112 {
1114 bool snapshot_set = false;
1115 CommandTag commandTag;
1116 QueryCompletion qc;
1120 Portal portal;
1122 int16 format;
1123 const char *cmdtagname;
1124 size_t cmdtaglen;
1125
1126 pgstat_report_query_id(0, true);
1127 pgstat_report_plan_id(0, true);
1128
1129 /*
1130 * Get the command name for use in status display (it also becomes the
1131 * default completion tag, in PortalDefineQuery). Set ps_status and
1132 * do any special start-of-SQL-command processing needed by the
1133 * destination.
1134 */
1135 commandTag = CreateCommandTag(parsetree->stmt);
1137
1139
1140 BeginCommand(commandTag, dest);
1141
1142 /*
1143 * If we are in an aborted transaction, reject all commands except
1144 * COMMIT/ABORT. It is important that this test occur before we try
1145 * to do parse analysis, rewrite, or planning, since all those phases
1146 * try to do database accesses, which may fail in abort state. (It
1147 * might be safe to allow some additional utility commands in this
1148 * state, but not many...)
1149 */
1151 !IsTransactionExitStmt(parsetree->stmt))
1152 ereport(ERROR,
1154 errmsg("current transaction is aborted, "
1155 "commands ignored until end of transaction block")));
1156
1157 /* Make sure we are in a transaction command */
1159
1160 /*
1161 * If using an implicit transaction block, and we're not already in a
1162 * transaction block, start an implicit block to force this statement
1163 * to be grouped together with any following ones. (We must do this
1164 * each time through the loop; otherwise, a COMMIT/ROLLBACK in the
1165 * list would cause later statements to not be grouped.)
1166 */
1169
1170 /* If we got a cancel signal in parsing or prior command, quit */
1172
1173 /*
1174 * Set up a snapshot if parse analysis/planning will need one.
1175 */
1176 if (analyze_requires_snapshot(parsetree))
1177 {
1179 snapshot_set = true;
1180 }
1181
1182 /*
1183 * OK to analyze, rewrite, and plan this query.
1184 *
1185 * Switch to appropriate context for constructing query and plan trees
1186 * (these can't be in the transaction context, as that will get reset
1187 * when the command is COMMIT/ROLLBACK). If we have multiple
1188 * parsetrees, we use a separate context for each one, so that we can
1189 * free that memory before moving on to the next one. But for the
1190 * last (or only) parsetree, just use MessageContext, which will be
1191 * reset shortly after completion anyway. In event of an error, the
1192 * per_parsetree_context will be deleted when MessageContext is reset.
1193 */
1195 {
1198 "per-parsetree message context",
1201 }
1202 else
1204
1205 querytree_list = pg_analyze_and_rewrite_fixedparams(parsetree, query_string,
1206 NULL, 0, NULL);
1207
1210
1211 /*
1212 * Done with the snapshot used for parsing/planning.
1213 *
1214 * While it looks promising to reuse the same snapshot for query
1215 * execution (at least for simple protocol), unfortunately it causes
1216 * execution to use a snapshot that has been acquired before locking
1217 * any of the tables mentioned in the query. This creates user-
1218 * visible anomalies, so refrain. Refer to
1219 * https://postgr.es/m/flat/5075D8DF.6050500@fuzzy.cz for details.
1220 */
1221 if (snapshot_set)
1223
1224 /* If we got a cancel signal in analysis or planning, quit */
1226
1227 /*
1228 * Create unnamed portal to run the query or queries in. If there
1229 * already is one, silently drop it.
1230 */
1231 portal = CreatePortal("", true, true);
1232 /* Don't display the portal in pg_cursors */
1233 portal->visible = false;
1234
1235 /*
1236 * We don't have to copy anything into the portal, because everything
1237 * we are passing here is in MessageContext or the
1238 * per_parsetree_context, and so will outlive the portal anyway.
1239 */
1240 PortalDefineQuery(portal,
1241 NULL,
1242 query_string,
1243 commandTag,
1245 NULL);
1246
1247 /*
1248 * Start the portal. No parameters here.
1249 */
1250 PortalStart(portal, NULL, 0, InvalidSnapshot);
1251
1252 /*
1253 * Select the appropriate output format: text unless we are doing a
1254 * FETCH from a binary cursor. (Pretty grotty to have to do this here
1255 * --- but it avoids grottiness in other places. Ah, the joys of
1256 * backward compatibility...)
1257 */
1258 format = 0; /* TEXT is default */
1259 if (IsA(parsetree->stmt, FetchStmt))
1260 {
1261 FetchStmt *stmt = (FetchStmt *) parsetree->stmt;
1262
1263 if (!stmt->ismove)
1264 {
1265 Portal fportal = GetPortalByName(stmt->portalname);
1266
1267 if (PortalIsValid(fportal) &&
1268 (fportal->cursorOptions & CURSOR_OPT_BINARY))
1269 format = 1; /* BINARY */
1270 }
1271 }
1272 PortalSetResultFormat(portal, 1, &format);
1273
1274 /*
1275 * Now we can create the destination receiver object.
1276 */
1278 if (dest == DestRemote)
1280
1281 /*
1282 * Switch back to transaction context for execution.
1283 */
1284 MemoryContextSwitchTo(oldcontext);
1285
1286 /*
1287 * Run the portal to completion, and then drop it (and the receiver).
1288 */
1289 (void) PortalRun(portal,
1290 FETCH_ALL,
1291 true, /* always top level */
1292 receiver,
1293 receiver,
1294 &qc);
1295
1296 receiver->rDestroy(receiver);
1297
1298 PortalDrop(portal, false);
1299
1301 {
1302 /*
1303 * If this is the last parsetree of the query string, close down
1304 * transaction statement before reporting command-complete. This
1305 * is so that any end-of-transaction errors are reported before
1306 * the command-complete message is issued, to avoid confusing
1307 * clients who will expect either a command-complete message or an
1308 * error, not one and then the other. Also, if we're using an
1309 * implicit transaction block, we must close that out first.
1310 */
1314 }
1315 else if (IsA(parsetree->stmt, TransactionStmt))
1316 {
1317 /*
1318 * If this was a transaction control statement, commit it. We will
1319 * start a new xact command for the next command.
1320 */
1322 }
1323 else
1324 {
1325 /*
1326 * We had better not see XACT_FLAGS_NEEDIMMEDIATECOMMIT set if
1327 * we're not calling finish_xact_command(). (The implicit
1328 * transaction block should have prevented it from getting set.)
1329 */
1331
1332 /*
1333 * We need a CommandCounterIncrement after every query, except
1334 * those that start or end a transaction block.
1335 */
1337
1338 /*
1339 * Disable statement timeout between queries of a multi-query
1340 * string, so that the timeout applies separately to each query.
1341 * (Our next loop iteration will start a fresh timeout.)
1342 */
1344 }
1345
1346 /*
1347 * Tell client that we're done with this query. Note we emit exactly
1348 * one EndCommand report for each raw parsetree, thus one for each SQL
1349 * command the client sent, regardless of rewriting. (But a command
1350 * aborted by error will not send an EndCommand report at all.)
1351 */
1352 EndCommand(&qc, dest, false);
1353
1354 /* Now we may drop the per-parsetree context, if one was created. */
1357 } /* end loop over parsetrees */
1358
1359 /*
1360 * Close down transaction statement, if one is open. (This will only do
1361 * something if the parsetree list was empty; otherwise the last loop
1362 * iteration already did it.)
1363 */
1365
1366 /*
1367 * If there were no parsetrees, return EmptyQueryResponse message.
1368 */
1369 if (!parsetree_list)
1370 NullCommand(dest);
1371
1372 /*
1373 * Emit duration logging if appropriate.
1374 */
1376 {
1377 case 1:
1378 ereport(LOG,
1379 (errmsg("duration: %s ms", msec_str),
1380 errhidestmt(true)));
1381 break;
1382 case 2:
1383 ereport(LOG,
1384 (errmsg("duration: %s ms statement: %s",
1385 msec_str, query_string),
1386 errhidestmt(true),
1388 break;
1389 }
1390
1392 ShowUsage("QUERY STATISTICS");
1393
1394 TRACE_POSTGRESQL_QUERY_DONE(query_string);
1395
1397}
1398
1399/*
1400 * exec_parse_message
1401 *
1402 * Execute a "Parse" protocol message.
1403 */
1404static void
1405exec_parse_message(const char *query_string, /* string to execute */
1406 const char *stmt_name, /* name for prepared stmt */
1407 Oid *paramTypes, /* parameter types */
1408 int numParams) /* number of parameters */
1409{
1411 MemoryContext oldcontext;
1413 RawStmt *raw_parse_tree;
1416 bool is_named;
1418 char msec_str[32];
1419
1420 /*
1421 * Report query to various monitoring facilities.
1422 */
1423 debug_query_string = query_string;
1424
1426
1427 set_ps_display("PARSE");
1428
1430 ResetUsage();
1431
1433 (errmsg_internal("parse %s: %s",
1434 *stmt_name ? stmt_name : "<unnamed>",
1435 query_string)));
1436
1437 /*
1438 * Start up a transaction command so we can run parse analysis etc. (Note
1439 * that this will normally change current memory context.) Nothing happens
1440 * if we are already in one. This also arms the statement timeout if
1441 * necessary.
1442 */
1444
1445 /*
1446 * Switch to appropriate context for constructing parsetrees.
1447 *
1448 * We have two strategies depending on whether the prepared statement is
1449 * named or not. For a named prepared statement, we do parsing in
1450 * MessageContext and copy the finished trees into the prepared
1451 * statement's plancache entry; then the reset of MessageContext releases
1452 * temporary space used by parsing and rewriting. For an unnamed prepared
1453 * statement, we assume the statement isn't going to hang around long, so
1454 * getting rid of temp space quickly is probably not worth the costs of
1455 * copying parse trees. So in this case, we create the plancache entry's
1456 * query_context here, and do all the parsing work therein.
1457 */
1458 is_named = (stmt_name[0] != '\0');
1459 if (is_named)
1460 {
1461 /* Named prepared statement --- parse in MessageContext */
1463 }
1464 else
1465 {
1466 /* Unnamed prepared statement --- release any prior unnamed stmt */
1468 /* Create context for parsing */
1471 "unnamed prepared statement",
1474 }
1475
1476 /*
1477 * Do basic parsing of the query or queries (this should be safe even if
1478 * we are in aborted transaction state!)
1479 */
1480 parsetree_list = pg_parse_query(query_string);
1481
1482 /*
1483 * We only allow a single user statement in a prepared statement. This is
1484 * mainly to keep the protocol simple --- otherwise we'd need to worry
1485 * about multiple result tupdescs and things like that.
1486 */
1487 if (list_length(parsetree_list) > 1)
1488 ereport(ERROR,
1490 errmsg("cannot insert multiple commands into a prepared statement")));
1491
1492 if (parsetree_list != NIL)
1493 {
1494 bool snapshot_set = false;
1495
1496 raw_parse_tree = linitial_node(RawStmt, parsetree_list);
1497
1498 /*
1499 * If we are in an aborted transaction, reject all commands except
1500 * COMMIT/ROLLBACK. It is important that this test occur before we
1501 * try to do parse analysis, rewrite, or planning, since all those
1502 * phases try to do database accesses, which may fail in abort state.
1503 * (It might be safe to allow some additional utility commands in this
1504 * state, but not many...)
1505 */
1507 !IsTransactionExitStmt(raw_parse_tree->stmt))
1508 ereport(ERROR,
1510 errmsg("current transaction is aborted, "
1511 "commands ignored until end of transaction block")));
1512
1513 /*
1514 * Create the CachedPlanSource before we do parse analysis, since it
1515 * needs to see the unmodified raw parse tree.
1516 */
1517 psrc = CreateCachedPlan(raw_parse_tree, query_string,
1518 CreateCommandTag(raw_parse_tree->stmt));
1519
1520 /*
1521 * Set up a snapshot if parse analysis will need one.
1522 */
1523 if (analyze_requires_snapshot(raw_parse_tree))
1524 {
1526 snapshot_set = true;
1527 }
1528
1529 /*
1530 * Analyze and rewrite the query. Note that the originally specified
1531 * parameter set is not required to be complete, so we have to use
1532 * pg_analyze_and_rewrite_varparams().
1533 */
1535 query_string,
1536 &paramTypes,
1537 &numParams,
1538 NULL);
1539
1540 /* Done with the snapshot used for parsing */
1541 if (snapshot_set)
1543 }
1544 else
1545 {
1546 /* Empty input string. This is legal. */
1547 raw_parse_tree = NULL;
1548 psrc = CreateCachedPlan(raw_parse_tree, query_string,
1551 }
1552
1553 /*
1554 * CachedPlanSource must be a direct child of MessageContext before we
1555 * reparent unnamed_stmt_context under it, else we have a disconnected
1556 * circular subgraph. Klugy, but less so than flipping contexts even more
1557 * above.
1558 */
1561
1562 /* Finish filling in the CachedPlanSource */
1566 paramTypes,
1567 numParams,
1568 NULL,
1569 NULL,
1570 CURSOR_OPT_PARALLEL_OK, /* allow parallel mode */
1571 true); /* fixed result */
1572
1573 /* If we got a cancel signal during analysis, quit */
1575
1576 if (is_named)
1577 {
1578 /*
1579 * Store the query as a prepared statement.
1580 */
1581 StorePreparedStatement(stmt_name, psrc, false);
1582 }
1583 else
1584 {
1585 /*
1586 * We just save the CachedPlanSource into unnamed_stmt_psrc.
1587 */
1590 }
1591
1592 MemoryContextSwitchTo(oldcontext);
1593
1594 /*
1595 * We do NOT close the open transaction command here; that only happens
1596 * when the client sends Sync. Instead, do CommandCounterIncrement just
1597 * in case something happened during parse/plan.
1598 */
1600
1601 /*
1602 * Send ParseComplete.
1603 */
1606
1607 /*
1608 * Emit duration logging if appropriate.
1609 */
1610 switch (check_log_duration(msec_str, false))
1611 {
1612 case 1:
1613 ereport(LOG,
1614 (errmsg("duration: %s ms", msec_str),
1615 errhidestmt(true)));
1616 break;
1617 case 2:
1618 ereport(LOG,
1619 (errmsg("duration: %s ms parse %s: %s",
1620 msec_str,
1621 *stmt_name ? stmt_name : "<unnamed>",
1622 query_string),
1623 errhidestmt(true)));
1624 break;
1625 }
1626
1628 ShowUsage("PARSE MESSAGE STATISTICS");
1629
1631}
1632
1633/*
1634 * exec_bind_message
1635 *
1636 * Process a "Bind" message to create a portal from a prepared statement
1637 */
1638static void
1640{
1641 const char *portal_name;
1642 const char *stmt_name;
1643 int numPFormats;
1644 int16 *pformats = NULL;
1645 int numParams;
1646 int numRFormats;
1647 int16 *rformats = NULL;
1649 CachedPlan *cplan;
1650 Portal portal;
1651 char *query_string;
1652 char *saved_stmt_name;
1653 ParamListInfo params;
1656 bool snapshot_set = false;
1657 char msec_str[32];
1660 ListCell *lc;
1661
1662 /* Get the fixed part of the message */
1664 stmt_name = pq_getmsgstring(input_message);
1665
1667 (errmsg_internal("bind %s to %s",
1668 *portal_name ? portal_name : "<unnamed>",
1669 *stmt_name ? stmt_name : "<unnamed>")));
1670
1671 /* Find prepared statement */
1672 if (stmt_name[0] != '\0')
1673 {
1674 PreparedStatement *pstmt;
1675
1676 pstmt = FetchPreparedStatement(stmt_name, true);
1677 psrc = pstmt->plansource;
1678 }
1679 else
1680 {
1681 /* special-case the unnamed statement */
1683 if (!psrc)
1684 ereport(ERROR,
1686 errmsg("unnamed prepared statement does not exist")));
1687 }
1688
1689 /*
1690 * Report query to various monitoring facilities.
1691 */
1692 debug_query_string = psrc->query_string;
1693
1695
1696 foreach(lc, psrc->query_list)
1697 {
1698 Query *query = lfirst_node(Query, lc);
1699
1700 if (query->queryId != INT64CONST(0))
1701 {
1702 pgstat_report_query_id(query->queryId, false);
1703 break;
1704 }
1705 }
1706
1707 set_ps_display("BIND");
1708
1710 ResetUsage();
1711
1712 /*
1713 * Start up a transaction command so we can call functions etc. (Note that
1714 * this will normally change current memory context.) Nothing happens if
1715 * we are already in one. This also arms the statement timeout if
1716 * necessary.
1717 */
1719
1720 /* Switch back to message context */
1722
1723 /* Get the parameter format codes */
1725 if (numPFormats > 0)
1726 {
1728 for (int i = 0; i < numPFormats; i++)
1730 }
1731
1732 /* Get the parameter value count */
1733 numParams = pq_getmsgint(input_message, 2);
1734
1735 if (numPFormats > 1 && numPFormats != numParams)
1736 ereport(ERROR,
1738 errmsg("bind message has %d parameter formats but %d parameters",
1739 numPFormats, numParams)));
1740
1741 if (numParams != psrc->num_params)
1742 ereport(ERROR,
1744 errmsg("bind message supplies %d parameters, but prepared statement \"%s\" requires %d",
1745 numParams, stmt_name, psrc->num_params)));
1746
1747 /*
1748 * If we are in aborted transaction state, the only portals we can
1749 * actually run are those containing COMMIT or ROLLBACK commands. We
1750 * disallow binding anything else to avoid problems with infrastructure
1751 * that expects to run inside a valid transaction. We also disallow
1752 * binding any parameters, since we can't risk calling user-defined I/O
1753 * functions.
1754 */
1756 (!(psrc->raw_parse_tree &&
1757 IsTransactionExitStmt(psrc->raw_parse_tree->stmt)) ||
1758 numParams != 0))
1759 ereport(ERROR,
1761 errmsg("current transaction is aborted, "
1762 "commands ignored until end of transaction block")));
1763
1764 /*
1765 * Create the portal. Allow silent replacement of an existing portal only
1766 * if the unnamed portal is specified.
1767 */
1768 if (portal_name[0] == '\0')
1769 portal = CreatePortal(portal_name, true, true);
1770 else
1771 portal = CreatePortal(portal_name, false, false);
1772
1773 /*
1774 * Prepare to copy stuff into the portal's memory context. We do all this
1775 * copying first, because it could possibly fail (out-of-memory) and we
1776 * don't want a failure to occur between GetCachedPlan and
1777 * PortalDefineQuery; that would result in leaking our plancache refcount.
1778 */
1780
1781 /* Copy the plan's query string into the portal */
1782 query_string = pstrdup(psrc->query_string);
1783
1784 /* Likewise make a copy of the statement name, unless it's unnamed */
1785 if (stmt_name[0])
1786 saved_stmt_name = pstrdup(stmt_name);
1787 else
1789
1790 /*
1791 * Set a snapshot if we have parameters to fetch (since the input
1792 * functions might need it) or the query isn't a utility command (and
1793 * hence could require redoing parse analysis and planning). We keep the
1794 * snapshot active till we're done, so that plancache.c doesn't have to
1795 * take new ones.
1796 */
1797 if (numParams > 0 ||
1798 (psrc->raw_parse_tree &&
1799 analyze_requires_snapshot(psrc->raw_parse_tree)))
1800 {
1802 snapshot_set = true;
1803 }
1804
1805 /*
1806 * Fetch parameters, if any, and store in the portal's memory context.
1807 */
1808 if (numParams > 0)
1809 {
1810 char **knownTextValues = NULL; /* allocate on first use */
1812
1813 /*
1814 * Set up an error callback so that if there's an error in this phase,
1815 * we can report the specific parameter causing the problem.
1816 */
1817 one_param_data.portalName = portal->name;
1818 one_param_data.paramno = -1;
1819 one_param_data.paramval = NULL;
1824
1825 params = makeParamList(numParams);
1826
1827 for (int paramno = 0; paramno < numParams; paramno++)
1828 {
1829 Oid ptype = psrc->param_types[paramno];
1830 int32 plength;
1831 Datum pval;
1832 bool isNull;
1834 char csave;
1835 int16 pformat;
1836
1837 one_param_data.paramno = paramno;
1838 one_param_data.paramval = NULL;
1839
1841 isNull = (plength == -1);
1842
1843 if (!isNull)
1844 {
1845 char *pvalue;
1846
1847 /*
1848 * Rather than copying data around, we just initialize a
1849 * StringInfo pointing to the correct portion of the message
1850 * buffer. We assume we can scribble on the message buffer to
1851 * add a trailing NUL which is required for the input function
1852 * call.
1853 */
1855 csave = pvalue[plength];
1856 pvalue[plength] = '\0';
1858 }
1859 else
1860 {
1861 pbuf.data = NULL; /* keep compiler quiet */
1862 csave = 0;
1863 }
1864
1865 if (numPFormats > 1)
1866 pformat = pformats[paramno];
1867 else if (numPFormats > 0)
1868 pformat = pformats[0];
1869 else
1870 pformat = 0; /* default = text */
1871
1872 if (pformat == 0) /* text mode */
1873 {
1874 Oid typinput;
1875 Oid typioparam;
1876 char *pstring;
1877
1878 getTypeInputInfo(ptype, &typinput, &typioparam);
1879
1880 /*
1881 * We have to do encoding conversion before calling the
1882 * typinput routine.
1883 */
1884 if (isNull)
1885 pstring = NULL;
1886 else
1888
1889 /* Now we can log the input string in case of error */
1890 one_param_data.paramval = pstring;
1891
1892 pval = OidInputFunctionCall(typinput, pstring, typioparam, -1);
1893
1894 one_param_data.paramval = NULL;
1895
1896 /*
1897 * If we might need to log parameters later, save a copy of
1898 * the converted string in MessageContext; then free the
1899 * result of encoding conversion, if any was done.
1900 */
1901 if (pstring)
1902 {
1904 {
1906
1908
1909 if (knownTextValues == NULL)
1910 knownTextValues = palloc0_array(char *, numParams);
1911
1913 knownTextValues[paramno] = pstrdup(pstring);
1914 else
1915 {
1916 /*
1917 * We can trim the saved string, knowing that we
1918 * won't print all of it. But we must copy at
1919 * least two more full characters than
1920 * BuildParamLogString wants to use; otherwise it
1921 * might fail to include the trailing ellipsis.
1922 */
1923 knownTextValues[paramno] =
1927 }
1928
1930 }
1931 if (pstring != pbuf.data)
1932 pfree(pstring);
1933 }
1934 }
1935 else if (pformat == 1) /* binary mode */
1936 {
1937 Oid typreceive;
1938 Oid typioparam;
1939 StringInfo bufptr;
1940
1941 /*
1942 * Call the parameter type's binary input converter
1943 */
1944 getTypeBinaryInputInfo(ptype, &typreceive, &typioparam);
1945
1946 if (isNull)
1947 bufptr = NULL;
1948 else
1949 bufptr = &pbuf;
1950
1951 pval = OidReceiveFunctionCall(typreceive, bufptr, typioparam, -1);
1952
1953 /* Trouble if it didn't eat the whole buffer */
1954 if (!isNull && pbuf.cursor != pbuf.len)
1955 ereport(ERROR,
1957 errmsg("incorrect binary data format in bind parameter %d",
1958 paramno + 1)));
1959 }
1960 else
1961 {
1962 ereport(ERROR,
1964 errmsg("unsupported format code: %d",
1965 pformat)));
1966 pval = 0; /* keep compiler quiet */
1967 }
1968
1969 /* Restore message buffer contents */
1970 if (!isNull)
1971 pbuf.data[plength] = csave;
1972
1973 params->params[paramno].value = pval;
1974 params->params[paramno].isnull = isNull;
1975
1976 /*
1977 * We mark the params as CONST. This ensures that any custom plan
1978 * makes full use of the parameter values.
1979 */
1980 params->params[paramno].pflags = PARAM_FLAG_CONST;
1981 params->params[paramno].ptype = ptype;
1982 }
1983
1984 /* Pop the per-parameter error callback */
1986
1987 /*
1988 * Once all parameters have been received, prepare for printing them
1989 * in future errors, if configured to do so. (This is saved in the
1990 * portal, so that they'll appear when the query is executed later.)
1991 */
1993 params->paramValuesStr =
1994 BuildParamLogString(params,
1997 }
1998 else
1999 params = NULL;
2000
2001 /* Done storing stuff in portal's context */
2003
2004 /*
2005 * Set up another error callback so that all the parameters are logged if
2006 * we get an error during the rest of the BIND processing.
2007 */
2008 params_data.portalName = portal->name;
2009 params_data.params = params;
2014
2015 /* Get the result format codes */
2017 if (numRFormats > 0)
2018 {
2020 for (int i = 0; i < numRFormats; i++)
2022 }
2023
2025
2026 /*
2027 * Obtain a plan from the CachedPlanSource. Any cruft from (re)planning
2028 * will be generated in MessageContext. The plan refcount will be
2029 * assigned to the Portal, so it will be released at portal destruction.
2030 */
2031 cplan = GetCachedPlan(psrc, params, NULL, NULL);
2032
2033 /*
2034 * Now we can define the portal.
2035 *
2036 * DO NOT put any code that could possibly throw an error between the
2037 * above GetCachedPlan call and here.
2038 */
2039 PortalDefineQuery(portal,
2041 query_string,
2043 cplan->stmt_list,
2044 cplan);
2045
2046 /* Portal is defined, set the plan ID based on its contents. */
2047 foreach(lc, portal->stmts)
2048 {
2050
2051 if (plan->planId != INT64CONST(0))
2052 {
2053 pgstat_report_plan_id(plan->planId, false);
2054 break;
2055 }
2056 }
2057
2058 /* Done with the snapshot used for parameter I/O and parsing/planning */
2059 if (snapshot_set)
2061
2062 /*
2063 * And we're ready to start portal execution.
2064 */
2065 PortalStart(portal, params, 0, InvalidSnapshot);
2066
2067 /*
2068 * Apply the result format requests to the portal.
2069 */
2071
2072 /*
2073 * Done binding; remove the parameters error callback. Entries emitted
2074 * later determine independently whether to log the parameters or not.
2075 */
2077
2078 /*
2079 * Send BindComplete.
2080 */
2083
2084 /*
2085 * Emit duration logging if appropriate.
2086 */
2087 switch (check_log_duration(msec_str, false))
2088 {
2089 case 1:
2090 ereport(LOG,
2091 (errmsg("duration: %s ms", msec_str),
2092 errhidestmt(true)));
2093 break;
2094 case 2:
2095 ereport(LOG,
2096 (errmsg("duration: %s ms bind %s%s%s: %s",
2097 msec_str,
2098 *stmt_name ? stmt_name : "<unnamed>",
2099 *portal_name ? "/" : "",
2100 *portal_name ? portal_name : "",
2101 psrc->query_string),
2102 errhidestmt(true),
2103 errdetail_params(params)));
2104 break;
2105 }
2106
2108 ShowUsage("BIND MESSAGE STATISTICS");
2109
2111
2113}
2114
2115/*
2116 * exec_execute_message
2117 *
2118 * Process an "Execute" message for a portal
2119 */
2120static void
2122{
2123 CommandDest dest;
2125 Portal portal;
2126 bool completed;
2127 QueryCompletion qc;
2128 const char *sourceText;
2129 const char *prepStmtName;
2130 ParamListInfo portalParams;
2132 bool is_xact_command;
2133 bool execute_is_fetch;
2134 bool was_logged = false;
2135 char msec_str[32];
2138 const char *cmdtagname;
2139 size_t cmdtaglen;
2140 ListCell *lc;
2141
2142 /* Adjust destination to tell printtup.c what to do */
2143 dest = whereToSendOutput;
2144 if (dest == DestRemote)
2145 dest = DestRemoteExecute;
2146
2147 portal = GetPortalByName(portal_name);
2148 if (!PortalIsValid(portal))
2149 ereport(ERROR,
2151 errmsg("portal \"%s\" does not exist", portal_name)));
2152
2153 /*
2154 * If the original query was a null string, just return
2155 * EmptyQueryResponse.
2156 */
2157 if (portal->commandTag == CMDTAG_UNKNOWN)
2158 {
2159 Assert(portal->stmts == NIL);
2160 NullCommand(dest);
2161 return;
2162 }
2163
2164 /* Does the portal contain a transaction command? */
2166
2167 /*
2168 * We must copy the sourceText and prepStmtName into MessageContext in
2169 * case the portal is destroyed during finish_xact_command. We do not
2170 * make a copy of the portalParams though, preferring to just not print
2171 * them in that case.
2172 */
2173 sourceText = pstrdup(portal->sourceText);
2174 if (portal->prepStmtName)
2175 prepStmtName = pstrdup(portal->prepStmtName);
2176 else
2177 prepStmtName = "<unnamed>";
2178 portalParams = portal->portalParams;
2179
2180 /*
2181 * Report query to various monitoring facilities.
2182 */
2183 debug_query_string = sourceText;
2184
2186
2187 foreach(lc, portal->stmts)
2188 {
2190
2191 if (stmt->queryId != INT64CONST(0))
2192 {
2193 pgstat_report_query_id(stmt->queryId, false);
2194 break;
2195 }
2196 }
2197
2198 foreach(lc, portal->stmts)
2199 {
2201
2202 if (stmt->planId != INT64CONST(0))
2203 {
2204 pgstat_report_plan_id(stmt->planId, false);
2205 break;
2206 }
2207 }
2208
2210
2212
2214 ResetUsage();
2215
2216 BeginCommand(portal->commandTag, dest);
2217
2218 /*
2219 * Create dest receiver in MessageContext (we don't want it in transaction
2220 * context, because that may get deleted if portal contains VACUUM).
2221 */
2223 if (dest == DestRemoteExecute)
2225
2226 /*
2227 * Ensure we are in a transaction command (this should normally be the
2228 * case already due to prior BIND).
2229 */
2231
2232 /*
2233 * If we re-issue an Execute protocol request against an existing portal,
2234 * then we are only fetching more rows rather than completely re-executing
2235 * the query from the start. atStart is never reset for a v3 portal, so we
2236 * are safe to use this check.
2237 */
2238 execute_is_fetch = !portal->atStart;
2239
2240 /* Log immediately if dictated by log_statement */
2241 if (check_log_statement(portal->stmts))
2242 {
2243 ereport(LOG,
2244 (errmsg("%s %s%s%s: %s",
2246 _("execute fetch from") :
2247 _("execute"),
2248 prepStmtName,
2249 *portal_name ? "/" : "",
2250 *portal_name ? portal_name : "",
2251 sourceText),
2252 errhidestmt(true),
2253 errdetail_params(portalParams)));
2254 was_logged = true;
2255 }
2256
2257 /*
2258 * If we are in aborted transaction state, the only portals we can
2259 * actually run are those containing COMMIT or ROLLBACK commands.
2260 */
2263 ereport(ERROR,
2265 errmsg("current transaction is aborted, "
2266 "commands ignored until end of transaction block")));
2267
2268 /* Check for cancel signal before we start execution */
2270
2271 /*
2272 * Okay to run the portal. Set the error callback so that parameters are
2273 * logged. The parameters must have been saved during the bind phase.
2274 */
2275 params_data.portalName = portal->name;
2276 params_data.params = portalParams;
2281
2282 if (max_rows <= 0)
2284
2285 completed = PortalRun(portal,
2286 max_rows,
2287 true, /* always top level */
2288 receiver,
2289 receiver,
2290 &qc);
2291
2292 receiver->rDestroy(receiver);
2293
2294 /* Done executing; remove the params error callback */
2296
2297 if (completed)
2298 {
2300 {
2301 /*
2302 * If this was a transaction control statement, commit it. We
2303 * will start a new xact command for the next command (if any).
2304 * Likewise if the statement required immediate commit. Without
2305 * this provision, we wouldn't force commit until Sync is
2306 * received, which creates a hazard if the client tries to
2307 * pipeline immediate-commit statements.
2308 */
2310
2311 /*
2312 * These commands typically don't have any parameters, and even if
2313 * one did we couldn't print them now because the storage went
2314 * away during finish_xact_command. So pretend there were none.
2315 */
2316 portalParams = NULL;
2317 }
2318 else
2319 {
2320 /*
2321 * We need a CommandCounterIncrement after every query, except
2322 * those that start or end a transaction block.
2323 */
2325
2326 /*
2327 * Set XACT_FLAGS_PIPELINING whenever we complete an Execute
2328 * message without immediately committing the transaction.
2329 */
2331
2332 /*
2333 * Disable statement timeout whenever we complete an Execute
2334 * message. The next protocol message will start a fresh timeout.
2335 */
2337 }
2338
2339 /* Send appropriate CommandComplete to client */
2340 EndCommand(&qc, dest, false);
2341 }
2342 else
2343 {
2344 /* Portal run not complete, so send PortalSuspended */
2347
2348 /*
2349 * Set XACT_FLAGS_PIPELINING whenever we suspend an Execute message,
2350 * too.
2351 */
2353 }
2354
2355 /*
2356 * Emit duration logging if appropriate.
2357 */
2359 {
2360 case 1:
2361 ereport(LOG,
2362 (errmsg("duration: %s ms", msec_str),
2363 errhidestmt(true)));
2364 break;
2365 case 2:
2366 ereport(LOG,
2367 (errmsg("duration: %s ms %s %s%s%s: %s",
2368 msec_str,
2370 _("execute fetch from") :
2371 _("execute"),
2372 prepStmtName,
2373 *portal_name ? "/" : "",
2374 *portal_name ? portal_name : "",
2375 sourceText),
2376 errhidestmt(true),
2377 errdetail_params(portalParams)));
2378 break;
2379 }
2380
2382 ShowUsage("EXECUTE MESSAGE STATISTICS");
2383
2385
2387}
2388
2389/*
2390 * check_log_statement
2391 * Determine whether command should be logged because of log_statement
2392 *
2393 * stmt_list can be either raw grammar output or a list of planned
2394 * statements
2395 */
2396static bool
2398{
2400
2402 return false;
2404 return true;
2405
2406 /* Else we have to inspect the statement(s) to see whether to log */
2407 foreach(stmt_item, stmt_list)
2408 {
2409 Node *stmt = (Node *) lfirst(stmt_item);
2410
2412 return true;
2413 }
2414
2415 return false;
2416}
2417
2418/*
2419 * check_log_duration
2420 * Determine whether current command's duration should be logged
2421 * We also check if this statement in this transaction must be logged
2422 * (regardless of its duration).
2423 *
2424 * Returns:
2425 * 0 if no logging is needed
2426 * 1 if just the duration should be logged
2427 * 2 if duration and query details should be logged
2428 *
2429 * If logging is needed, the duration in msec is formatted into msec_str[],
2430 * which must be a 32-byte buffer.
2431 *
2432 * was_logged should be true if caller already logged query details (this
2433 * essentially prevents 2 from being returned).
2434 */
2435int
2437{
2440 {
2441 long secs;
2442 int usecs;
2443 int msecs;
2444 bool exceeded_duration;
2446 bool in_sample = false;
2447
2450 &secs, &usecs);
2451 msecs = usecs / 1000;
2452
2453 /*
2454 * This odd-looking test for log_min_duration_* being exceeded is
2455 * designed to avoid integer overflow with very long durations: don't
2456 * compute secs * 1000 until we've verified it will fit in int.
2457 */
2460 (secs > log_min_duration_statement / 1000 ||
2461 secs * 1000 + msecs >= log_min_duration_statement)));
2462
2465 (secs > log_min_duration_sample / 1000 ||
2466 secs * 1000 + msecs >= log_min_duration_sample)));
2467
2468 /*
2469 * Do not log if log_statement_sample_rate = 0. Log a sample if
2470 * log_statement_sample_rate <= 1 and avoid unnecessary PRNG call if
2471 * log_statement_sample_rate = 1.
2472 */
2477
2479 {
2480 snprintf(msec_str, 32, "%ld.%03d",
2481 secs * 1000 + msecs, usecs % 1000);
2483 return 2;
2484 else
2485 return 1;
2486 }
2487 }
2488
2489 return 0;
2490}
2491
2492/*
2493 * errdetail_execute
2494 *
2495 * Add an errdetail() line showing the query referenced by an EXECUTE, if any.
2496 * The argument is the raw parsetree list.
2497 */
2498static int
2500{
2502
2504 {
2506
2507 if (IsA(parsetree->stmt, ExecuteStmt))
2508 {
2509 ExecuteStmt *stmt = (ExecuteStmt *) parsetree->stmt;
2510 PreparedStatement *pstmt;
2511
2512 pstmt = FetchPreparedStatement(stmt->name, false);
2513 if (pstmt)
2514 {
2515 errdetail("prepare: %s", pstmt->plansource->query_string);
2516 return 0;
2517 }
2518 }
2519 }
2520
2521 return 0;
2522}
2523
2524/*
2525 * errdetail_params
2526 *
2527 * Add an errdetail() line showing bind-parameter data, if available.
2528 * Note that this is only used for statement logging, so it is controlled
2529 * by log_parameter_max_length not log_parameter_max_length_on_error.
2530 */
2531static int
2533{
2534 if (params && params->numParams > 0 && log_parameter_max_length != 0)
2535 {
2536 char *str;
2537
2539 if (str && str[0] != '\0')
2540 errdetail("Parameters: %s", str);
2541 }
2542
2543 return 0;
2544}
2545
2546/*
2547 * errdetail_recovery_conflict
2548 *
2549 * Add an errdetail() line showing conflict source.
2550 */
2551static int
2553{
2554 switch (reason)
2555 {
2557 errdetail("User was holding shared buffer pin for too long.");
2558 break;
2560 errdetail("User was holding a relation lock for too long.");
2561 break;
2563 errdetail("User was or might have been using tablespace that must be dropped.");
2564 break;
2566 errdetail("User query might have needed to see row versions that must be removed.");
2567 break;
2569 errdetail("User was using a logical replication slot that must be invalidated.");
2570 break;
2572 errdetail("User transaction caused deadlock with recovery.");
2573 break;
2575 errdetail("User transaction caused buffer deadlock with recovery.");
2576 break;
2578 errdetail("User was connected to a database that must be dropped.");
2579 break;
2580 }
2581
2582 return 0;
2583}
2584
2585/*
2586 * bind_param_error_callback
2587 *
2588 * Error context callback used while parsing parameters in a Bind message
2589 */
2590static void
2592{
2595 char *quotedval;
2596
2597 if (data->paramno < 0)
2598 return;
2599
2600 /* If we have a textual value, quote it, and trim if necessary */
2601 if (data->paramval)
2602 {
2606 quotedval = buf.data;
2607 }
2608 else
2609 quotedval = NULL;
2610
2611 if (data->portalName && data->portalName[0] != '\0')
2612 {
2613 if (quotedval)
2614 errcontext("portal \"%s\" parameter $%d = %s",
2615 data->portalName, data->paramno + 1, quotedval);
2616 else
2617 errcontext("portal \"%s\" parameter $%d",
2618 data->portalName, data->paramno + 1);
2619 }
2620 else
2621 {
2622 if (quotedval)
2623 errcontext("unnamed portal parameter $%d = %s",
2624 data->paramno + 1, quotedval);
2625 else
2626 errcontext("unnamed portal parameter $%d",
2627 data->paramno + 1);
2628 }
2629
2630 if (quotedval)
2632}
2633
2634/*
2635 * exec_describe_statement_message
2636 *
2637 * Process a "Describe" message for a prepared statement
2638 */
2639static void
2641{
2643
2644 /*
2645 * Start up a transaction command. (Note that this will normally change
2646 * current memory context.) Nothing happens if we are already in one.
2647 */
2649
2650 /* Switch back to message context */
2652
2653 /* Find prepared statement */
2654 if (stmt_name[0] != '\0')
2655 {
2656 PreparedStatement *pstmt;
2657
2658 pstmt = FetchPreparedStatement(stmt_name, true);
2659 psrc = pstmt->plansource;
2660 }
2661 else
2662 {
2663 /* special-case the unnamed statement */
2665 if (!psrc)
2666 ereport(ERROR,
2668 errmsg("unnamed prepared statement does not exist")));
2669 }
2670
2671 /* Prepared statements shouldn't have changeable result descs */
2672 Assert(psrc->fixed_result);
2673
2674 /*
2675 * If we are in aborted transaction state, we can't run
2676 * SendRowDescriptionMessage(), because that needs catalog accesses.
2677 * Hence, refuse to Describe statements that return data. (We shouldn't
2678 * just refuse all Describes, since that might break the ability of some
2679 * clients to issue COMMIT or ROLLBACK commands, if they use code that
2680 * blindly Describes whatever it does.) We can Describe parameters
2681 * without doing anything dangerous, so we don't restrict that.
2682 */
2684 psrc->resultDesc)
2685 ereport(ERROR,
2687 errmsg("current transaction is aborted, "
2688 "commands ignored until end of transaction block")));
2689
2691 return; /* can't actually do anything... */
2692
2693 /*
2694 * First describe the parameters...
2695 */
2697 pq_sendint16(&row_description_buf, psrc->num_params);
2698
2699 for (int i = 0; i < psrc->num_params; i++)
2700 {
2701 Oid ptype = psrc->param_types[i];
2702
2703 pq_sendint32(&row_description_buf, (int) ptype);
2704 }
2706
2707 /*
2708 * Next send RowDescription or NoData to describe the result...
2709 */
2710 if (psrc->resultDesc)
2711 {
2712 List *tlist;
2713
2714 /* Get the plan's primary targetlist */
2716
2718 psrc->resultDesc,
2719 tlist,
2720 NULL);
2721 }
2722 else
2724}
2725
2726/*
2727 * exec_describe_portal_message
2728 *
2729 * Process a "Describe" message for a portal
2730 */
2731static void
2733{
2734 Portal portal;
2735
2736 /*
2737 * Start up a transaction command. (Note that this will normally change
2738 * current memory context.) Nothing happens if we are already in one.
2739 */
2741
2742 /* Switch back to message context */
2744
2745 portal = GetPortalByName(portal_name);
2746 if (!PortalIsValid(portal))
2747 ereport(ERROR,
2749 errmsg("portal \"%s\" does not exist", portal_name)));
2750
2751 /*
2752 * If we are in aborted transaction state, we can't run
2753 * SendRowDescriptionMessage(), because that needs catalog accesses.
2754 * Hence, refuse to Describe portals that return data. (We shouldn't just
2755 * refuse all Describes, since that might break the ability of some
2756 * clients to issue COMMIT or ROLLBACK commands, if they use code that
2757 * blindly Describes whatever it does.)
2758 */
2760 portal->tupDesc)
2761 ereport(ERROR,
2763 errmsg("current transaction is aborted, "
2764 "commands ignored until end of transaction block")));
2765
2767 return; /* can't actually do anything... */
2768
2769 if (portal->tupDesc)
2771 portal->tupDesc,
2772 FetchPortalTargetList(portal),
2773 portal->formats);
2774 else
2776}
2777
2778
2779/*
2780 * Convenience routines for starting/committing a single command.
2781 */
2782static void
2784{
2785 if (!xact_started)
2786 {
2788
2789 xact_started = true;
2790 }
2792 {
2793 /*
2794 * When the first Execute message is completed, following commands
2795 * will be done in an implicit transaction block created via
2796 * pipelining. The transaction state needs to be updated to an
2797 * implicit block if we're not already in a transaction block (like
2798 * one started by an explicit BEGIN).
2799 */
2801 }
2802
2803 /*
2804 * Start statement timeout if necessary. Note that this'll intentionally
2805 * not reset the clock on an already started timeout, to avoid the timing
2806 * overhead when start_xact_command() is invoked repeatedly, without an
2807 * interceding finish_xact_command() (e.g. parse/bind/execute). If that's
2808 * not desired, the timeout has to be disabled explicitly.
2809 */
2811
2812 /* Start timeout for checking if the client has gone away if necessary. */
2815 MyProcPort &&
2819}
2820
2821static void
2823{
2824 /* cancel active statement timeout after each command */
2826
2827 if (xact_started)
2828 {
2830
2831#ifdef MEMORY_CONTEXT_CHECKING
2832 /* Check all memory contexts that weren't freed during commit */
2833 /* (those that were, were checked before being deleted) */
2835#endif
2836
2837#ifdef SHOW_MEMORY_STATS
2838 /* Print mem stats after each commit for leak tracking */
2840#endif
2841
2842 xact_started = false;
2843 }
2844}
2845
2846
2847/*
2848 * Convenience routines for checking whether a statement is one of the
2849 * ones that we allow in transaction-aborted state.
2850 */
2851
2852/* Test a bare parsetree */
2853static bool
2855{
2856 if (parsetree && IsA(parsetree, TransactionStmt))
2857 {
2858 TransactionStmt *stmt = (TransactionStmt *) parsetree;
2859
2860 if (stmt->kind == TRANS_STMT_COMMIT ||
2861 stmt->kind == TRANS_STMT_PREPARE ||
2862 stmt->kind == TRANS_STMT_ROLLBACK ||
2864 return true;
2865 }
2866 return false;
2867}
2868
2869/* Test a list that contains PlannedStmt nodes */
2870static bool
2872{
2873 if (list_length(pstmts) == 1)
2874 {
2876
2877 if (pstmt->commandType == CMD_UTILITY &&
2879 return true;
2880 }
2881 return false;
2882}
2883
2884/* Test a list that contains PlannedStmt nodes */
2885static bool
2887{
2888 if (list_length(pstmts) == 1)
2889 {
2891
2892 if (pstmt->commandType == CMD_UTILITY &&
2894 return true;
2895 }
2896 return false;
2897}
2898
2899/* Release any existing unnamed prepared statement */
2900static void
2902{
2903 /* paranoia to avoid a dangling pointer in case of error */
2905 {
2907
2910 }
2911}
2912
2913
2914/* --------------------------------
2915 * signal handler routines used in PostgresMain()
2916 * --------------------------------
2917 */
2918
2919/*
2920 * quickdie() occurs when signaled SIGQUIT by the postmaster.
2921 *
2922 * Either some backend has bought the farm, or we've been told to shut down
2923 * "immediately"; so we need to stop what we're doing and exit.
2924 */
2925void
2927{
2928 sigaddset(&BlockSig, SIGQUIT); /* prevent nested calls */
2930
2931 /*
2932 * Prevent interrupts while exiting; though we just blocked signals that
2933 * would queue new interrupts, one may have been pending. We don't want a
2934 * quickdie() downgraded to a mere query cancel.
2935 */
2937
2938 /*
2939 * If we're aborting out of client auth, don't risk trying to send
2940 * anything to the client; we will likely violate the protocol, not to
2941 * mention that we may have interrupted the guts of OpenSSL or some
2942 * authentication library.
2943 */
2946
2947 /*
2948 * Notify the client before exiting, to give a clue on what happened.
2949 *
2950 * It's dubious to call ereport() from a signal handler. It is certainly
2951 * not async-signal safe. But it seems better to try, than to disconnect
2952 * abruptly and leave the client wondering what happened. It's remotely
2953 * possible that we crash or hang while trying to send the message, but
2954 * receiving a SIGQUIT is a sign that something has already gone badly
2955 * wrong, so there's not much to lose. Assuming the postmaster is still
2956 * running, it will SIGKILL us soon if we get stuck for some reason.
2957 *
2958 * One thing we can do to make this a tad safer is to clear the error
2959 * context stack, so that context callbacks are not called. That's a lot
2960 * less code that could be reached here, and the context info is unlikely
2961 * to be very relevant to a SIGQUIT report anyway.
2962 */
2964
2965 /*
2966 * When responding to a postmaster-issued signal, we send the message only
2967 * to the client; sending to the server log just creates log spam, plus
2968 * it's more code that we need to hope will work in a signal handler.
2969 *
2970 * Ideally these should be ereport(FATAL), but then we'd not get control
2971 * back to force the correct type of process exit.
2972 */
2973 switch (GetQuitSignalReason())
2974 {
2975 case PMQUIT_NOT_SENT:
2976 /* Hmm, SIGQUIT arrived out of the blue */
2979 errmsg("terminating connection because of unexpected SIGQUIT signal")));
2980 break;
2981 case PMQUIT_FOR_CRASH:
2982 /* A crash-and-restart cycle is in progress */
2985 errmsg("terminating connection because of crash of another server process"),
2986 errdetail("The postmaster has commanded this server process to roll back"
2987 " the current transaction and exit, because another"
2988 " server process exited abnormally and possibly corrupted"
2989 " shared memory."),
2990 errhint("In a moment you should be able to reconnect to the"
2991 " database and repeat your command.")));
2992 break;
2993 case PMQUIT_FOR_STOP:
2994 /* Immediate-mode stop */
2997 errmsg("terminating connection due to immediate shutdown command")));
2998 break;
2999 }
3000
3001 /*
3002 * We DO NOT want to run proc_exit() or atexit() callbacks -- we're here
3003 * because shared memory may be corrupted, so we don't want to try to
3004 * clean up our transaction. Just nail the windows shut and get out of
3005 * town. The callbacks wouldn't be safe to run from a signal handler,
3006 * anyway.
3007 *
3008 * Note we do _exit(2) not _exit(0). This is to force the postmaster into
3009 * a system reset cycle if someone sends a manual SIGQUIT to a random
3010 * backend. This is necessary precisely because we don't clean up our
3011 * shared memory state. (The "dead man switch" mechanism in pmsignal.c
3012 * should ensure the postmaster sees this as a crash, too, but no harm in
3013 * being doubly sure.)
3014 */
3015 _exit(2);
3016}
3017
3018/*
3019 * Shutdown signal from postmaster: abort transaction and exit
3020 * at soonest convenient time
3021 */
3022void
3024{
3025 /* Don't joggle the elbow of proc_exit */
3027 {
3028 InterruptPending = true;
3029 ProcDiePending = true;
3030 }
3031
3032 /* for the cumulative stats system */
3034
3035 /* If we're still here, waken anything waiting on the process latch */
3037
3038 /*
3039 * If we're in single user mode, we want to quit immediately - we can't
3040 * rely on latches as they wouldn't work when stdin/stdout is a file.
3041 * Rather ugly, but it's unlikely to be worthwhile to invest much more
3042 * effort just for the benefit of single user mode.
3043 */
3046}
3047
3048/*
3049 * Query-cancel signal from postmaster: abort current transaction
3050 * at soonest convenient time
3051 */
3052void
3054{
3055 /*
3056 * Don't joggle the elbow of proc_exit
3057 */
3059 {
3060 InterruptPending = true;
3061 QueryCancelPending = true;
3062 }
3063
3064 /* If we're still here, waken anything waiting on the process latch */
3066}
3067
3068/* signal handler for floating point exception */
3069void
3071{
3072 /* We're not returning, so no need to save errno */
3073 ereport(ERROR,
3075 errmsg("floating-point exception"),
3076 errdetail("An invalid floating-point operation was signaled. "
3077 "This probably means an out-of-range result or an "
3078 "invalid operation, such as division by zero.")));
3079}
3080
3081/*
3082 * Tell the next CHECK_FOR_INTERRUPTS() to process recovery conflicts. Runs
3083 * in a SIGUSR1 handler.
3084 */
3085void
3087{
3089 InterruptPending = true;
3090 /* latch will be set by procsignal_sigusr1_handler */
3091}
3092
3093/*
3094 * Check one individual conflict reason.
3095 */
3096static void
3098{
3099 switch (reason)
3100 {
3102
3103 /*
3104 * The startup process is waiting on a lock held by us, and has
3105 * requested us to check if it is a deadlock (i.e. the deadlock
3106 * timeout expired).
3107 *
3108 * If we aren't waiting for a lock we can never deadlock.
3109 */
3110 if (GetAwaitedLock() == NULL)
3111 return;
3112
3113 /* Set the flag so that ProcSleep() will check for deadlocks. */
3115 return;
3116
3118
3119 /*
3120 * The startup process is waiting on a buffer pin, and has
3121 * requested us to check if there is a deadlock involving the pin.
3122 *
3123 * If we're not waiting on a lock, there can be no deadlock.
3124 */
3125 if (GetAwaitedLock() == NULL)
3126 return;
3127
3128 /*
3129 * If we're not holding the buffer pin, also no deadlock. (The
3130 * startup process doesn't know who's holding the pin, and sends
3131 * this signal to *all* backends, so this is the common case.)
3132 */
3134 return;
3135
3136 /*
3137 * Otherwise, we probably have a deadlock. Unfortunately the
3138 * normal deadlock detector doesn't know about buffer pins, so we
3139 * cannot perform comprehensively deadlock check. Instead, we
3140 * just assume that it is a deadlock if the above two conditions
3141 * are met. In principle this can lead to false positives, but
3142 * it's rare in practice because sessions in a hot standby server
3143 * rarely hold locks that can block other backends.
3144 */
3146 return;
3147
3149
3150 /*
3151 * Someone is holding a buffer pin that the startup process is
3152 * waiting for, and it got tired of waiting. If that's us, error
3153 * out to release the pin.
3154 */
3156 return;
3157
3159 return;
3160
3164
3165 /*
3166 * If we aren't in a transaction any longer then ignore.
3167 */
3169 return;
3170
3172 return;
3173
3176 return;
3177
3179
3180 /* The database is being dropped; terminate the session */
3182 return;
3183 }
3184 elog(FATAL, "unrecognized conflict mode: %d", (int) reason);
3185}
3186
3187/*
3188 * This transaction or session is conflicting with recovery and needs to be
3189 * killed. Roll back the transaction, if that's sufficient, or terminate the
3190 * connection, or do nothing if we're already in an aborted state.
3191 */
3192static void
3194{
3195 bool fatal;
3196
3197 if (reason == RECOVERY_CONFLICT_DATABASE)
3198 {
3199 /* note: no hint about reconnecting, and different errcode */
3201 ereport(FATAL,
3203 errmsg("terminating connection due to conflict with recovery"),
3205 }
3206 if (reason == RECOVERY_CONFLICT_LOGICALSLOT)
3207 {
3208 /*
3209 * RECOVERY_CONFLICT_LOGICALSLOT is a special case that always throws
3210 * an ERROR (ie never promotes to FATAL), though it still has to
3211 * respect QueryCancelHoldoffCount, so it shares this code path.
3212 * Logical decoding slots are only acquired while performing logical
3213 * decoding. During logical decoding no user controlled code is run.
3214 * During [sub]transaction abort, the slot is released. Therefore
3215 * user controlled code cannot intercept an error before the
3216 * replication slot is released.
3217 */
3218 fatal = false;
3219 }
3220 else
3221 {
3223 }
3224
3225 /*
3226 * If we're not in a subtransaction then we are OK to throw an ERROR to
3227 * resolve the conflict.
3228 *
3229 * XXX other times that we can throw just an ERROR *may* be
3230 * RECOVERY_CONFLICT_LOCK if no locks are held in parent transactions
3231 *
3232 * RECOVERY_CONFLICT_SNAPSHOT if no snapshots are held by parent
3233 * transactions and the transaction is not transaction-snapshot mode
3234 *
3235 * RECOVERY_CONFLICT_TABLESPACE if no temp files or cursors open in parent
3236 * transactions
3237 */
3238 if (!fatal)
3239 {
3240 /*
3241 * If we already aborted then we no longer need to cancel. We do this
3242 * here since we do not wish to ignore aborted subtransactions, which
3243 * must cause FATAL, currently.
3244 */
3246 return;
3247
3248 /*
3249 * If a recovery conflict happens while we are waiting for input from
3250 * the client, the client is presumably just sitting idle in a
3251 * transaction, preventing recovery from making progress. We'll drop
3252 * through to the FATAL case below to dislodge it, in that case.
3253 */
3254 if (!DoingCommandRead)
3255 {
3256 /* Avoid losing sync in the FE/BE protocol. */
3257 if (QueryCancelHoldoffCount != 0)
3258 {
3259 /*
3260 * Re-arm and defer this interrupt until later. See similar
3261 * code in ProcessInterrupts().
3262 */
3264 InterruptPending = true;
3265 return;
3266 }
3267
3268 /*
3269 * We are cleared to throw an ERROR. Either it's the logical slot
3270 * case, or we have a top-level transaction that we can abort and
3271 * a conflict that isn't inherently non-retryable.
3272 */
3275 ereport(ERROR,
3277 errmsg("canceling statement due to conflict with recovery"),
3279 }
3280 }
3281
3282 /*
3283 * We couldn't resolve the conflict with ERROR, so terminate the whole
3284 * session.
3285 */
3287 ereport(FATAL,
3289 errmsg("terminating connection due to conflict with recovery"),
3291 errhint("In a moment you should be able to reconnect to the"
3292 " database and repeat your command.")));
3293}
3294
3295/*
3296 * Check each possible recovery conflict reason.
3297 */
3298static void
3300{
3301 uint32 pending;
3302
3303 /*
3304 * We don't need to worry about joggling the elbow of proc_exit, because
3305 * proc_exit_prepare() holds interrupts, so ProcessInterrupts() won't call
3306 * us.
3307 */
3310
3311 /* Are any recovery conflict pending? */
3313 if (pending == 0)
3314 return;
3315
3316 /*
3317 * Check the conflicts one by one, clearing each flag only before
3318 * processing the particular conflict. This ensures that if multiple
3319 * conflicts are pending, we come back here to process the remaining
3320 * conflicts, if an error is thrown during processing one of them.
3321 */
3322 for (RecoveryConflictReason reason = 0;
3324 reason++)
3325 {
3326 if ((pending & (1 << reason)) != 0)
3327 {
3328 /* clear the flag */
3330
3332 }
3333 }
3334}
3335
3336/*
3337 * ProcessInterrupts: out-of-line portion of CHECK_FOR_INTERRUPTS() macro
3338 *
3339 * If an interrupt condition is pending, and it's safe to service it,
3340 * then clear the flag and accept the interrupt. Called only when
3341 * InterruptPending is true.
3342 *
3343 * Note: if INTERRUPTS_CAN_BE_PROCESSED() is true, then ProcessInterrupts
3344 * is guaranteed to clear the InterruptPending flag before returning.
3345 * (This is not the same as guaranteeing that it's still clear when we
3346 * return; another interrupt could have arrived. But we promise that
3347 * any pre-existing one will have been serviced.)
3348 */
3349void
3351{
3352 /* OK to accept any interrupts now? */
3353 if (InterruptHoldoffCount != 0 || CritSectionCount != 0)
3354 return;
3355 InterruptPending = false;
3356
3357 if (ProcDiePending)
3358 {
3361
3362 ProcDiePending = false;
3363 ProcDieSenderPid = 0;
3364 ProcDieSenderUid = 0;
3365 QueryCancelPending = false; /* ProcDie trumps QueryCancel */
3367 /* As in quickdie, don't risk sending to client during auth */
3371 ereport(FATAL,
3373 errmsg("canceling authentication due to timeout")));
3374 else if (AmAutoVacuumWorkerProcess())
3375 ereport(FATAL,
3377 errmsg("terminating autovacuum process due to administrator command"),
3379 else if (IsLogicalWorker())
3380 ereport(FATAL,
3382 errmsg("terminating logical replication worker due to administrator command"),
3384 else if (IsLogicalLauncher())
3385 {
3387 (errmsg_internal("logical replication launcher shutting down"),
3389
3390 /*
3391 * The logical replication launcher can be stopped at any time.
3392 * Use exit status 1 so the background worker is restarted.
3393 */
3394 proc_exit(1);
3395 }
3396 else if (AmWalReceiverProcess())
3397 ereport(FATAL,
3399 errmsg("terminating walreceiver process due to administrator command"),
3401 else if (AmBackgroundWorkerProcess())
3402 ereport(FATAL,
3404 errmsg("terminating background worker \"%s\" due to administrator command",
3407 else if (AmIoWorkerProcess())
3408 {
3410 (errmsg_internal("io worker shutting down due to administrator command"),
3412
3413 proc_exit(0);
3414 }
3415 else
3416 ereport(FATAL,
3418 errmsg("terminating connection due to administrator command"),
3420 }
3421
3423 {
3425
3426 /*
3427 * Check for lost connection and re-arm, if still configured, but not
3428 * if we've arrived back at DoingCommandRead state. We don't want to
3429 * wake up idle sessions, and they already know how to detect lost
3430 * connections.
3431 */
3433 {
3434 if (!pq_check_connection())
3435 ClientConnectionLost = true;
3436 else
3439 }
3440 }
3441
3443 {
3444 QueryCancelPending = false; /* lost connection trumps QueryCancel */
3446 /* don't send to client, we already know the connection to be dead. */
3448 ereport(FATAL,
3450 errmsg("connection to client lost")));
3451 }
3452
3453 /*
3454 * Don't allow query cancel interrupts while reading input from the
3455 * client, because we might lose sync in the FE/BE protocol. (Die
3456 * interrupts are OK, because we won't read any further messages from the
3457 * client in that case.)
3458 *
3459 * See similar logic in ProcessRecoveryConflictInterrupts().
3460 */
3462 {
3463 /*
3464 * Re-arm InterruptPending so that we process the cancel request as
3465 * soon as we're done reading the message. (XXX this is seriously
3466 * ugly: it complicates INTERRUPTS_CAN_BE_PROCESSED(), and it means we
3467 * can't use that macro directly as the initial test in this function,
3468 * meaning that this code also creates opportunities for other bugs to
3469 * appear.)
3470 */
3471 InterruptPending = true;
3472 }
3473 else if (QueryCancelPending)
3474 {
3477
3478 QueryCancelPending = false;
3479
3480 /*
3481 * If LOCK_TIMEOUT and STATEMENT_TIMEOUT indicators are both set, we
3482 * need to clear both, so always fetch both.
3483 */
3486
3487 /*
3488 * If both were set, we want to report whichever timeout completed
3489 * earlier; this ensures consistent behavior if the machine is slow
3490 * enough that the second timeout triggers before we get here. A tie
3491 * is arbitrarily broken in favor of reporting a lock timeout.
3492 */
3495 lock_timeout_occurred = false; /* report stmt timeout */
3496
3498 {
3500 ereport(ERROR,
3502 errmsg("canceling statement due to lock timeout")));
3503 }
3505 {
3507 ereport(ERROR,
3509 errmsg("canceling statement due to statement timeout")));
3510 }
3512 {
3514 ereport(ERROR,
3516 errmsg("canceling autovacuum task")));
3517 }
3518
3519 /*
3520 * If we are reading a command from the client, just ignore the cancel
3521 * request --- sending an extra error message won't accomplish
3522 * anything. Otherwise, go ahead and throw the error.
3523 */
3524 if (!DoingCommandRead)
3525 {
3527 ereport(ERROR,
3529 errmsg("canceling statement due to user request")));
3530 }
3531 }
3532
3535
3537 {
3538 /*
3539 * If the GUC has been reset to zero, ignore the signal. This is
3540 * important because the GUC update itself won't disable any pending
3541 * interrupt. We need to unset the flag before the injection point,
3542 * otherwise we could loop in interrupts checking.
3543 */
3546 {
3547 INJECTION_POINT("idle-in-transaction-session-timeout", NULL);
3548 ereport(FATAL,
3550 errmsg("terminating connection due to idle-in-transaction timeout")));
3551 }
3552 }
3553
3555 {
3556 /* As above, ignore the signal if the GUC has been reset to zero. */
3558 if (TransactionTimeout > 0)
3559 {
3560 INJECTION_POINT("transaction-timeout", NULL);
3561 ereport(FATAL,
3563 errmsg("terminating connection due to transaction timeout")));
3564 }
3565 }
3566
3568 {
3569 /* As above, ignore the signal if the GUC has been reset to zero. */
3571 if (IdleSessionTimeout > 0)
3572 {
3573 INJECTION_POINT("idle-session-timeout", NULL);
3574 ereport(FATAL,
3576 errmsg("terminating connection due to idle-session timeout")));
3577 }
3578 }
3579
3580 /*
3581 * If there are pending stats updates and we currently are truly idle
3582 * (matching the conditions in PostgresMain(), report stats now.
3583 */
3586 {
3588 pgstat_report_stat(true);
3589 }
3590
3593
3596
3599
3602
3605
3608}
3609
3610/*
3611 * GUC check_hook for client_connection_check_interval
3612 */
3613bool
3615{
3616 if (!WaitEventSetCanReportClosed() && *newval != 0)
3617 {
3618 GUC_check_errdetail("\"client_connection_check_interval\" must be set to 0 on this platform.");
3619 return false;
3620 }
3621 return true;
3622}
3623
3624/*
3625 * GUC check_hook for log_parser_stats, log_planner_stats, log_executor_stats
3626 *
3627 * This function and check_log_stats interact to prevent their variables from
3628 * being set in a disallowed combination. This is a hack that doesn't really
3629 * work right; for example it might fail while applying pg_db_role_setting
3630 * values even though the final state would have been acceptable. However,
3631 * since these variables are legacy settings with little production usage,
3632 * we tolerate that.
3633 */
3634bool
3636{
3638 {
3639 GUC_check_errdetail("Cannot enable parameter when \"log_statement_stats\" is true.");
3640 return false;
3641 }
3642 return true;
3643}
3644
3645/*
3646 * GUC check_hook for log_statement_stats
3647 */
3648bool
3650{
3651 if (*newval &&
3653 {
3654 GUC_check_errdetail("Cannot enable \"log_statement_stats\" when "
3655 "\"log_parser_stats\", \"log_planner_stats\", "
3656 "or \"log_executor_stats\" is true.");
3657 return false;
3658 }
3659 return true;
3660}
3661
3662/* GUC assign hook for transaction_timeout */
3663void
3665{
3666 if (IsTransactionState())
3667 {
3668 /*
3669 * If transaction_timeout GUC has changed within the transaction block
3670 * enable or disable the timer correspondingly.
3671 */
3676 }
3677}
3678
3679/*
3680 * GUC check_hook for restrict_nonsystem_relation_kind
3681 */
3682bool
3684{
3685 char *rawstring;
3686 List *elemlist;
3687 ListCell *l;
3688 int flags = 0;
3689
3690 /* Need a modifiable copy of string */
3692
3694 {
3695 /* syntax error in list */
3696 GUC_check_errdetail("List syntax is invalid.");
3699 return false;
3700 }
3701
3702 foreach(l, elemlist)
3703 {
3704 char *tok = (char *) lfirst(l);
3705
3706 if (pg_strcasecmp(tok, "view") == 0)
3707 flags |= RESTRICT_RELKIND_VIEW;
3708 else if (pg_strcasecmp(tok, "foreign-table") == 0)
3710 else
3711 {
3712 GUC_check_errdetail("Unrecognized key word: \"%s\".", tok);
3715 return false;
3716 }
3717 }
3718
3721
3722 /* Save the flags in *extra, for use by the assign function */
3723 *extra = guc_malloc(LOG, sizeof(int));
3724 if (!*extra)
3725 return false;
3726 *((int *) *extra) = flags;
3727
3728 return true;
3729}
3730
3731/*
3732 * GUC assign_hook for restrict_nonsystem_relation_kind
3733 */
3734void
3736{
3737 int *flags = (int *) extra;
3738
3740}
3741
3742/*
3743 * set_debug_options --- apply "-d N" command line option
3744 *
3745 * -d is not quite the same as setting log_min_messages because it enables
3746 * other output options.
3747 */
3748void
3750{
3751 if (debug_flag > 0)
3752 {
3753 char debugstr[64];
3754
3755 sprintf(debugstr, "debug%d", debug_flag);
3756 SetConfigOption("log_min_messages", debugstr, context, source);
3757 }
3758 else
3759 SetConfigOption("log_min_messages", "notice", context, source);
3760
3761 if (debug_flag >= 1 && context == PGC_POSTMASTER)
3762 {
3763 SetConfigOption("log_connections", "all", context, source);
3764 SetConfigOption("log_disconnections", "true", context, source);
3765 }
3766 if (debug_flag >= 2)
3767 SetConfigOption("log_statement", "all", context, source);
3768 if (debug_flag >= 3)
3769 {
3770 SetConfigOption("debug_print_raw_parse", "true", context, source);
3771 SetConfigOption("debug_print_parse", "true", context, source);
3772 }
3773 if (debug_flag >= 4)
3774 SetConfigOption("debug_print_plan", "true", context, source);
3775 if (debug_flag >= 5)
3776 SetConfigOption("debug_print_rewritten", "true", context, source);
3777}
3778
3779
3780bool
3782{
3783 const char *tmp = NULL;
3784
3785 switch (arg[0])
3786 {
3787 case 's': /* seqscan */
3788 tmp = "enable_seqscan";
3789 break;
3790 case 'i': /* indexscan */
3791 tmp = "enable_indexscan";
3792 break;
3793 case 'o': /* indexonlyscan */
3794 tmp = "enable_indexonlyscan";
3795 break;
3796 case 'b': /* bitmapscan */
3797 tmp = "enable_bitmapscan";
3798 break;
3799 case 't': /* tidscan */
3800 tmp = "enable_tidscan";
3801 break;
3802 case 'n': /* nestloop */
3803 tmp = "enable_nestloop";
3804 break;
3805 case 'm': /* mergejoin */
3806 tmp = "enable_mergejoin";
3807 break;
3808 case 'h': /* hashjoin */
3809 tmp = "enable_hashjoin";
3810 break;
3811 }
3812 if (tmp)
3813 {
3814 SetConfigOption(tmp, "false", context, source);
3815 return true;
3816 }
3817 else
3818 return false;
3819}
3820
3821
3822const char *
3824{
3825 switch (arg[0])
3826 {
3827 case 'p':
3828 if (arg[1] == 'a') /* "parser" */
3829 return "log_parser_stats";
3830 else if (arg[1] == 'l') /* "planner" */
3831 return "log_planner_stats";
3832 break;
3833
3834 case 'e': /* "executor" */
3835 return "log_executor_stats";
3836 break;
3837 }
3838
3839 return NULL;
3840}
3841
3842
3843/* ----------------------------------------------------------------
3844 * process_postgres_switches
3845 * Parse command line arguments for backends
3846 *
3847 * This is called twice, once for the "secure" options coming from the
3848 * postmaster or command line, and once for the "insecure" options coming
3849 * from the client's startup packet. The latter have the same syntax but
3850 * may be restricted in what they can do.
3851 *
3852 * argv[0] is ignored in either case (it's assumed to be the program name).
3853 *
3854 * ctx is PGC_POSTMASTER for secure options, PGC_BACKEND for insecure options
3855 * coming from the client, or PGC_SU_BACKEND for insecure options coming from
3856 * a superuser client.
3857 *
3858 * If a database name is present in the command line arguments, it's
3859 * returned into *dbname (this is allowed only if *dbname is initially NULL).
3860 * ----------------------------------------------------------------
3861 */
3862void
3863process_postgres_switches(int argc, char *argv[], GucContext ctx,
3864 const char **dbname)
3865{
3866 bool secure = (ctx == PGC_POSTMASTER);
3867 int errs = 0;
3869 int flag;
3871
3872 if (secure)
3873 {
3874 gucsource = PGC_S_ARGV; /* switches came from command line */
3875
3876 /* Ignore the initial --single argument, if present */
3877 if (argc > 1 && strcmp(argv[1], "--single") == 0)
3878 {
3879 argv++;
3880 argc--;
3881 }
3882 }
3883 else
3884 {
3885 gucsource = PGC_S_CLIENT; /* switches came from client */
3886 }
3887
3888 /*
3889 * Parse command-line options. CAUTION: keep this in sync with
3890 * postmaster/postmaster.c (the option sets should not conflict) and with
3891 * the common help() function in main/main.c.
3892 */
3893 pg_getopt_start(&optctx, argc, argv, "B:bC:c:D:d:EeFf:h:ijk:lN:nOPp:r:S:sTt:v:W:-:");
3894
3895 /*
3896 * Turn this off because it's either printed to stderr and not the log
3897 * where we'd want it, or argv[0] is now "--single", which would make for
3898 * a weird error message. We print our own error message below.
3899 */
3900 optctx.opterr = 0;
3901
3902 while ((flag = pg_getopt_next(&optctx)) != -1)
3903 {
3904 switch (flag)
3905 {
3906 case 'B':
3907 SetConfigOption("shared_buffers", optctx.optarg, ctx, gucsource);
3908 break;
3909
3910 case 'b':
3911 /* Undocumented flag used for binary upgrades */
3912 if (secure)
3913 IsBinaryUpgrade = true;
3914 break;
3915
3916 case 'C':
3917 /* ignored for consistency with the postmaster */
3918 break;
3919
3920 case '-':
3921
3922 /*
3923 * Error if the user misplaced a special must-be-first option
3924 * for dispatching to a subprogram. parse_dispatch_option()
3925 * returns DISPATCH_POSTMASTER if it doesn't find a match, so
3926 * error for anything else.
3927 */
3929 ereport(ERROR,
3931 errmsg("--%s must be first argument", optctx.optarg)));
3932
3934 case 'c':
3935 {
3936 char *name,
3937 *value;
3938
3939 ParseLongOption(optctx.optarg, &name, &value);
3940 if (!value)
3941 {
3942 if (flag == '-')
3943 ereport(ERROR,
3945 errmsg("--%s requires a value",
3946 optctx.optarg)));
3947 else
3948 ereport(ERROR,
3950 errmsg("-c %s requires a value",
3951 optctx.optarg)));
3952 }
3954 pfree(name);
3955 pfree(value);
3956 break;
3957 }
3958
3959 case 'D':
3960 if (secure)
3961 userDoption = strdup(optctx.optarg);
3962 break;
3963
3964 case 'd':
3965 set_debug_options(atoi(optctx.optarg), ctx, gucsource);
3966 break;
3967
3968 case 'E':
3969 if (secure)
3970 EchoQuery = true;
3971 break;
3972
3973 case 'e':
3974 SetConfigOption("datestyle", "euro", ctx, gucsource);
3975 break;
3976
3977 case 'F':
3978 SetConfigOption("fsync", "false", ctx, gucsource);
3979 break;
3980
3981 case 'f':
3982 if (!set_plan_disabling_options(optctx.optarg, ctx, gucsource))
3983 errs++;
3984 break;
3985
3986 case 'h':
3987 SetConfigOption("listen_addresses", optctx.optarg, ctx, gucsource);
3988 break;
3989
3990 case 'i':
3991 SetConfigOption("listen_addresses", "*", ctx, gucsource);
3992 break;
3993
3994 case 'j':
3995 if (secure)
3996 UseSemiNewlineNewline = true;
3997 break;
3998
3999 case 'k':
4000 SetConfigOption("unix_socket_directories", optctx.optarg, ctx, gucsource);
4001 break;
4002
4003 case 'l':
4004 SetConfigOption("ssl", "true", ctx, gucsource);
4005 break;
4006
4007 case 'N':
4008 SetConfigOption("max_connections", optctx.optarg, ctx, gucsource);
4009 break;
4010
4011 case 'n':
4012 /* ignored for consistency with postmaster */
4013 break;
4014
4015 case 'O':
4016 SetConfigOption("allow_system_table_mods", "true", ctx, gucsource);
4017 break;
4018
4019 case 'P':
4020 SetConfigOption("ignore_system_indexes", "true", ctx, gucsource);
4021 break;
4022
4023 case 'p':
4024 SetConfigOption("port", optctx.optarg, ctx, gucsource);
4025 break;
4026
4027 case 'r':
4028 /* send output (stdout and stderr) to the given file */
4029 if (secure)
4031 break;
4032
4033 case 'S':
4034 SetConfigOption("work_mem", optctx.optarg, ctx, gucsource);
4035 break;
4036
4037 case 's':
4038 SetConfigOption("log_statement_stats", "true", ctx, gucsource);
4039 break;
4040
4041 case 'T':
4042 /* ignored for consistency with the postmaster */
4043 break;
4044
4045 case 't':
4046 {
4047 const char *tmp = get_stats_option_name(optctx.optarg);
4048
4049 if (tmp)
4050 SetConfigOption(tmp, "true", ctx, gucsource);
4051 else
4052 errs++;
4053 break;
4054 }
4055
4056 case 'v':
4057
4058 /*
4059 * -v is no longer used in normal operation, since
4060 * FrontendProtocol is already set before we get here. We keep
4061 * the switch only for possible use in standalone operation,
4062 * in case we ever support using normal FE/BE protocol with a
4063 * standalone backend.
4064 */
4065 if (secure)
4067 break;
4068
4069 case 'W':
4070 SetConfigOption("post_auth_delay", optctx.optarg, ctx, gucsource);
4071 break;
4072
4073 default:
4074 errs++;
4075 break;
4076 }
4077
4078 if (errs)
4079 break;
4080 }
4081
4082 /*
4083 * Optional database name should be there only if *dbname is NULL.
4084 */
4085 if (!errs && dbname && *dbname == NULL && argc - optctx.optind >= 1)
4086 *dbname = strdup(argv[optctx.optind++]);
4087
4088 if (errs || argc != optctx.optind)
4089 {
4090 if (errs)
4091 optctx.optind--; /* complain about the previous argument */
4092
4093 /* spell the error message a bit differently depending on context */
4095 ereport(FATAL,
4097 errmsg("invalid command-line argument for server process: %s", argv[optctx.optind]),
4098 errhint("Try \"%s --help\" for more information.", progname));
4099 else
4100 ereport(FATAL,
4102 errmsg("%s: invalid command-line argument: %s",
4103 progname, argv[optctx.optind]),
4104 errhint("Try \"%s --help\" for more information.", progname));
4105 }
4106}
4107
4108
4109/*
4110 * PostgresSingleUserMain
4111 * Entry point for single user mode. argc/argv are the command line
4112 * arguments to be used.
4113 *
4114 * Performs single user specific setup then calls PostgresMain() to actually
4115 * process queries. Single user mode specific setup should go here, rather
4116 * than PostgresMain() or InitPostgres() when reasonably possible.
4117 */
4118void
4119PostgresSingleUserMain(int argc, char *argv[],
4120 const char *username)
4121{
4122 const char *dbname = NULL;
4123
4125
4126 /* Initialize startup process environment. */
4127 InitStandaloneProcess(argv[0]);
4128
4129 /*
4130 * Set default values for command-line options.
4131 */
4133
4134 /*
4135 * Parse command-line options.
4136 */
4138
4139 /* Must have gotten a database name, or have a default (the username) */
4140 if (dbname == NULL)
4141 {
4142 dbname = username;
4143 if (dbname == NULL)
4144 ereport(FATAL,
4146 errmsg("%s: no database nor user name specified",
4147 progname)));
4148 }
4149
4150 /* Acquire configuration parameters */
4152 proc_exit(1);
4153
4154 /*
4155 * Validate we have been given a reasonable-looking DataDir and change
4156 * into it.
4157 */
4158 checkDataDir();
4160
4161 /*
4162 * Create lockfile for data directory.
4163 */
4164 CreateDataDirLockFile(false);
4165
4166 /* read control file (error checking and contains config ) */
4168
4169 /* Register the shared memory needs of all core subsystems. */
4171
4172 /*
4173 * process any libraries that should be preloaded at postmaster start
4174 */
4176
4177 /* Initialize MaxBackends */
4179
4180 /*
4181 * We don't need postmaster child slots in single-user mode, but
4182 * initialize them anyway to avoid having special handling.
4183 */
4185
4186 /* Initialize size of fast-path lock cache. */
4188
4189 /*
4190 * Also call any legacy shmem request hooks that might'be been installed
4191 * by preloaded libraries.
4192 *
4193 * Note: this must be done before ShmemCallRequestCallbacks(), because the
4194 * hooks may request LWLocks with RequestNamedLWLockTranche(), which in
4195 * turn affects the size of the LWLock array calculated in lwlock.c.
4196 */
4198
4199 /*
4200 * Before computing the total size needed, give all subsystems, including
4201 * add-ins, a chance to chance to adjust their requested shmem sizes.
4202 */
4204
4205 /*
4206 * Now that loadable modules have had their chance to request additional
4207 * shared memory, determine the value of any runtime-computed GUCs that
4208 * depend on the amount of shared memory required.
4209 */
4211
4212 /*
4213 * Now that modules have been loaded, we can process any custom resource
4214 * managers specified in the wal_consistency_checking GUC.
4215 */
4217
4218 /*
4219 * Create shared memory etc. (Nothing's really "shared" in single-user
4220 * mode, but we must have these data structures anyway.)
4221 */
4223
4224 /*
4225 * Estimate number of openable files. This must happen after setting up
4226 * semaphores, because on some platforms semaphores count as open files.
4227 */
4229
4230 /*
4231 * Remember stand-alone backend startup time,roughly at the same point
4232 * during startup that postmaster does so.
4233 */
4235
4236 /*
4237 * Create a per-backend PGPROC struct in shared memory. We must do this
4238 * before we can use LWLocks.
4239 */
4240 InitProcess();
4241
4242 /*
4243 * Now that sufficient infrastructure has been initialized, PostgresMain()
4244 * can do the rest.
4245 */
4247}
4248
4249
4250/* ----------------------------------------------------------------
4251 * PostgresMain
4252 * postgres main loop -- all backends, interactive or otherwise loop here
4253 *
4254 * dbname is the name of the database to connect to, username is the
4255 * PostgreSQL user name to be used for the session.
4256 *
4257 * NB: Single user mode specific setup should go to PostgresSingleUserMain()
4258 * if reasonably possible.
4259 * ----------------------------------------------------------------
4260 */
4261void
4262PostgresMain(const char *dbname, const char *username)
4263{
4265
4266 /* these must be volatile to ensure state is preserved across longjmp: */
4267 volatile bool send_ready_for_query = true;
4268 volatile bool idle_in_transaction_timeout_enabled = false;
4269 volatile bool idle_session_timeout_enabled = false;
4270
4271 Assert(dbname != NULL);
4272 Assert(username != NULL);
4273
4275
4276 /*
4277 * Set up signal handlers. (InitPostmasterChild or InitStandaloneProcess
4278 * has already set up BlockSig and made that the active signal mask.)
4279 *
4280 * Note that postmaster blocked all signals before forking child process,
4281 * so there is no race condition whereby we might receive a signal before
4282 * we have set up the handler.
4283 *
4284 * Also note: it's best not to use any signals that are SIG_IGNored in the
4285 * postmaster. If such a signal arrives before we are able to change the
4286 * handler to non-SIG_IGN, it'll get dropped. Instead, make a dummy
4287 * handler in the postmaster to reserve the signal. (Of course, this isn't
4288 * an issue for signals that are locally generated, such as SIGALRM and
4289 * SIGPIPE.)
4290 */
4291 if (am_walsender)
4292 WalSndSignals();
4293 else
4294 {
4296 pqsignal(SIGINT, StatementCancelHandler); /* cancel current query */
4297 pqsignal(SIGTERM, die); /* cancel current query and exit */
4298
4299 /*
4300 * In a postmaster child backend, replace SignalHandlerForCrashExit
4301 * with quickdie, so we can tell the client we're dying.
4302 *
4303 * In a standalone backend, SIGQUIT can be generated from the keyboard
4304 * easily, while SIGTERM cannot, so we make both signals do die()
4305 * rather than quickdie().
4306 */
4308 pqsignal(SIGQUIT, quickdie); /* hard crash time */
4309 else
4310 pqsignal(SIGQUIT, die); /* cancel current query and exit */
4311 InitializeTimeouts(); /* establishes SIGALRM handler */
4312
4313 /*
4314 * Ignore failure to write to frontend. Note: if frontend closes
4315 * connection, we will notice it and exit cleanly when control next
4316 * returns to outer loop. This seems safer than forcing exit in the
4317 * midst of output during who-knows-what operation...
4318 */
4323
4324 /*
4325 * Reset some signals that are accepted by postmaster but not by
4326 * backend
4327 */
4328 pqsignal(SIGCHLD, SIG_DFL); /* system() requires this on some
4329 * platforms */
4330 }
4331
4332 /* Early initialization */
4333 BaseInit();
4334
4335 /* We need to allow SIGINT, etc during the initial transaction */
4337
4338 /*
4339 * Generate a random cancel key, if this is a backend serving a
4340 * connection. InitPostgres() will advertise it in shared memory.
4341 */
4344 {
4345 int len;
4346
4347 len = (MyProcPort == NULL || MyProcPort->proto >= PG_PROTOCOL(3, 2))
4350 {
4351 ereport(ERROR,
4353 errmsg("could not generate random cancel key")));
4354 }
4356 }
4357
4358 /*
4359 * General initialization.
4360 *
4361 * NOTE: if you are tempted to add code in this vicinity, consider putting
4362 * it inside InitPostgres() instead. In particular, anything that
4363 * involves database access should be there, not here.
4364 *
4365 * Honor session_preload_libraries if not dealing with a WAL sender.
4366 */
4367 InitPostgres(dbname, InvalidOid, /* database to connect to */
4368 username, InvalidOid, /* role to connect as */
4370 NULL); /* no out_dbname */
4371
4372 /*
4373 * If the PostmasterContext is still around, recycle the space; we don't
4374 * need it anymore after InitPostgres completes.
4375 */
4377 {
4380 }
4381
4383
4384 /*
4385 * Now all GUC states are fully set up. Report them to client if
4386 * appropriate.
4387 */
4389
4390 /*
4391 * Also set up handler to log session end; we have to wait till now to be
4392 * sure Log_disconnections has its final value.
4393 */
4396
4398
4399 /* Perform initialization specific to a WAL sender process. */
4400 if (am_walsender)
4401 InitWalSender();
4402
4403 /*
4404 * Send this backend's cancellation info to the frontend.
4405 */
4407 {
4409
4413
4416 /* Need not flush since ReadyForQuery will do it. */
4417 }
4418
4419 /* Welcome banner for standalone case */
4421 printf("\nPostgreSQL stand-alone backend %s\n", PG_VERSION);
4422
4423 /*
4424 * Create the memory context we will use in the main loop.
4425 *
4426 * MessageContext is reset once per iteration of the main loop, ie, upon
4427 * completion of processing of each command message from the client.
4428 */
4430 "MessageContext",
4432
4433 /*
4434 * Create memory context and buffer used for RowDescription messages. As
4435 * SendRowDescriptionMessage(), via exec_describe_statement_message(), is
4436 * frequently executed for every single statement, we don't want to
4437 * allocate a separate buffer every time.
4438 */
4440 "RowDescriptionContext",
4445
4446 /* Fire any defined login event triggers, if appropriate */
4448
4449 /*
4450 * POSTGRES main processing loop begins here
4451 *
4452 * If an exception is encountered, processing resumes here so we abort the
4453 * current transaction and start a new one.
4454 *
4455 * You might wonder why this isn't coded as an infinite loop around a
4456 * PG_TRY construct. The reason is that this is the bottom of the
4457 * exception stack, and so with PG_TRY there would be no exception handler
4458 * in force at all during the CATCH part. By leaving the outermost setjmp
4459 * always active, we have at least some chance of recovering from an error
4460 * during error recovery. (If we get into an infinite loop thereby, it
4461 * will soon be stopped by overflow of elog.c's internal state stack.)
4462 *
4463 * Note that we use sigsetjmp(..., 1), so that this function's signal mask
4464 * (to wit, UnBlockSig) will be restored when longjmp'ing to here. This
4465 * is essential in case we longjmp'd out of a signal handler on a platform
4466 * where that leaves the signal blocked. It's not redundant with the
4467 * unblock in AbortTransaction() because the latter is only called if we
4468 * were inside a transaction.
4469 */
4470
4471 if (sigsetjmp(local_sigjmp_buf, 1) != 0)
4472 {
4473 /*
4474 * NOTE: if you are tempted to add more code in this if-block,
4475 * consider the high probability that it should be in
4476 * AbortTransaction() instead. The only stuff done directly here
4477 * should be stuff that is guaranteed to apply *only* for outer-level
4478 * error recovery, such as adjusting the FE/BE protocol status.
4479 */
4480
4481 /* Since not using PG_TRY, must reset error stack by hand */
4483
4484 /* Prevent interrupts while cleaning up */
4486
4487 /*
4488 * Forget any pending QueryCancel request, since we're returning to
4489 * the idle loop anyway, and cancel any active timeout requests. (In
4490 * future we might want to allow some timeout requests to survive, but
4491 * at minimum it'd be necessary to do reschedule_timeouts(), in case
4492 * we got here because of a query cancel interrupting the SIGALRM
4493 * interrupt handler.) Note in particular that we must clear the
4494 * statement and lock timeout indicators, to prevent any future plain
4495 * query cancels from being misreported as timeouts in case we're
4496 * forgetting a timeout cancel.
4497 */
4498 disable_all_timeouts(false); /* do first to avoid race condition */
4499 QueryCancelPending = false;
4502
4503 /* Not reading from the client anymore. */
4504 DoingCommandRead = false;
4505
4506 /* Make sure libpq is in a good state */
4507 pq_comm_reset();
4508
4509 /* Report the error to the client and/or server log */
4511
4512 /*
4513 * If Valgrind noticed something during the erroneous query, print the
4514 * query string, assuming we have one.
4515 */
4517
4518 /*
4519 * Make sure debug_query_string gets reset before we possibly clobber
4520 * the storage it points at.
4521 */
4523
4524 /*
4525 * Abort the current transaction in order to recover.
4526 */
4528
4529 if (am_walsender)
4531
4533
4534 /*
4535 * We can't release replication slots inside AbortTransaction() as we
4536 * need to be able to start and abort transactions while having a slot
4537 * acquired. But we never need to hold them across top level errors,
4538 * so releasing here is fine. There also is a before_shmem_exit()
4539 * callback ensuring correct cleanup on FATAL errors.
4540 */
4541 if (MyReplicationSlot != NULL)
4543
4544 /* We also want to cleanup temporary slots on error. */
4546
4548
4549 /*
4550 * Now return to normal top-level context and clear ErrorContext for
4551 * next time.
4552 */
4555
4556 /*
4557 * If we were handling an extended-query-protocol message, initiate
4558 * skip till next Sync. This also causes us not to issue
4559 * ReadyForQuery (until we get Sync).
4560 */
4562 ignore_till_sync = true;
4563
4564 /* We don't have a transaction command open anymore */
4565 xact_started = false;
4566
4567 /*
4568 * If an error occurred while we were reading a message from the
4569 * client, we have potentially lost track of where the previous
4570 * message ends and the next one begins. Even though we have
4571 * otherwise recovered from the error, we cannot safely read any more
4572 * messages from the client, so there isn't much we can do with the
4573 * connection anymore.
4574 */
4575 if (pq_is_reading_msg())
4576 ereport(FATAL,
4578 errmsg("terminating connection because protocol synchronization was lost")));
4579
4580 /* Now we can allow interrupts again */
4582 }
4583
4584 /* We can now handle ereport(ERROR) */
4586
4587 if (!ignore_till_sync)
4588 send_ready_for_query = true; /* initially, or after error */
4589
4590 /*
4591 * Non-error queries loop here.
4592 */
4593
4594 for (;;)
4595 {
4596 int firstchar;
4598
4599 /*
4600 * At top of loop, reset extended-query-message flag, so that any
4601 * errors encountered in "idle" state don't provoke skip.
4602 */
4604
4605 /*
4606 * For valgrind reporting purposes, the "current query" begins here.
4607 */
4608#ifdef USE_VALGRIND
4610#endif
4611
4612 /*
4613 * Release storage left over from prior query cycle, and create a new
4614 * query input buffer in the cleared MessageContext.
4615 */
4618
4620
4621 /*
4622 * Also consider releasing our catalog snapshot if any, so that it's
4623 * not preventing advance of global xmin while we wait for the client.
4624 */
4626
4627 /*
4628 * (1) If we've reached idle state, tell the frontend we're ready for
4629 * a new query.
4630 *
4631 * Note: this includes fflush()'ing the last of the prior output.
4632 *
4633 * This is also a good time to flush out collected statistics to the
4634 * cumulative stats system, and to update the PS stats display. We
4635 * avoid doing those every time through the message loop because it'd
4636 * slow down processing of batched messages, and because we don't want
4637 * to report uncommitted updates (that confuses autovacuum). The
4638 * notification processor wants a call too, if we are not in a
4639 * transaction block.
4640 *
4641 * Also, if an idle timeout is enabled, start the timer for that.
4642 */
4644 {
4646 {
4647 set_ps_display("idle in transaction (aborted)");
4649
4650 /* Start the idle-in-transaction timer */
4653 {
4657 }
4658 }
4660 {
4661 set_ps_display("idle in transaction");
4663
4664 /* Start the idle-in-transaction timer */
4667 {
4671 }
4672 }
4673 else
4674 {
4675 long stats_timeout;
4676
4677 /*
4678 * Process incoming notifies (including self-notifies), if
4679 * any, and send relevant messages to the client. Doing it
4680 * here helps ensure stable behavior in tests: if any notifies
4681 * were received during the just-finished transaction, they'll
4682 * be seen by the client before ReadyForQuery is.
4683 */
4686
4687 /*
4688 * Check if we need to report stats. If pgstat_report_stat()
4689 * decides it's too soon to flush out pending stats / lock
4690 * contention prevented reporting, it'll tell us when we
4691 * should try to report stats again (so that stats updates
4692 * aren't unduly delayed if the connection goes idle for a
4693 * long time). We only enable the timeout if we don't already
4694 * have a timeout in progress, because we don't disable the
4695 * timeout below. enable_timeout_after() needs to determine
4696 * the current timestamp, which can have a negative
4697 * performance impact. That's OK because pgstat_report_stat()
4698 * won't have us wake up sooner than a prior call.
4699 */
4701 if (stats_timeout > 0)
4702 {
4706 }
4707 else
4708 {
4709 /* all stats flushed, no need for the timeout */
4712 }
4713
4714 set_ps_display("idle");
4716
4717 /* Start the idle-session timer */
4718 if (IdleSessionTimeout > 0)
4719 {
4723 }
4724 }
4725
4726 /* Report any recently-changed GUC options */
4728
4729 /*
4730 * The first time this backend is ready for query, log the
4731 * durations of the different components of connection
4732 * establishment and setup.
4733 */
4737 {
4741
4743
4753
4754 ereport(LOG,
4755 errmsg("connection ready: setup total=%.3f ms, fork=%.3f ms, authentication=%.3f ms",
4756 (double) total_duration / NS_PER_US,
4757 (double) fork_duration / NS_PER_US,
4758 (double) auth_duration / NS_PER_US));
4759 }
4760
4762 send_ready_for_query = false;
4763 }
4764
4765 /*
4766 * (2) Allow asynchronous signals to be executed immediately if they
4767 * come in while we are waiting for client input. (This must be
4768 * conditional since we don't want, say, reads on behalf of COPY FROM
4769 * STDIN doing the same thing.)
4770 */
4771 DoingCommandRead = true;
4772
4773 /*
4774 * (3) read a command (loop blocks here)
4775 */
4777
4778 /*
4779 * (4) turn off the idle-in-transaction and idle-session timeouts if
4780 * active. We do this before step (5) so that any last-moment timeout
4781 * is certain to be detected in step (5).
4782 *
4783 * At most one of these timeouts will be active, so there's no need to
4784 * worry about combining the timeout.c calls into one.
4785 */
4787 {
4790 }
4792 {
4795 }
4796
4797 /*
4798 * (5) disable async signal conditions again.
4799 *
4800 * Query cancel is supposed to be a no-op when there is no query in
4801 * progress, so if a query cancel arrived while we were idle, just
4802 * reset QueryCancelPending. ProcessInterrupts() has that effect when
4803 * it's called when DoingCommandRead is set, so check for interrupts
4804 * before resetting DoingCommandRead.
4805 */
4807 DoingCommandRead = false;
4808
4809 /*
4810 * (6) check for any other interesting events that happened while we
4811 * slept.
4812 */
4814 {
4815 ConfigReloadPending = false;
4817 }
4818
4819 /*
4820 * (7) process the command. But ignore it if we're skipping till
4821 * Sync.
4822 */
4823 if (ignore_till_sync && firstchar != EOF)
4824 continue;
4825
4826 switch (firstchar)
4827 {
4828 case PqMsg_Query:
4829 {
4830 const char *query_string;
4831
4832 /* Set statement_timestamp() */
4834
4835 query_string = pq_getmsgstring(&input_message);
4837
4838 if (am_walsender)
4839 {
4840 if (!exec_replication_command(query_string))
4841 exec_simple_query(query_string);
4842 }
4843 else
4844 exec_simple_query(query_string);
4845
4846 valgrind_report_error_query(query_string);
4847
4848 send_ready_for_query = true;
4849 }
4850 break;
4851
4852 case PqMsg_Parse:
4853 {
4854 const char *stmt_name;
4855 const char *query_string;
4856 int numParams;
4857 Oid *paramTypes = NULL;
4858
4860
4861 /* Set statement_timestamp() */
4863
4864 stmt_name = pq_getmsgstring(&input_message);
4865 query_string = pq_getmsgstring(&input_message);
4866 numParams = pq_getmsgint(&input_message, 2);
4867 if (numParams > 0)
4868 {
4869 paramTypes = palloc_array(Oid, numParams);
4870 for (int i = 0; i < numParams; i++)
4871 paramTypes[i] = pq_getmsgint(&input_message, 4);
4872 }
4874
4875 exec_parse_message(query_string, stmt_name,
4876 paramTypes, numParams);
4877
4878 valgrind_report_error_query(query_string);
4879 }
4880 break;
4881
4882 case PqMsg_Bind:
4884
4885 /* Set statement_timestamp() */
4887
4888 /*
4889 * this message is complex enough that it seems best to put
4890 * the field extraction out-of-line
4891 */
4893
4894 /* exec_bind_message does valgrind_report_error_query */
4895 break;
4896
4897 case PqMsg_Execute:
4898 {
4899 const char *portal_name;
4900 int max_rows;
4901
4903
4904 /* Set statement_timestamp() */
4906
4910
4912
4913 /* exec_execute_message does valgrind_report_error_query */
4914 }
4915 break;
4916
4917 case PqMsg_FunctionCall:
4919
4920 /* Set statement_timestamp() */
4922
4923 /* Report query to various monitoring facilities. */
4925 set_ps_display("<FASTPATH>");
4926
4927 /* start an xact for this function invocation */
4929
4930 /*
4931 * Note: we may at this point be inside an aborted
4932 * transaction. We can't throw error for that until we've
4933 * finished reading the function-call message, so
4934 * HandleFunctionRequest() must check for it after doing so.
4935 * Be careful not to do anything that assumes we're inside a
4936 * valid transaction here.
4937 */
4938
4939 /* switch back to message context */
4941
4943
4944 /* commit the function-invocation transaction */
4946
4947 valgrind_report_error_query("fastpath function call");
4948
4949 send_ready_for_query = true;
4950 break;
4951
4952 case PqMsg_Close:
4953 {
4954 int close_type;
4955 const char *close_target;
4956
4958
4962
4963 switch (close_type)
4964 {
4965 case 'S':
4966 if (close_target[0] != '\0')
4968 else
4969 {
4970 /* special-case the unnamed statement */
4972 }
4973 break;
4974 case 'P':
4975 {
4976 Portal portal;
4977
4978 portal = GetPortalByName(close_target);
4979 if (PortalIsValid(portal))
4980 PortalDrop(portal, false);
4981 }
4982 break;
4983 default:
4984 ereport(ERROR,
4986 errmsg("invalid CLOSE message subtype %d",
4987 close_type)));
4988 break;
4989 }
4990
4993
4994 valgrind_report_error_query("CLOSE message");
4995 }
4996 break;
4997
4998 case PqMsg_Describe:
4999 {
5000 int describe_type;
5001 const char *describe_target;
5002
5004
5005 /* Set statement_timestamp() (needed for xact) */
5007
5011
5012 switch (describe_type)
5013 {
5014 case 'S':
5016 break;
5017 case 'P':
5019 break;
5020 default:
5021 ereport(ERROR,
5023 errmsg("invalid DESCRIBE message subtype %d",
5024 describe_type)));
5025 break;
5026 }
5027
5028 valgrind_report_error_query("DESCRIBE message");
5029 }
5030 break;
5031
5032 case PqMsg_Flush:
5035 pq_flush();
5036 break;
5037
5038 case PqMsg_Sync:
5040
5041 /*
5042 * If pipelining was used, we may be in an implicit
5043 * transaction block. Close it before calling
5044 * finish_xact_command.
5045 */
5048 valgrind_report_error_query("SYNC message");
5049 send_ready_for_query = true;
5050 break;
5051
5052 /*
5053 * PqMsg_Terminate means that the frontend is closing down the
5054 * socket. EOF means unexpected loss of frontend connection.
5055 * Either way, perform normal shutdown.
5056 */
5057 case EOF:
5058
5059 /* for the cumulative statistics system */
5061
5063
5064 case PqMsg_Terminate:
5065
5066 /*
5067 * Reset whereToSendOutput to prevent ereport from attempting
5068 * to send any more messages to client.
5069 */
5072
5073 /*
5074 * NOTE: if you are tempted to add more code here, DON'T!
5075 * Whatever you had in mind to do should be set up as an
5076 * on_proc_exit or on_shmem_exit callback, instead. Otherwise
5077 * it will fail to be called during other backend-shutdown
5078 * scenarios.
5079 */
5080 proc_exit(0);
5081
5082 case PqMsg_CopyData:
5083 case PqMsg_CopyDone:
5084 case PqMsg_CopyFail:
5085
5086 /*
5087 * Accept but ignore these messages, per protocol spec; we
5088 * probably got here because a COPY failed, and the frontend
5089 * is still sending data.
5090 */
5091 break;
5092
5093 default:
5094 ereport(FATAL,
5096 errmsg("invalid frontend message type %d",
5097 firstchar)));
5098 }
5099 } /* end of input-reading loop */
5100}
5101
5102/*
5103 * Throw an error if we're a WAL sender process.
5104 *
5105 * This is used to forbid anything else than simple query protocol messages
5106 * in a WAL sender process. 'firstchar' specifies what kind of a forbidden
5107 * message was received, and is used to construct the error message.
5108 */
5109static void
5111{
5112 if (am_walsender)
5113 {
5115 ereport(ERROR,
5117 errmsg("fastpath function calls not supported in a replication connection")));
5118 else
5119 ereport(ERROR,
5121 errmsg("extended query protocol not supported in a replication connection")));
5122 }
5123}
5124
5125
5126static struct rusage Save_r;
5127static struct timeval Save_t;
5128
5129void
5131{
5134}
5135
5136void
5137ShowUsage(const char *title)
5138{
5140 struct timeval user,
5141 sys;
5142 struct timeval elapse_t;
5143 struct rusage r;
5144
5147 memcpy(&user, &r.ru_utime, sizeof(user));
5148 memcpy(&sys, &r.ru_stime, sizeof(sys));
5149 if (elapse_t.tv_usec < Save_t.tv_usec)
5150 {
5151 elapse_t.tv_sec--;
5152 elapse_t.tv_usec += 1000000;
5153 }
5154 if (r.ru_utime.tv_usec < Save_r.ru_utime.tv_usec)
5155 {
5156 r.ru_utime.tv_sec--;
5157 r.ru_utime.tv_usec += 1000000;
5158 }
5159 if (r.ru_stime.tv_usec < Save_r.ru_stime.tv_usec)
5160 {
5161 r.ru_stime.tv_sec--;
5162 r.ru_stime.tv_usec += 1000000;
5163 }
5164
5165 /*
5166 * The only stats we don't show here are ixrss, idrss, isrss. It takes
5167 * some work to interpret them, and most platforms don't fill them in.
5168 */
5170
5171 appendStringInfoString(&str, "! system usage stats:\n");
5173 "!\t%ld.%06ld s user, %ld.%06ld s system, %ld.%06ld s elapsed\n",
5174 (long) (r.ru_utime.tv_sec - Save_r.ru_utime.tv_sec),
5175 (long) (r.ru_utime.tv_usec - Save_r.ru_utime.tv_usec),
5176 (long) (r.ru_stime.tv_sec - Save_r.ru_stime.tv_sec),
5177 (long) (r.ru_stime.tv_usec - Save_r.ru_stime.tv_usec),
5178 (long) (elapse_t.tv_sec - Save_t.tv_sec),
5179 (long) (elapse_t.tv_usec - Save_t.tv_usec));
5181 "!\t[%ld.%06ld s user, %ld.%06ld s system total]\n",
5182 (long) user.tv_sec,
5183 (long) user.tv_usec,
5184 (long) sys.tv_sec,
5185 (long) sys.tv_usec);
5186#ifndef WIN32
5187
5188 /*
5189 * The following rusage fields are not defined by POSIX, but they're
5190 * present on all current Unix-like systems so we use them without any
5191 * special checks. Some of these could be provided in our Windows
5192 * emulation in src/port/win32getrusage.c with more work.
5193 */
5195 "!\t%ld kB max resident size\n",
5197 /* in bytes on macOS */
5198 r.ru_maxrss / 1024
5199#else
5200 /* in kilobytes on most other platforms */
5201 r.ru_maxrss
5202#endif
5203 );
5205 "!\t%ld/%ld [%ld/%ld] filesystem blocks in/out\n",
5206 r.ru_inblock - Save_r.ru_inblock,
5207 /* they only drink coffee at dec */
5208 r.ru_oublock - Save_r.ru_oublock,
5209 r.ru_inblock, r.ru_oublock);
5211 "!\t%ld/%ld [%ld/%ld] page faults/reclaims, %ld [%ld] swaps\n",
5212 r.ru_majflt - Save_r.ru_majflt,
5213 r.ru_minflt - Save_r.ru_minflt,
5214 r.ru_majflt, r.ru_minflt,
5215 r.ru_nswap - Save_r.ru_nswap,
5216 r.ru_nswap);
5218 "!\t%ld [%ld] signals rcvd, %ld/%ld [%ld/%ld] messages rcvd/sent\n",
5219 r.ru_nsignals - Save_r.ru_nsignals,
5220 r.ru_nsignals,
5221 r.ru_msgrcv - Save_r.ru_msgrcv,
5222 r.ru_msgsnd - Save_r.ru_msgsnd,
5223 r.ru_msgrcv, r.ru_msgsnd);
5225 "!\t%ld/%ld [%ld/%ld] voluntary/involuntary context switches\n",
5226 r.ru_nvcsw - Save_r.ru_nvcsw,
5227 r.ru_nivcsw - Save_r.ru_nivcsw,
5228 r.ru_nvcsw, r.ru_nivcsw);
5229#endif /* !WIN32 */
5230
5231 /* remove trailing newline */
5232 if (str.data[str.len - 1] == '\n')
5233 str.data[--str.len] = '\0';
5234
5235 ereport(LOG,
5236 (errmsg_internal("%s", title),
5237 errdetail_internal("%s", str.data)));
5238
5239 pfree(str.data);
5240}
5241
5242/*
5243 * on_proc_exit handler to log end of session
5244 */
5245static void
5247{
5248 Port *port = MyProcPort;
5249 long secs;
5250 int usecs;
5251 int msecs;
5252 int hours,
5253 minutes,
5254 seconds;
5255
5258 &secs, &usecs);
5259 msecs = usecs / 1000;
5260
5265
5266 ereport(LOG,
5267 (errmsg("disconnection: session time: %d:%02d:%02d.%03d "
5268 "user=%s database=%s host=%s%s%s",
5270 port->user_name, port->database_name, port->remote_host,
5271 port->remote_port[0] ? " port=" : "", port->remote_port)));
5272}
5273
5274/*
5275 * Start statement timeout timer, if enabled.
5276 *
5277 * If there's already a timeout running, don't restart the timer. That
5278 * enables compromises between accuracy of timeouts and cost of starting a
5279 * timeout.
5280 */
5281static void
5283{
5284 /* must be within an xact */
5286
5287 if (StatementTimeout > 0
5289 {
5292 }
5293 else
5294 {
5297 }
5298}
5299
5300/*
5301 * Disable statement timeout, if active.
5302 */
5303static void
Datum querytree(PG_FUNCTION_ARGS)
Definition _int_bool.c:665
volatile sig_atomic_t ParallelApplyMessagePending
void ProcessParallelApplyMessages(void)
void ProcessNotifyInterrupt(bool flush)
Definition async.c: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:6065
void TimestampDifference(TimestampTz start_time, TimestampTz stop_time, long *secs, int *microsecs)
Definition timestamp.c:1715
TimestampTz GetCurrentTimestamp(void)
Definition timestamp.c:1639
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:6817
#define INT64CONST(x)
Definition c.h:630
#define unconstify(underlying_type, expr)
Definition c.h:1325
#define SIGNAL_ARGS
Definition c.h:1450
#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:169
DestReceiver * CreateDestReceiver(CommandDest dest)
Definition dest.c:113
void BeginCommand(CommandTag commandTag, CommandDest dest)
Definition dest.c:103
void ReadyForQuery(CommandDest dest)
Definition dest.c:257
void NullCommand(CommandDest dest)
Definition dest.c:219
CommandDest
Definition dest.h:86
@ DestRemote
Definition dest.h:89
@ DestDebug
Definition dest.h:88
@ DestRemoteExecute
Definition dest.h:90
@ DestNone
Definition dest.h:87
Datum arg
Definition elog.c:1322
void EmitErrorReport(void)
Definition elog.c:1882
ErrorContextCallback * error_context_stack
Definition elog.c:99
void FlushErrorState(void)
Definition elog.c:2062
int errcode(int sqlerrcode)
Definition elog.c:874
#define _(x)
Definition elog.c:95
sigjmp_buf * PG_exception_stack
Definition elog.c:101
int int errhidestmt(bool hide_stmt)
#define LOG
Definition elog.h: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:76
#define palloc0_array(type, count)
Definition fe_memutils.h:77
Datum OidReceiveFunctionCall(Oid functionId, StringInfo buf, Oid typioparam, int32 typmod)
Definition fmgr.c:1773
Datum OidInputFunctionCall(Oid functionId, char *str, Oid typioparam, int32 typmod)
Definition fmgr.c:1755
volatile sig_atomic_t IdleStatsUpdateTimeoutPending
Definition globals.c:42
volatile sig_atomic_t LogMemoryContextPending
Definition globals.c:41
volatile sig_atomic_t ProcSignalBarrierPending
Definition globals.c:40
volatile sig_atomic_t InterruptPending
Definition globals.c:32
int MyCancelKeyLength
Definition globals.c: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:1907
void getTypeInputInfo(Oid type, Oid *typInput, Oid *typIOParam)
Definition lsyscache.c:3096
void getTypeBinaryInputInfo(Oid type, Oid *typReceive, Oid *typIOParam)
Definition lsyscache.c:3162
DispatchOption parse_dispatch_option(const char *name)
Definition main.c:244
const char * progname
Definition main.c:44
char * pg_client_to_server(const char *s, int len)
Definition mbutils.c:671
MemoryContext MessageContext
Definition mcxt.c:170
void MemoryContextReset(MemoryContext context)
Definition mcxt.c:403
char * pstrdup(const char *in)
Definition mcxt.c:1781
void MemoryContextSetParent(MemoryContext context, MemoryContext new_parent)
Definition mcxt.c:686
void pfree(void *pointer)
Definition mcxt.c:1616
MemoryContext TopMemoryContext
Definition mcxt.c:166
char * pnstrdup(const char *in, Size len)
Definition mcxt.c:1792
void MemoryContextStats(MemoryContext context)
Definition mcxt.c:863
MemoryContext PostmasterContext
Definition mcxt.c:168
void ProcessLogMemoryContextInterrupt(void)
Definition mcxt.c:1340
void MemoryContextDelete(MemoryContext context)
Definition mcxt.c:472
#define AllocSetContextCreate
Definition memutils.h:129
#define ALLOCSET_DEFAULT_SIZES
Definition memutils.h:160
#define RESUME_INTERRUPTS()
Definition miscadmin.h: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:124
ParamListInfo makeParamList(int numParams)
Definition params.c:44
char * BuildParamLogString(ParamListInfo params, char **knownTextValues, int maxlen)
Definition params.c:333
void ParamsErrorCallback(void *arg)
Definition params.c:405
#define PARAM_FLAG_CONST
Definition params.h:87
void(* ParserSetupHook)(ParseState *pstate, void *arg)
Definition params.h:107
@ TRANS_STMT_ROLLBACK_TO
@ TRANS_STMT_ROLLBACK
@ TRANS_STMT_COMMIT
@ TRANS_STMT_PREPARE
#define FETCH_ALL
#define CURSOR_OPT_PARALLEL_OK
#define CURSOR_OPT_BINARY
Query * parse_analyze_withcb(RawStmt *parseTree, const char *sourceText, ParserSetupHook parserSetup, void *parserSetupArg, QueryEnvironment *queryEnv)
Definition analyze.c: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:315
@ 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:547
bool pg_strong_random(void *buf, size_t len)
int pg_strcasecmp(const char *s1, const char *s2)
#define sprintf
Definition port.h:262
#define snprintf
Definition port.h:260
#define printf(...)
Definition port.h:266
size_t strlcpy(char *dst, const char *src, size_t siz)
Definition strlcpy.c:45
#define PortalIsValid(p)
Definition portal.h:211
void PortalDrop(Portal portal, bool isTopCommit)
Definition portalmem.c:469
Portal GetPortalByName(const char *name)
Definition portalmem.c:132
void PortalDefineQuery(Portal portal, const char *prepStmtName, const char *sourceText, CommandTag commandTag, List *stmts, CachedPlan *cplan)
Definition portalmem.c:284
Portal CreatePortal(const char *name, bool allowDup, bool dupSilent)
Definition portalmem.c:177
void PortalErrorCleanup(void)
Definition portalmem.c:919
static void disable_statement_timeout(void)
Definition postgres.c:5304
int log_statement
Definition postgres.c:102
static bool IsTransactionStmtList(List *pstmts)
Definition postgres.c:2886
List * pg_analyze_and_rewrite_withcb(RawStmt *parsetree, const char *query_string, ParserSetupHook parserSetup, void *parserSetupArg, QueryEnvironment *queryEnv)
Definition postgres.c:774
void assign_transaction_timeout(int newval, void *extra)
Definition postgres.c:3664
List * pg_parse_query(const char *query_string)
Definition postgres.c:615
static bool check_log_statement(List *stmt_list)
Definition postgres.c:2397
static void exec_describe_statement_message(const char *stmt_name)
Definition postgres.c:2640
void assign_restrict_nonsystem_relation_kind(const char *newval, void *extra)
Definition postgres.c:3735
void process_postgres_switches(int argc, char *argv[], GucContext ctx, const char **dbname)
Definition postgres.c:3863
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:898
void quickdie(SIGNAL_ARGS)
Definition postgres.c:2926
static bool IsTransactionExitStmtList(List *pstmts)
Definition postgres.c:2871
static void log_disconnections(int code, Datum arg)
Definition postgres.c:5246
static void forbidden_in_wal_sender(char firstchar)
Definition postgres.c:5110
static void exec_execute_message(const char *portal_name, long max_rows)
Definition postgres.c:2121
static void report_recovery_conflict(RecoveryConflictReason reason)
Definition postgres.c:3193
void PostgresSingleUserMain(int argc, char *argv[], const char *username)
Definition postgres.c:4119
List * pg_plan_queries(List *querytrees, const char *query_string, int cursorOptions, ParamListInfo boundParams)
Definition postgres.c:986
void set_debug_options(int debug_flag, GucContext context, GucSource source)
Definition postgres.c:3749
static bool UseSemiNewlineNewline
Definition postgres.c:169
static CachedPlanSource * unnamed_stmt_psrc
Definition postgres.c:164
void FloatExceptionHandler(SIGNAL_ARGS)
Definition postgres.c:3070
int client_connection_check_interval
Definition postgres.c:108
bool check_log_stats(bool *newval, void **extra, GucSource source)
Definition postgres.c:3649
static bool EchoQuery
Definition postgres.c:168
void StatementCancelHandler(SIGNAL_ARGS)
Definition postgres.c:3053
CommandDest whereToSendOutput
Definition postgres.c:97
static bool ignore_till_sync
Definition postgres.c:157
static void ProcessRecoveryConflictInterrupt(RecoveryConflictReason reason)
Definition postgres.c:3097
static void finish_xact_command(void)
Definition postgres.c:2822
bool set_plan_disabling_options(const char *arg, GucContext context, GucSource source)
Definition postgres.c:3781
static void enable_statement_timeout(void)
Definition postgres.c:5282
List * pg_analyze_and_rewrite_fixedparams(RawStmt *parsetree, const char *query_string, const Oid *paramTypes, int numParams, QueryEnvironment *queryEnv)
Definition postgres.c:681
int check_log_duration(char *msec_str, bool was_logged)
Definition postgres.c:2436
static struct timeval Save_t
Definition postgres.c:5127
const char * debug_query_string
Definition postgres.c:94
static void exec_simple_query(const char *query_string)
Definition postgres.c:1028
const char * get_stats_option_name(const char *arg)
Definition postgres.c:3823
List * pg_rewrite_query(Query *query)
Definition postgres.c:814
static int errdetail_execute(List *raw_parsetree_list)
Definition postgres.c:2499
void ShowUsage(const char *title)
Definition postgres.c:5137
static void exec_parse_message(const char *query_string, const char *stmt_name, Oid *paramTypes, int numParams)
Definition postgres.c:1405
int restrict_nonsystem_relation_kind
Definition postgres.c:111
static const char * userDoption
Definition postgres.c:167
#define ERRDETAIL_SIGNAL_SENDER(pid, uid)
Definition postgres.c:117
static void exec_bind_message(StringInfo input_message)
Definition postgres.c:1639
static bool DoingCommandRead
Definition postgres.c:150
static bool xact_started
Definition postgres.c:143
static int errdetail_recovery_conflict(RecoveryConflictReason reason)
Definition postgres.c:2552
static int interactive_getc(void)
Definition postgres.c:336
static int errdetail_params(ParamListInfo params)
Definition postgres.c:2532
static void ProcessRecoveryConflictInterrupts(void)
Definition postgres.c:3299
static int SocketBackend(StringInfo inBuf)
Definition postgres.c:364
void ProcessClientReadInterrupt(bool blocked)
Definition postgres.c:513
void ProcessInterrupts(void)
Definition postgres.c:3350
static void bind_param_error_callback(void *arg)
Definition postgres.c:2591
static bool IsTransactionExitStmt(Node *parsetree)
Definition postgres.c:2854
void PostgresMain(const char *dbname, const char *username)
Definition postgres.c:4262
static MemoryContext row_description_context
Definition postgres.c:172
static int InteractiveBackend(StringInfo inBuf)
Definition postgres.c:248
static struct rusage Save_r
Definition postgres.c:5126
bool check_client_connection_check_interval(int *newval, void **extra, GucSource source)
Definition postgres.c:3614
static StringInfoData row_description_buf
Definition postgres.c:173
void ProcessClientWriteInterrupt(bool blocked)
Definition postgres.c:559
static bool doing_extended_query_message
Definition postgres.c:156
void ResetUsage(void)
Definition postgres.c:5130
static void start_xact_command(void)
Definition postgres.c:2783
bool check_restrict_nonsystem_relation_kind(char **newval, void **extra, GucSource source)
Definition postgres.c:3683
static void exec_describe_portal_message(const char *portal_name)
Definition postgres.c:2732
void HandleRecoveryConflictInterrupt(void)
Definition postgres.c:3086
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:720
static void drop_unnamed_stmt(void)
Definition postgres.c:2901
#define valgrind_report_error_query(query)
Definition postgres.c:228
static int ReadCommand(StringInfo inBuf)
Definition postgres.c:492
bool check_stage_log_stats(bool *newval, void **extra, GucSource source)
Definition postgres.c:3635
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:719
bool ClientAuthInProgress
Definition postmaster.c:373
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:146
void ProcessRepackMessages(void)
Definition repack.c:3515
int getrusage(int who, struct rusage *rusage)
#define RUSAGE_SELF
Definition resource.h:9
List * QueryRewrite(Query *parsetree)
void ShmemCallRequestCallbacks(void)
Definition shmem.c:979
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:1335
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:129
const char * paramval
Definition postgres.c:131
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:2384
LogStmtLevel GetCommandLogLevel(Node *parsetree)
Definition utility.c:3289
static uint64 TimestampDifferenceMicroseconds(TimestampTz start_time, TimestampTz stop_time)
Definition timestamp.h:90
#define NS_PER_US
Definition uuid.c:33
bool SplitIdentifierString(char *rawstring, char separator, List **namelist)
Definition varlena.c:2867
const char * name
bool WaitEventSetCanReportClosed(void)
void WalSndErrorCleanup(void)
Definition walsender.c:370
bool am_walsender
Definition walsender.c:135
bool exec_replication_command(const char *cmd_string)
Definition walsender.c:2058
void InitWalSender(void)
Definition walsender.c:323
void WalSndSignals(void)
Definition walsender.c:3892
#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:5188
void LocalProcessControlFile(bool reset)
Definition xlog.c:5269