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 * Record who sent the signal. Will be 0 on platforms without
3033 * SA_SIGINFO, which is fine -- ProcessInterrupts() checks for that.
3034 * Only set on the first SIGTERM so we report the original sender.
3035 */
3036 if (ProcDieSenderPid == 0)
3037 {
3040 }
3041 }
3042
3043 /* for the cumulative stats system */
3045
3046 /* If we're still here, waken anything waiting on the process latch */
3048
3049 /*
3050 * If we're in single user mode, we want to quit immediately - we can't
3051 * rely on latches as they wouldn't work when stdin/stdout is a file.
3052 * Rather ugly, but it's unlikely to be worthwhile to invest much more
3053 * effort just for the benefit of single user mode.
3054 */
3057}
3058
3059/*
3060 * Query-cancel signal from postmaster: abort current transaction
3061 * at soonest convenient time
3062 */
3063void
3065{
3066 /*
3067 * Don't joggle the elbow of proc_exit
3068 */
3070 {
3071 InterruptPending = true;
3072 QueryCancelPending = true;
3073 }
3074
3075 /* If we're still here, waken anything waiting on the process latch */
3077}
3078
3079/* signal handler for floating point exception */
3080void
3082{
3083 /* We're not returning, so no need to save errno */
3084 ereport(ERROR,
3086 errmsg("floating-point exception"),
3087 errdetail("An invalid floating-point operation was signaled. "
3088 "This probably means an out-of-range result or an "
3089 "invalid operation, such as division by zero.")));
3090}
3091
3092/*
3093 * Tell the next CHECK_FOR_INTERRUPTS() to process recovery conflicts. Runs
3094 * in a SIGUSR1 handler.
3095 */
3096void
3098{
3100 InterruptPending = true;
3101 /* latch will be set by procsignal_sigusr1_handler */
3102}
3103
3104/*
3105 * Check one individual conflict reason.
3106 */
3107static void
3109{
3110 switch (reason)
3111 {
3113
3114 /*
3115 * The startup process is waiting on a lock held by us, and has
3116 * requested us to check if it is a deadlock (i.e. the deadlock
3117 * timeout expired).
3118 *
3119 * If we aren't waiting for a lock we can never deadlock.
3120 */
3121 if (GetAwaitedLock() == NULL)
3122 return;
3123
3124 /* Set the flag so that ProcSleep() will check for deadlocks. */
3126 return;
3127
3129
3130 /*
3131 * The startup process is waiting on a buffer pin, and has
3132 * requested us to check if there is a deadlock involving the pin.
3133 *
3134 * If we're not waiting on a lock, there can be no deadlock.
3135 */
3136 if (GetAwaitedLock() == NULL)
3137 return;
3138
3139 /*
3140 * If we're not holding the buffer pin, also no deadlock. (The
3141 * startup process doesn't know who's holding the pin, and sends
3142 * this signal to *all* backends, so this is the common case.)
3143 */
3145 return;
3146
3147 /*
3148 * Otherwise, we probably have a deadlock. Unfortunately the
3149 * normal deadlock detector doesn't know about buffer pins, so we
3150 * cannot perform comprehensively deadlock check. Instead, we
3151 * just assume that it is a deadlock if the above two conditions
3152 * are met. In principle this can lead to false positives, but
3153 * it's rare in practice because sessions in a hot standby server
3154 * rarely hold locks that can block other backends.
3155 */
3157 return;
3158
3160
3161 /*
3162 * Someone is holding a buffer pin that the startup process is
3163 * waiting for, and it got tired of waiting. If that's us, error
3164 * out to release the pin.
3165 */
3167 return;
3168
3170 return;
3171
3175
3176 /*
3177 * If we aren't in a transaction any longer then ignore.
3178 */
3180 return;
3181
3183 return;
3184
3187 return;
3188
3190
3191 /* The database is being dropped; terminate the session */
3193 return;
3194 }
3195 elog(FATAL, "unrecognized conflict mode: %d", (int) reason);
3196}
3197
3198/*
3199 * This transaction or session is conflicting with recovery and needs to be
3200 * killed. Roll back the transaction, if that's sufficient, or terminate the
3201 * connection, or do nothing if we're already in an aborted state.
3202 */
3203static void
3205{
3206 bool fatal;
3207
3208 if (reason == RECOVERY_CONFLICT_DATABASE)
3209 {
3210 /* note: no hint about reconnecting, and different errcode */
3212 ereport(FATAL,
3214 errmsg("terminating connection due to conflict with recovery"),
3216 }
3217 if (reason == RECOVERY_CONFLICT_LOGICALSLOT)
3218 {
3219 /*
3220 * RECOVERY_CONFLICT_LOGICALSLOT is a special case that always throws
3221 * an ERROR (ie never promotes to FATAL), though it still has to
3222 * respect QueryCancelHoldoffCount, so it shares this code path.
3223 * Logical decoding slots are only acquired while performing logical
3224 * decoding. During logical decoding no user controlled code is run.
3225 * During [sub]transaction abort, the slot is released. Therefore
3226 * user controlled code cannot intercept an error before the
3227 * replication slot is released.
3228 */
3229 fatal = false;
3230 }
3231 else
3232 {
3234 }
3235
3236 /*
3237 * If we're not in a subtransaction then we are OK to throw an ERROR to
3238 * resolve the conflict.
3239 *
3240 * XXX other times that we can throw just an ERROR *may* be
3241 * RECOVERY_CONFLICT_LOCK if no locks are held in parent transactions
3242 *
3243 * RECOVERY_CONFLICT_SNAPSHOT if no snapshots are held by parent
3244 * transactions and the transaction is not transaction-snapshot mode
3245 *
3246 * RECOVERY_CONFLICT_TABLESPACE if no temp files or cursors open in parent
3247 * transactions
3248 */
3249 if (!fatal)
3250 {
3251 /*
3252 * If we already aborted then we no longer need to cancel. We do this
3253 * here since we do not wish to ignore aborted subtransactions, which
3254 * must cause FATAL, currently.
3255 */
3257 return;
3258
3259 /*
3260 * If a recovery conflict happens while we are waiting for input from
3261 * the client, the client is presumably just sitting idle in a
3262 * transaction, preventing recovery from making progress. We'll drop
3263 * through to the FATAL case below to dislodge it, in that case.
3264 */
3265 if (!DoingCommandRead)
3266 {
3267 /* Avoid losing sync in the FE/BE protocol. */
3268 if (QueryCancelHoldoffCount != 0)
3269 {
3270 /*
3271 * Re-arm and defer this interrupt until later. See similar
3272 * code in ProcessInterrupts().
3273 */
3275 InterruptPending = true;
3276 return;
3277 }
3278
3279 /*
3280 * We are cleared to throw an ERROR. Either it's the logical slot
3281 * case, or we have a top-level transaction that we can abort and
3282 * a conflict that isn't inherently non-retryable.
3283 */
3286 ereport(ERROR,
3288 errmsg("canceling statement due to conflict with recovery"),
3290 }
3291 }
3292
3293 /*
3294 * We couldn't resolve the conflict with ERROR, so terminate the whole
3295 * session.
3296 */
3298 ereport(FATAL,
3300 errmsg("terminating connection due to conflict with recovery"),
3302 errhint("In a moment you should be able to reconnect to the"
3303 " database and repeat your command.")));
3304}
3305
3306/*
3307 * Check each possible recovery conflict reason.
3308 */
3309static void
3311{
3312 uint32 pending;
3313
3314 /*
3315 * We don't need to worry about joggling the elbow of proc_exit, because
3316 * proc_exit_prepare() holds interrupts, so ProcessInterrupts() won't call
3317 * us.
3318 */
3321
3322 /* Are any recovery conflict pending? */
3324 if (pending == 0)
3325 return;
3326
3327 /*
3328 * Check the conflicts one by one, clearing each flag only before
3329 * processing the particular conflict. This ensures that if multiple
3330 * conflicts are pending, we come back here to process the remaining
3331 * conflicts, if an error is thrown during processing one of them.
3332 */
3333 for (RecoveryConflictReason reason = 0;
3335 reason++)
3336 {
3337 if ((pending & (1 << reason)) != 0)
3338 {
3339 /* clear the flag */
3341
3343 }
3344 }
3345}
3346
3347/*
3348 * ProcessInterrupts: out-of-line portion of CHECK_FOR_INTERRUPTS() macro
3349 *
3350 * If an interrupt condition is pending, and it's safe to service it,
3351 * then clear the flag and accept the interrupt. Called only when
3352 * InterruptPending is true.
3353 *
3354 * Note: if INTERRUPTS_CAN_BE_PROCESSED() is true, then ProcessInterrupts
3355 * is guaranteed to clear the InterruptPending flag before returning.
3356 * (This is not the same as guaranteeing that it's still clear when we
3357 * return; another interrupt could have arrived. But we promise that
3358 * any pre-existing one will have been serviced.)
3359 */
3360void
3362{
3363 /* OK to accept any interrupts now? */
3364 if (InterruptHoldoffCount != 0 || CritSectionCount != 0)
3365 return;
3366 InterruptPending = false;
3367
3368 if (ProcDiePending)
3369 {
3372
3373 ProcDiePending = false;
3374 ProcDieSenderPid = 0;
3375 ProcDieSenderUid = 0;
3376 QueryCancelPending = false; /* ProcDie trumps QueryCancel */
3378 /* As in quickdie, don't risk sending to client during auth */
3382 ereport(FATAL,
3384 errmsg("canceling authentication due to timeout")));
3385 else if (AmAutoVacuumWorkerProcess())
3386 ereport(FATAL,
3388 errmsg("terminating autovacuum process due to administrator command"),
3390 else if (IsLogicalWorker())
3391 ereport(FATAL,
3393 errmsg("terminating logical replication worker due to administrator command"),
3395 else if (IsLogicalLauncher())
3396 {
3398 (errmsg_internal("logical replication launcher shutting down"),
3400
3401 /*
3402 * The logical replication launcher can be stopped at any time.
3403 * Use exit status 1 so the background worker is restarted.
3404 */
3405 proc_exit(1);
3406 }
3407 else if (AmWalReceiverProcess())
3408 ereport(FATAL,
3410 errmsg("terminating walreceiver process due to administrator command"),
3412 else if (AmBackgroundWorkerProcess())
3413 ereport(FATAL,
3415 errmsg("terminating background worker \"%s\" due to administrator command",
3418 else if (AmIoWorkerProcess())
3419 {
3421 (errmsg_internal("io worker shutting down due to administrator command"),
3423
3424 proc_exit(0);
3425 }
3426 else
3427 ereport(FATAL,
3429 errmsg("terminating connection due to administrator command"),
3431 }
3432
3434 {
3436
3437 /*
3438 * Check for lost connection and re-arm, if still configured, but not
3439 * if we've arrived back at DoingCommandRead state. We don't want to
3440 * wake up idle sessions, and they already know how to detect lost
3441 * connections.
3442 */
3444 {
3445 if (!pq_check_connection())
3446 ClientConnectionLost = true;
3447 else
3450 }
3451 }
3452
3454 {
3455 QueryCancelPending = false; /* lost connection trumps QueryCancel */
3457 /* don't send to client, we already know the connection to be dead. */
3459 ereport(FATAL,
3461 errmsg("connection to client lost")));
3462 }
3463
3464 /*
3465 * Don't allow query cancel interrupts while reading input from the
3466 * client, because we might lose sync in the FE/BE protocol. (Die
3467 * interrupts are OK, because we won't read any further messages from the
3468 * client in that case.)
3469 *
3470 * See similar logic in ProcessRecoveryConflictInterrupts().
3471 */
3473 {
3474 /*
3475 * Re-arm InterruptPending so that we process the cancel request as
3476 * soon as we're done reading the message. (XXX this is seriously
3477 * ugly: it complicates INTERRUPTS_CAN_BE_PROCESSED(), and it means we
3478 * can't use that macro directly as the initial test in this function,
3479 * meaning that this code also creates opportunities for other bugs to
3480 * appear.)
3481 */
3482 InterruptPending = true;
3483 }
3484 else if (QueryCancelPending)
3485 {
3488
3489 QueryCancelPending = false;
3490
3491 /*
3492 * If LOCK_TIMEOUT and STATEMENT_TIMEOUT indicators are both set, we
3493 * need to clear both, so always fetch both.
3494 */
3497
3498 /*
3499 * If both were set, we want to report whichever timeout completed
3500 * earlier; this ensures consistent behavior if the machine is slow
3501 * enough that the second timeout triggers before we get here. A tie
3502 * is arbitrarily broken in favor of reporting a lock timeout.
3503 */
3506 lock_timeout_occurred = false; /* report stmt timeout */
3507
3509 {
3511 ereport(ERROR,
3513 errmsg("canceling statement due to lock timeout")));
3514 }
3516 {
3518 ereport(ERROR,
3520 errmsg("canceling statement due to statement timeout")));
3521 }
3523 {
3525 ereport(ERROR,
3527 errmsg("canceling autovacuum task")));
3528 }
3529
3530 /*
3531 * If we are reading a command from the client, just ignore the cancel
3532 * request --- sending an extra error message won't accomplish
3533 * anything. Otherwise, go ahead and throw the error.
3534 */
3535 if (!DoingCommandRead)
3536 {
3538 ereport(ERROR,
3540 errmsg("canceling statement due to user request")));
3541 }
3542 }
3543
3546
3548 {
3549 /*
3550 * If the GUC has been reset to zero, ignore the signal. This is
3551 * important because the GUC update itself won't disable any pending
3552 * interrupt. We need to unset the flag before the injection point,
3553 * otherwise we could loop in interrupts checking.
3554 */
3557 {
3558 INJECTION_POINT("idle-in-transaction-session-timeout", NULL);
3559 ereport(FATAL,
3561 errmsg("terminating connection due to idle-in-transaction timeout")));
3562 }
3563 }
3564
3566 {
3567 /* As above, ignore the signal if the GUC has been reset to zero. */
3569 if (TransactionTimeout > 0)
3570 {
3571 INJECTION_POINT("transaction-timeout", NULL);
3572 ereport(FATAL,
3574 errmsg("terminating connection due to transaction timeout")));
3575 }
3576 }
3577
3579 {
3580 /* As above, ignore the signal if the GUC has been reset to zero. */
3582 if (IdleSessionTimeout > 0)
3583 {
3584 INJECTION_POINT("idle-session-timeout", NULL);
3585 ereport(FATAL,
3587 errmsg("terminating connection due to idle-session timeout")));
3588 }
3589 }
3590
3591 /*
3592 * If there are pending stats updates and we currently are truly idle
3593 * (matching the conditions in PostgresMain(), report stats now.
3594 */
3597 {
3599 pgstat_report_stat(true);
3600 }
3601
3604
3607
3610
3613
3616
3619}
3620
3621/*
3622 * GUC check_hook for client_connection_check_interval
3623 */
3624bool
3626{
3627 if (!WaitEventSetCanReportClosed() && *newval != 0)
3628 {
3629 GUC_check_errdetail("\"client_connection_check_interval\" must be set to 0 on this platform.");
3630 return false;
3631 }
3632 return true;
3633}
3634
3635/*
3636 * GUC check_hook for log_parser_stats, log_planner_stats, log_executor_stats
3637 *
3638 * This function and check_log_stats interact to prevent their variables from
3639 * being set in a disallowed combination. This is a hack that doesn't really
3640 * work right; for example it might fail while applying pg_db_role_setting
3641 * values even though the final state would have been acceptable. However,
3642 * since these variables are legacy settings with little production usage,
3643 * we tolerate that.
3644 */
3645bool
3647{
3649 {
3650 GUC_check_errdetail("Cannot enable parameter when \"log_statement_stats\" is true.");
3651 return false;
3652 }
3653 return true;
3654}
3655
3656/*
3657 * GUC check_hook for log_statement_stats
3658 */
3659bool
3661{
3662 if (*newval &&
3664 {
3665 GUC_check_errdetail("Cannot enable \"log_statement_stats\" when "
3666 "\"log_parser_stats\", \"log_planner_stats\", "
3667 "or \"log_executor_stats\" is true.");
3668 return false;
3669 }
3670 return true;
3671}
3672
3673/* GUC assign hook for transaction_timeout */
3674void
3676{
3677 if (IsTransactionState())
3678 {
3679 /*
3680 * If transaction_timeout GUC has changed within the transaction block
3681 * enable or disable the timer correspondingly.
3682 */
3687 }
3688}
3689
3690/*
3691 * GUC check_hook for restrict_nonsystem_relation_kind
3692 */
3693bool
3695{
3696 char *rawstring;
3697 List *elemlist;
3698 ListCell *l;
3699 int flags = 0;
3700
3701 /* Need a modifiable copy of string */
3703
3705 {
3706 /* syntax error in list */
3707 GUC_check_errdetail("List syntax is invalid.");
3710 return false;
3711 }
3712
3713 foreach(l, elemlist)
3714 {
3715 char *tok = (char *) lfirst(l);
3716
3717 if (pg_strcasecmp(tok, "view") == 0)
3718 flags |= RESTRICT_RELKIND_VIEW;
3719 else if (pg_strcasecmp(tok, "foreign-table") == 0)
3721 else
3722 {
3723 GUC_check_errdetail("Unrecognized key word: \"%s\".", tok);
3726 return false;
3727 }
3728 }
3729
3732
3733 /* Save the flags in *extra, for use by the assign function */
3734 *extra = guc_malloc(LOG, sizeof(int));
3735 if (!*extra)
3736 return false;
3737 *((int *) *extra) = flags;
3738
3739 return true;
3740}
3741
3742/*
3743 * GUC assign_hook for restrict_nonsystem_relation_kind
3744 */
3745void
3747{
3748 int *flags = (int *) extra;
3749
3751}
3752
3753/*
3754 * set_debug_options --- apply "-d N" command line option
3755 *
3756 * -d is not quite the same as setting log_min_messages because it enables
3757 * other output options.
3758 */
3759void
3761{
3762 if (debug_flag > 0)
3763 {
3764 char debugstr[64];
3765
3766 sprintf(debugstr, "debug%d", debug_flag);
3767 SetConfigOption("log_min_messages", debugstr, context, source);
3768 }
3769 else
3770 SetConfigOption("log_min_messages", "notice", context, source);
3771
3772 if (debug_flag >= 1 && context == PGC_POSTMASTER)
3773 {
3774 SetConfigOption("log_connections", "all", context, source);
3775 SetConfigOption("log_disconnections", "true", context, source);
3776 }
3777 if (debug_flag >= 2)
3778 SetConfigOption("log_statement", "all", context, source);
3779 if (debug_flag >= 3)
3780 {
3781 SetConfigOption("debug_print_raw_parse", "true", context, source);
3782 SetConfigOption("debug_print_parse", "true", context, source);
3783 }
3784 if (debug_flag >= 4)
3785 SetConfigOption("debug_print_plan", "true", context, source);
3786 if (debug_flag >= 5)
3787 SetConfigOption("debug_print_rewritten", "true", context, source);
3788}
3789
3790
3791bool
3793{
3794 const char *tmp = NULL;
3795
3796 switch (arg[0])
3797 {
3798 case 's': /* seqscan */
3799 tmp = "enable_seqscan";
3800 break;
3801 case 'i': /* indexscan */
3802 tmp = "enable_indexscan";
3803 break;
3804 case 'o': /* indexonlyscan */
3805 tmp = "enable_indexonlyscan";
3806 break;
3807 case 'b': /* bitmapscan */
3808 tmp = "enable_bitmapscan";
3809 break;
3810 case 't': /* tidscan */
3811 tmp = "enable_tidscan";
3812 break;
3813 case 'n': /* nestloop */
3814 tmp = "enable_nestloop";
3815 break;
3816 case 'm': /* mergejoin */
3817 tmp = "enable_mergejoin";
3818 break;
3819 case 'h': /* hashjoin */
3820 tmp = "enable_hashjoin";
3821 break;
3822 }
3823 if (tmp)
3824 {
3825 SetConfigOption(tmp, "false", context, source);
3826 return true;
3827 }
3828 else
3829 return false;
3830}
3831
3832
3833const char *
3835{
3836 switch (arg[0])
3837 {
3838 case 'p':
3839 if (arg[1] == 'a') /* "parser" */
3840 return "log_parser_stats";
3841 else if (arg[1] == 'l') /* "planner" */
3842 return "log_planner_stats";
3843 break;
3844
3845 case 'e': /* "executor" */
3846 return "log_executor_stats";
3847 break;
3848 }
3849
3850 return NULL;
3851}
3852
3853
3854/* ----------------------------------------------------------------
3855 * process_postgres_switches
3856 * Parse command line arguments for backends
3857 *
3858 * This is called twice, once for the "secure" options coming from the
3859 * postmaster or command line, and once for the "insecure" options coming
3860 * from the client's startup packet. The latter have the same syntax but
3861 * may be restricted in what they can do.
3862 *
3863 * argv[0] is ignored in either case (it's assumed to be the program name).
3864 *
3865 * ctx is PGC_POSTMASTER for secure options, PGC_BACKEND for insecure options
3866 * coming from the client, or PGC_SU_BACKEND for insecure options coming from
3867 * a superuser client.
3868 *
3869 * If a database name is present in the command line arguments, it's
3870 * returned into *dbname (this is allowed only if *dbname is initially NULL).
3871 * ----------------------------------------------------------------
3872 */
3873void
3874process_postgres_switches(int argc, char *argv[], GucContext ctx,
3875 const char **dbname)
3876{
3877 bool secure = (ctx == PGC_POSTMASTER);
3878 int errs = 0;
3880 int flag;
3882
3883 if (secure)
3884 {
3885 gucsource = PGC_S_ARGV; /* switches came from command line */
3886
3887 /* Ignore the initial --single argument, if present */
3888 if (argc > 1 && strcmp(argv[1], "--single") == 0)
3889 {
3890 argv++;
3891 argc--;
3892 }
3893 }
3894 else
3895 {
3896 gucsource = PGC_S_CLIENT; /* switches came from client */
3897 }
3898
3899 /*
3900 * Parse command-line options. CAUTION: keep this in sync with
3901 * postmaster/postmaster.c (the option sets should not conflict) and with
3902 * the common help() function in main/main.c.
3903 */
3904 pg_getopt_start(&optctx, argc, argv, "B:bC:c:D:d:EeFf:h:ijk:lN:nOPp:r:S:sTt:v:W:-:");
3905
3906 /*
3907 * Turn this off because it's either printed to stderr and not the log
3908 * where we'd want it, or argv[0] is now "--single", which would make for
3909 * a weird error message. We print our own error message below.
3910 */
3911 optctx.opterr = 0;
3912
3913 while ((flag = pg_getopt_next(&optctx)) != -1)
3914 {
3915 switch (flag)
3916 {
3917 case 'B':
3918 SetConfigOption("shared_buffers", optctx.optarg, ctx, gucsource);
3919 break;
3920
3921 case 'b':
3922 /* Undocumented flag used for binary upgrades */
3923 if (secure)
3924 IsBinaryUpgrade = true;
3925 break;
3926
3927 case 'C':
3928 /* ignored for consistency with the postmaster */
3929 break;
3930
3931 case '-':
3932
3933 /*
3934 * Error if the user misplaced a special must-be-first option
3935 * for dispatching to a subprogram. parse_dispatch_option()
3936 * returns DISPATCH_POSTMASTER if it doesn't find a match, so
3937 * error for anything else.
3938 */
3940 ereport(ERROR,
3942 errmsg("--%s must be first argument", optctx.optarg)));
3943
3945 case 'c':
3946 {
3947 char *name,
3948 *value;
3949
3950 ParseLongOption(optctx.optarg, &name, &value);
3951 if (!value)
3952 {
3953 if (flag == '-')
3954 ereport(ERROR,
3956 errmsg("--%s requires a value",
3957 optctx.optarg)));
3958 else
3959 ereport(ERROR,
3961 errmsg("-c %s requires a value",
3962 optctx.optarg)));
3963 }
3965 pfree(name);
3966 pfree(value);
3967 break;
3968 }
3969
3970 case 'D':
3971 if (secure)
3972 userDoption = strdup(optctx.optarg);
3973 break;
3974
3975 case 'd':
3976 set_debug_options(atoi(optctx.optarg), ctx, gucsource);
3977 break;
3978
3979 case 'E':
3980 if (secure)
3981 EchoQuery = true;
3982 break;
3983
3984 case 'e':
3985 SetConfigOption("datestyle", "euro", ctx, gucsource);
3986 break;
3987
3988 case 'F':
3989 SetConfigOption("fsync", "false", ctx, gucsource);
3990 break;
3991
3992 case 'f':
3993 if (!set_plan_disabling_options(optctx.optarg, ctx, gucsource))
3994 errs++;
3995 break;
3996
3997 case 'h':
3998 SetConfigOption("listen_addresses", optctx.optarg, ctx, gucsource);
3999 break;
4000
4001 case 'i':
4002 SetConfigOption("listen_addresses", "*", ctx, gucsource);
4003 break;
4004
4005 case 'j':
4006 if (secure)
4007 UseSemiNewlineNewline = true;
4008 break;
4009
4010 case 'k':
4011 SetConfigOption("unix_socket_directories", optctx.optarg, ctx, gucsource);
4012 break;
4013
4014 case 'l':
4015 SetConfigOption("ssl", "true", ctx, gucsource);
4016 break;
4017
4018 case 'N':
4019 SetConfigOption("max_connections", optctx.optarg, ctx, gucsource);
4020 break;
4021
4022 case 'n':
4023 /* ignored for consistency with postmaster */
4024 break;
4025
4026 case 'O':
4027 SetConfigOption("allow_system_table_mods", "true", ctx, gucsource);
4028 break;
4029
4030 case 'P':
4031 SetConfigOption("ignore_system_indexes", "true", ctx, gucsource);
4032 break;
4033
4034 case 'p':
4035 SetConfigOption("port", optctx.optarg, ctx, gucsource);
4036 break;
4037
4038 case 'r':
4039 /* send output (stdout and stderr) to the given file */
4040 if (secure)
4042 break;
4043
4044 case 'S':
4045 SetConfigOption("work_mem", optctx.optarg, ctx, gucsource);
4046 break;
4047
4048 case 's':
4049 SetConfigOption("log_statement_stats", "true", ctx, gucsource);
4050 break;
4051
4052 case 'T':
4053 /* ignored for consistency with the postmaster */
4054 break;
4055
4056 case 't':
4057 {
4058 const char *tmp = get_stats_option_name(optctx.optarg);
4059
4060 if (tmp)
4061 SetConfigOption(tmp, "true", ctx, gucsource);
4062 else
4063 errs++;
4064 break;
4065 }
4066
4067 case 'v':
4068
4069 /*
4070 * -v is no longer used in normal operation, since
4071 * FrontendProtocol is already set before we get here. We keep
4072 * the switch only for possible use in standalone operation,
4073 * in case we ever support using normal FE/BE protocol with a
4074 * standalone backend.
4075 */
4076 if (secure)
4078 break;
4079
4080 case 'W':
4081 SetConfigOption("post_auth_delay", optctx.optarg, ctx, gucsource);
4082 break;
4083
4084 default:
4085 errs++;
4086 break;
4087 }
4088
4089 if (errs)
4090 break;
4091 }
4092
4093 /*
4094 * Optional database name should be there only if *dbname is NULL.
4095 */
4096 if (!errs && dbname && *dbname == NULL && argc - optctx.optind >= 1)
4097 *dbname = strdup(argv[optctx.optind++]);
4098
4099 if (errs || argc != optctx.optind)
4100 {
4101 if (errs)
4102 optctx.optind--; /* complain about the previous argument */
4103
4104 /* spell the error message a bit differently depending on context */
4106 ereport(FATAL,
4108 errmsg("invalid command-line argument for server process: %s", argv[optctx.optind]),
4109 errhint("Try \"%s --help\" for more information.", progname));
4110 else
4111 ereport(FATAL,
4113 errmsg("%s: invalid command-line argument: %s",
4114 progname, argv[optctx.optind]),
4115 errhint("Try \"%s --help\" for more information.", progname));
4116 }
4117}
4118
4119
4120/*
4121 * PostgresSingleUserMain
4122 * Entry point for single user mode. argc/argv are the command line
4123 * arguments to be used.
4124 *
4125 * Performs single user specific setup then calls PostgresMain() to actually
4126 * process queries. Single user mode specific setup should go here, rather
4127 * than PostgresMain() or InitPostgres() when reasonably possible.
4128 */
4129void
4130PostgresSingleUserMain(int argc, char *argv[],
4131 const char *username)
4132{
4133 const char *dbname = NULL;
4134
4136
4137 /* Initialize startup process environment. */
4138 InitStandaloneProcess(argv[0]);
4139
4140 /*
4141 * Set default values for command-line options.
4142 */
4144
4145 /*
4146 * Parse command-line options.
4147 */
4149
4150 /* Must have gotten a database name, or have a default (the username) */
4151 if (dbname == NULL)
4152 {
4153 dbname = username;
4154 if (dbname == NULL)
4155 ereport(FATAL,
4157 errmsg("%s: no database nor user name specified",
4158 progname)));
4159 }
4160
4161 /* Acquire configuration parameters */
4163 proc_exit(1);
4164
4165 /*
4166 * Validate we have been given a reasonable-looking DataDir and change
4167 * into it.
4168 */
4169 checkDataDir();
4171
4172 /*
4173 * Create lockfile for data directory.
4174 */
4175 CreateDataDirLockFile(false);
4176
4177 /* read control file (error checking and contains config ) */
4179
4180 /* Register the shared memory needs of all core subsystems. */
4182
4183 /*
4184 * process any libraries that should be preloaded at postmaster start
4185 */
4187
4188 /* Initialize MaxBackends */
4190
4191 /*
4192 * We don't need postmaster child slots in single-user mode, but
4193 * initialize them anyway to avoid having special handling.
4194 */
4196
4197 /* Initialize size of fast-path lock cache. */
4199
4200 /*
4201 * Also call any legacy shmem request hooks that might'be been installed
4202 * by preloaded libraries.
4203 *
4204 * Note: this must be done before ShmemCallRequestCallbacks(), because the
4205 * hooks may request LWLocks with RequestNamedLWLockTranche(), which in
4206 * turn affects the size of the LWLock array calculated in lwlock.c.
4207 */
4209
4210 /*
4211 * Before computing the total size needed, give all subsystems, including
4212 * add-ins, a chance to chance to adjust their requested shmem sizes.
4213 */
4215
4216 /*
4217 * Now that loadable modules have had their chance to request additional
4218 * shared memory, determine the value of any runtime-computed GUCs that
4219 * depend on the amount of shared memory required.
4220 */
4222
4223 /*
4224 * Now that modules have been loaded, we can process any custom resource
4225 * managers specified in the wal_consistency_checking GUC.
4226 */
4228
4229 /*
4230 * Create shared memory etc. (Nothing's really "shared" in single-user
4231 * mode, but we must have these data structures anyway.)
4232 */
4234
4235 /*
4236 * Estimate number of openable files. This must happen after setting up
4237 * semaphores, because on some platforms semaphores count as open files.
4238 */
4240
4241 /*
4242 * Remember stand-alone backend startup time,roughly at the same point
4243 * during startup that postmaster does so.
4244 */
4246
4247 /*
4248 * Create a per-backend PGPROC struct in shared memory. We must do this
4249 * before we can use LWLocks.
4250 */
4251 InitProcess();
4252
4253 /*
4254 * Now that sufficient infrastructure has been initialized, PostgresMain()
4255 * can do the rest.
4256 */
4258}
4259
4260
4261/* ----------------------------------------------------------------
4262 * PostgresMain
4263 * postgres main loop -- all backends, interactive or otherwise loop here
4264 *
4265 * dbname is the name of the database to connect to, username is the
4266 * PostgreSQL user name to be used for the session.
4267 *
4268 * NB: Single user mode specific setup should go to PostgresSingleUserMain()
4269 * if reasonably possible.
4270 * ----------------------------------------------------------------
4271 */
4272void
4273PostgresMain(const char *dbname, const char *username)
4274{
4276
4277 /* these must be volatile to ensure state is preserved across longjmp: */
4278 volatile bool send_ready_for_query = true;
4279 volatile bool idle_in_transaction_timeout_enabled = false;
4280 volatile bool idle_session_timeout_enabled = false;
4281
4282 Assert(dbname != NULL);
4283 Assert(username != NULL);
4284
4286
4287 /*
4288 * Set up signal handlers. (InitPostmasterChild or InitStandaloneProcess
4289 * has already set up BlockSig and made that the active signal mask.)
4290 *
4291 * Note that postmaster blocked all signals before forking child process,
4292 * so there is no race condition whereby we might receive a signal before
4293 * we have set up the handler.
4294 *
4295 * Also note: it's best not to use any signals that are SIG_IGNored in the
4296 * postmaster. If such a signal arrives before we are able to change the
4297 * handler to non-SIG_IGN, it'll get dropped. Instead, make a dummy
4298 * handler in the postmaster to reserve the signal. (Of course, this isn't
4299 * an issue for signals that are locally generated, such as SIGALRM and
4300 * SIGPIPE.)
4301 */
4302 if (am_walsender)
4303 WalSndSignals();
4304 else
4305 {
4307 pqsignal(SIGINT, StatementCancelHandler); /* cancel current query */
4308 pqsignal(SIGTERM, die); /* cancel current query and exit */
4309
4310 /*
4311 * In a postmaster child backend, replace SignalHandlerForCrashExit
4312 * with quickdie, so we can tell the client we're dying.
4313 *
4314 * In a standalone backend, SIGQUIT can be generated from the keyboard
4315 * easily, while SIGTERM cannot, so we make both signals do die()
4316 * rather than quickdie().
4317 */
4319 pqsignal(SIGQUIT, quickdie); /* hard crash time */
4320 else
4321 pqsignal(SIGQUIT, die); /* cancel current query and exit */
4322 InitializeTimeouts(); /* establishes SIGALRM handler */
4323
4324 /*
4325 * Ignore failure to write to frontend. Note: if frontend closes
4326 * connection, we will notice it and exit cleanly when control next
4327 * returns to outer loop. This seems safer than forcing exit in the
4328 * midst of output during who-knows-what operation...
4329 */
4334
4335 /*
4336 * Reset some signals that are accepted by postmaster but not by
4337 * backend
4338 */
4339 pqsignal(SIGCHLD, PG_SIG_DFL); /* system() requires this on some
4340 * platforms */
4341 }
4342
4343 /* Early initialization */
4344 BaseInit();
4345
4346 /* We need to allow SIGINT, etc during the initial transaction */
4348
4349 /*
4350 * Generate a random cancel key, if this is a backend serving a
4351 * connection. InitPostgres() will advertise it in shared memory.
4352 */
4355 {
4356 int len;
4357
4358 len = (MyProcPort == NULL || MyProcPort->proto >= PG_PROTOCOL(3, 2))
4361 {
4362 ereport(ERROR,
4364 errmsg("could not generate random cancel key")));
4365 }
4367 }
4368
4369 /*
4370 * General initialization.
4371 *
4372 * NOTE: if you are tempted to add code in this vicinity, consider putting
4373 * it inside InitPostgres() instead. In particular, anything that
4374 * involves database access should be there, not here.
4375 *
4376 * Honor session_preload_libraries if not dealing with a WAL sender.
4377 */
4378 InitPostgres(dbname, InvalidOid, /* database to connect to */
4379 username, InvalidOid, /* role to connect as */
4381 NULL); /* no out_dbname */
4382
4383 /*
4384 * If the PostmasterContext is still around, recycle the space; we don't
4385 * need it anymore after InitPostgres completes.
4386 */
4388 {
4391 }
4392
4394
4395 /*
4396 * Now all GUC states are fully set up. Report them to client if
4397 * appropriate.
4398 */
4400
4401 /*
4402 * Also set up handler to log session end; we have to wait till now to be
4403 * sure Log_disconnections has its final value.
4404 */
4407
4409
4410 /* Perform initialization specific to a WAL sender process. */
4411 if (am_walsender)
4412 InitWalSender();
4413
4414 /*
4415 * Send this backend's cancellation info to the frontend.
4416 */
4418 {
4420
4424
4427 /* Need not flush since ReadyForQuery will do it. */
4428 }
4429
4430 /* Welcome banner for standalone case */
4432 printf("\nPostgreSQL stand-alone backend %s\n", PG_VERSION);
4433
4434 /*
4435 * Create the memory context we will use in the main loop.
4436 *
4437 * MessageContext is reset once per iteration of the main loop, ie, upon
4438 * completion of processing of each command message from the client.
4439 */
4441 "MessageContext",
4443
4444 /*
4445 * Create memory context and buffer used for RowDescription messages. As
4446 * SendRowDescriptionMessage(), via exec_describe_statement_message(), is
4447 * frequently executed for every single statement, we don't want to
4448 * allocate a separate buffer every time.
4449 */
4451 "RowDescriptionContext",
4456
4457 /* Fire any defined login event triggers, if appropriate */
4459
4460 /*
4461 * POSTGRES main processing loop begins here
4462 *
4463 * If an exception is encountered, processing resumes here so we abort the
4464 * current transaction and start a new one.
4465 *
4466 * You might wonder why this isn't coded as an infinite loop around a
4467 * PG_TRY construct. The reason is that this is the bottom of the
4468 * exception stack, and so with PG_TRY there would be no exception handler
4469 * in force at all during the CATCH part. By leaving the outermost setjmp
4470 * always active, we have at least some chance of recovering from an error
4471 * during error recovery. (If we get into an infinite loop thereby, it
4472 * will soon be stopped by overflow of elog.c's internal state stack.)
4473 *
4474 * Note that we use sigsetjmp(..., 1), so that this function's signal mask
4475 * (to wit, UnBlockSig) will be restored when longjmp'ing to here. This
4476 * is essential in case we longjmp'd out of a signal handler on a platform
4477 * where that leaves the signal blocked. It's not redundant with the
4478 * unblock in AbortTransaction() because the latter is only called if we
4479 * were inside a transaction.
4480 */
4481
4482 if (sigsetjmp(local_sigjmp_buf, 1) != 0)
4483 {
4484 /*
4485 * NOTE: if you are tempted to add more code in this if-block,
4486 * consider the high probability that it should be in
4487 * AbortTransaction() instead. The only stuff done directly here
4488 * should be stuff that is guaranteed to apply *only* for outer-level
4489 * error recovery, such as adjusting the FE/BE protocol status.
4490 */
4491
4492 /* Since not using PG_TRY, must reset error stack by hand */
4494
4495 /* Prevent interrupts while cleaning up */
4497
4498 /*
4499 * Forget any pending QueryCancel request, since we're returning to
4500 * the idle loop anyway, and cancel any active timeout requests. (In
4501 * future we might want to allow some timeout requests to survive, but
4502 * at minimum it'd be necessary to do reschedule_timeouts(), in case
4503 * we got here because of a query cancel interrupting the SIGALRM
4504 * interrupt handler.) Note in particular that we must clear the
4505 * statement and lock timeout indicators, to prevent any future plain
4506 * query cancels from being misreported as timeouts in case we're
4507 * forgetting a timeout cancel.
4508 */
4509 disable_all_timeouts(false); /* do first to avoid race condition */
4510 QueryCancelPending = false;
4513
4514 /* Not reading from the client anymore. */
4515 DoingCommandRead = false;
4516
4517 /* Make sure libpq is in a good state */
4518 pq_comm_reset();
4519
4520 /* Report the error to the client and/or server log */
4522
4523 /*
4524 * If Valgrind noticed something during the erroneous query, print the
4525 * query string, assuming we have one.
4526 */
4528
4529 /*
4530 * Make sure debug_query_string gets reset before we possibly clobber
4531 * the storage it points at.
4532 */
4534
4535 /*
4536 * Abort the current transaction in order to recover.
4537 */
4539
4540 if (am_walsender)
4542
4544
4545 /*
4546 * We can't release replication slots inside AbortTransaction() as we
4547 * need to be able to start and abort transactions while having a slot
4548 * acquired. But we never need to hold them across top level errors,
4549 * so releasing here is fine. There also is a before_shmem_exit()
4550 * callback ensuring correct cleanup on FATAL errors.
4551 */
4552 if (MyReplicationSlot != NULL)
4554
4555 /* We also want to cleanup temporary slots on error. */
4557
4559
4560 /*
4561 * Now return to normal top-level context and clear ErrorContext for
4562 * next time.
4563 */
4566
4567 /*
4568 * If we were handling an extended-query-protocol message, initiate
4569 * skip till next Sync. This also causes us not to issue
4570 * ReadyForQuery (until we get Sync).
4571 */
4573 ignore_till_sync = true;
4574
4575 /* We don't have a transaction command open anymore */
4576 xact_started = false;
4577
4578 /*
4579 * If an error occurred while we were reading a message from the
4580 * client, we have potentially lost track of where the previous
4581 * message ends and the next one begins. Even though we have
4582 * otherwise recovered from the error, we cannot safely read any more
4583 * messages from the client, so there isn't much we can do with the
4584 * connection anymore.
4585 */
4586 if (pq_is_reading_msg())
4587 ereport(FATAL,
4589 errmsg("terminating connection because protocol synchronization was lost")));
4590
4591 /* Now we can allow interrupts again */
4593 }
4594
4595 /* We can now handle ereport(ERROR) */
4597
4598 if (!ignore_till_sync)
4599 send_ready_for_query = true; /* initially, or after error */
4600
4601 /*
4602 * Non-error queries loop here.
4603 */
4604
4605 for (;;)
4606 {
4607 int firstchar;
4609
4610 /*
4611 * At top of loop, reset extended-query-message flag, so that any
4612 * errors encountered in "idle" state don't provoke skip.
4613 */
4615
4616 /*
4617 * For valgrind reporting purposes, the "current query" begins here.
4618 */
4619#ifdef USE_VALGRIND
4621#endif
4622
4623 /*
4624 * Release storage left over from prior query cycle, and create a new
4625 * query input buffer in the cleared MessageContext.
4626 */
4629
4631
4632 /*
4633 * Also consider releasing our catalog snapshot if any, so that it's
4634 * not preventing advance of global xmin while we wait for the client.
4635 */
4637
4638 /*
4639 * (1) If we've reached idle state, tell the frontend we're ready for
4640 * a new query.
4641 *
4642 * Note: this includes fflush()'ing the last of the prior output.
4643 *
4644 * This is also a good time to flush out collected statistics to the
4645 * cumulative stats system, and to update the PS stats display. We
4646 * avoid doing those every time through the message loop because it'd
4647 * slow down processing of batched messages, and because we don't want
4648 * to report uncommitted updates (that confuses autovacuum). The
4649 * notification processor wants a call too, if we are not in a
4650 * transaction block.
4651 *
4652 * Also, if an idle timeout is enabled, start the timer for that.
4653 */
4655 {
4657 {
4658 set_ps_display("idle in transaction (aborted)");
4660
4661 /* Start the idle-in-transaction timer */
4664 {
4668 }
4669 }
4671 {
4672 set_ps_display("idle in transaction");
4674
4675 /* Start the idle-in-transaction timer */
4678 {
4682 }
4683 }
4684 else
4685 {
4686 long stats_timeout;
4687
4688 /*
4689 * Process incoming notifies (including self-notifies), if
4690 * any, and send relevant messages to the client. Doing it
4691 * here helps ensure stable behavior in tests: if any notifies
4692 * were received during the just-finished transaction, they'll
4693 * be seen by the client before ReadyForQuery is.
4694 */
4697
4698 /*
4699 * Check if we need to report stats. If pgstat_report_stat()
4700 * decides it's too soon to flush out pending stats / lock
4701 * contention prevented reporting, it'll tell us when we
4702 * should try to report stats again (so that stats updates
4703 * aren't unduly delayed if the connection goes idle for a
4704 * long time). We only enable the timeout if we don't already
4705 * have a timeout in progress, because we don't disable the
4706 * timeout below. enable_timeout_after() needs to determine
4707 * the current timestamp, which can have a negative
4708 * performance impact. That's OK because pgstat_report_stat()
4709 * won't have us wake up sooner than a prior call.
4710 */
4712 if (stats_timeout > 0)
4713 {
4717 }
4718 else
4719 {
4720 /* all stats flushed, no need for the timeout */
4723 }
4724
4725 set_ps_display("idle");
4727
4728 /* Start the idle-session timer */
4729 if (IdleSessionTimeout > 0)
4730 {
4734 }
4735 }
4736
4737 /* Report any recently-changed GUC options */
4739
4740 /*
4741 * The first time this backend is ready for query, log the
4742 * durations of the different components of connection
4743 * establishment and setup.
4744 */
4748 {
4752
4754
4764
4765 ereport(LOG,
4766 errmsg("connection ready: setup total=%.3f ms, fork=%.3f ms, authentication=%.3f ms",
4767 (double) total_duration / NS_PER_US,
4768 (double) fork_duration / NS_PER_US,
4769 (double) auth_duration / NS_PER_US));
4770 }
4771
4773 send_ready_for_query = false;
4774 }
4775
4776 /*
4777 * (2) Allow asynchronous signals to be executed immediately if they
4778 * come in while we are waiting for client input. (This must be
4779 * conditional since we don't want, say, reads on behalf of COPY FROM
4780 * STDIN doing the same thing.)
4781 */
4782 DoingCommandRead = true;
4783
4784 /*
4785 * (3) read a command (loop blocks here)
4786 */
4788
4789 /*
4790 * (4) turn off the idle-in-transaction and idle-session timeouts if
4791 * active. We do this before step (5) so that any last-moment timeout
4792 * is certain to be detected in step (5).
4793 *
4794 * At most one of these timeouts will be active, so there's no need to
4795 * worry about combining the timeout.c calls into one.
4796 */
4798 {
4801 }
4803 {
4806 }
4807
4808 /*
4809 * (5) disable async signal conditions again.
4810 *
4811 * Query cancel is supposed to be a no-op when there is no query in
4812 * progress, so if a query cancel arrived while we were idle, just
4813 * reset QueryCancelPending. ProcessInterrupts() has that effect when
4814 * it's called when DoingCommandRead is set, so check for interrupts
4815 * before resetting DoingCommandRead.
4816 */
4818 DoingCommandRead = false;
4819
4820 /*
4821 * (6) check for any other interesting events that happened while we
4822 * slept.
4823 */
4825 {
4826 ConfigReloadPending = false;
4828 }
4829
4830 /*
4831 * (7) process the command. But ignore it if we're skipping till
4832 * Sync.
4833 */
4834 if (ignore_till_sync && firstchar != EOF)
4835 continue;
4836
4837 switch (firstchar)
4838 {
4839 case PqMsg_Query:
4840 {
4841 const char *query_string;
4842
4843 /* Set statement_timestamp() */
4845
4846 query_string = pq_getmsgstring(&input_message);
4848
4849 if (am_walsender)
4850 {
4851 if (!exec_replication_command(query_string))
4852 exec_simple_query(query_string);
4853 }
4854 else
4855 exec_simple_query(query_string);
4856
4857 valgrind_report_error_query(query_string);
4858
4859 send_ready_for_query = true;
4860 }
4861 break;
4862
4863 case PqMsg_Parse:
4864 {
4865 const char *stmt_name;
4866 const char *query_string;
4867 int numParams;
4868 Oid *paramTypes = NULL;
4869
4871
4872 /* Set statement_timestamp() */
4874
4875 stmt_name = pq_getmsgstring(&input_message);
4876 query_string = pq_getmsgstring(&input_message);
4877 numParams = pq_getmsgint(&input_message, 2);
4878 if (numParams > 0)
4879 {
4880 paramTypes = palloc_array(Oid, numParams);
4881 for (int i = 0; i < numParams; i++)
4882 paramTypes[i] = pq_getmsgint(&input_message, 4);
4883 }
4885
4886 exec_parse_message(query_string, stmt_name,
4887 paramTypes, numParams);
4888
4889 valgrind_report_error_query(query_string);
4890 }
4891 break;
4892
4893 case PqMsg_Bind:
4895
4896 /* Set statement_timestamp() */
4898
4899 /*
4900 * this message is complex enough that it seems best to put
4901 * the field extraction out-of-line
4902 */
4904
4905 /* exec_bind_message does valgrind_report_error_query */
4906 break;
4907
4908 case PqMsg_Execute:
4909 {
4910 const char *portal_name;
4911 int max_rows;
4912
4914
4915 /* Set statement_timestamp() */
4917
4921
4923
4924 /* exec_execute_message does valgrind_report_error_query */
4925 }
4926 break;
4927
4928 case PqMsg_FunctionCall:
4930
4931 /* Set statement_timestamp() */
4933
4934 /* Report query to various monitoring facilities. */
4936 set_ps_display("<FASTPATH>");
4937
4938 /* start an xact for this function invocation */
4940
4941 /*
4942 * Note: we may at this point be inside an aborted
4943 * transaction. We can't throw error for that until we've
4944 * finished reading the function-call message, so
4945 * HandleFunctionRequest() must check for it after doing so.
4946 * Be careful not to do anything that assumes we're inside a
4947 * valid transaction here.
4948 */
4949
4950 /* switch back to message context */
4952
4954
4955 /* commit the function-invocation transaction */
4957
4958 valgrind_report_error_query("fastpath function call");
4959
4960 send_ready_for_query = true;
4961 break;
4962
4963 case PqMsg_Close:
4964 {
4965 int close_type;
4966 const char *close_target;
4967
4969
4973
4974 switch (close_type)
4975 {
4976 case 'S':
4977 if (close_target[0] != '\0')
4979 else
4980 {
4981 /* special-case the unnamed statement */
4983 }
4984 break;
4985 case 'P':
4986 {
4987 Portal portal;
4988
4989 portal = GetPortalByName(close_target);
4990 if (PortalIsValid(portal))
4991 PortalDrop(portal, false);
4992 }
4993 break;
4994 default:
4995 ereport(ERROR,
4997 errmsg("invalid CLOSE message subtype %d",
4998 close_type)));
4999 break;
5000 }
5001
5004
5005 valgrind_report_error_query("CLOSE message");
5006 }
5007 break;
5008
5009 case PqMsg_Describe:
5010 {
5011 int describe_type;
5012 const char *describe_target;
5013
5015
5016 /* Set statement_timestamp() (needed for xact) */
5018
5022
5023 switch (describe_type)
5024 {
5025 case 'S':
5027 break;
5028 case 'P':
5030 break;
5031 default:
5032 ereport(ERROR,
5034 errmsg("invalid DESCRIBE message subtype %d",
5035 describe_type)));
5036 break;
5037 }
5038
5039 valgrind_report_error_query("DESCRIBE message");
5040 }
5041 break;
5042
5043 case PqMsg_Flush:
5046 pq_flush();
5047 break;
5048
5049 case PqMsg_Sync:
5051
5052 /*
5053 * If pipelining was used, we may be in an implicit
5054 * transaction block. Close it before calling
5055 * finish_xact_command.
5056 */
5059 valgrind_report_error_query("SYNC message");
5060 send_ready_for_query = true;
5061 break;
5062
5063 /*
5064 * PqMsg_Terminate means that the frontend is closing down the
5065 * socket. EOF means unexpected loss of frontend connection.
5066 * Either way, perform normal shutdown.
5067 */
5068 case EOF:
5069
5070 /* for the cumulative statistics system */
5072
5074
5075 case PqMsg_Terminate:
5076
5077 /*
5078 * Reset whereToSendOutput to prevent ereport from attempting
5079 * to send any more messages to client.
5080 */
5083
5084 /*
5085 * NOTE: if you are tempted to add more code here, DON'T!
5086 * Whatever you had in mind to do should be set up as an
5087 * on_proc_exit or on_shmem_exit callback, instead. Otherwise
5088 * it will fail to be called during other backend-shutdown
5089 * scenarios.
5090 */
5091 proc_exit(0);
5092
5093 case PqMsg_CopyData:
5094 case PqMsg_CopyDone:
5095 case PqMsg_CopyFail:
5096
5097 /*
5098 * Accept but ignore these messages, per protocol spec; we
5099 * probably got here because a COPY failed, and the frontend
5100 * is still sending data.
5101 */
5102 break;
5103
5104 default:
5105 ereport(FATAL,
5107 errmsg("invalid frontend message type %d",
5108 firstchar)));
5109 }
5110 } /* end of input-reading loop */
5111}
5112
5113/*
5114 * Throw an error if we're a WAL sender process.
5115 *
5116 * This is used to forbid anything else than simple query protocol messages
5117 * in a WAL sender process. 'firstchar' specifies what kind of a forbidden
5118 * message was received, and is used to construct the error message.
5119 */
5120static void
5122{
5123 if (am_walsender)
5124 {
5126 ereport(ERROR,
5128 errmsg("fastpath function calls not supported in a replication connection")));
5129 else
5130 ereport(ERROR,
5132 errmsg("extended query protocol not supported in a replication connection")));
5133 }
5134}
5135
5136
5137static struct rusage Save_r;
5138static struct timeval Save_t;
5139
5140void
5142{
5145}
5146
5147void
5148ShowUsage(const char *title)
5149{
5151 struct timeval user,
5152 sys;
5153 struct timeval elapse_t;
5154 struct rusage r;
5155
5158 memcpy(&user, &r.ru_utime, sizeof(user));
5159 memcpy(&sys, &r.ru_stime, sizeof(sys));
5160 if (elapse_t.tv_usec < Save_t.tv_usec)
5161 {
5162 elapse_t.tv_sec--;
5163 elapse_t.tv_usec += 1000000;
5164 }
5165 if (r.ru_utime.tv_usec < Save_r.ru_utime.tv_usec)
5166 {
5167 r.ru_utime.tv_sec--;
5168 r.ru_utime.tv_usec += 1000000;
5169 }
5170 if (r.ru_stime.tv_usec < Save_r.ru_stime.tv_usec)
5171 {
5172 r.ru_stime.tv_sec--;
5173 r.ru_stime.tv_usec += 1000000;
5174 }
5175
5176 /*
5177 * The only stats we don't show here are ixrss, idrss, isrss. It takes
5178 * some work to interpret them, and most platforms don't fill them in.
5179 */
5181
5182 appendStringInfoString(&str, "! system usage stats:\n");
5184 "!\t%ld.%06ld s user, %ld.%06ld s system, %ld.%06ld s elapsed\n",
5185 (long) (r.ru_utime.tv_sec - Save_r.ru_utime.tv_sec),
5186 (long) (r.ru_utime.tv_usec - Save_r.ru_utime.tv_usec),
5187 (long) (r.ru_stime.tv_sec - Save_r.ru_stime.tv_sec),
5188 (long) (r.ru_stime.tv_usec - Save_r.ru_stime.tv_usec),
5189 (long) (elapse_t.tv_sec - Save_t.tv_sec),
5190 (long) (elapse_t.tv_usec - Save_t.tv_usec));
5192 "!\t[%ld.%06ld s user, %ld.%06ld s system total]\n",
5193 (long) user.tv_sec,
5194 (long) user.tv_usec,
5195 (long) sys.tv_sec,
5196 (long) sys.tv_usec);
5197#ifndef WIN32
5198
5199 /*
5200 * The following rusage fields are not defined by POSIX, but they're
5201 * present on all current Unix-like systems so we use them without any
5202 * special checks. Some of these could be provided in our Windows
5203 * emulation in src/port/win32getrusage.c with more work.
5204 */
5206 "!\t%ld kB max resident size\n",
5208 /* in bytes on macOS */
5209 r.ru_maxrss / 1024
5210#else
5211 /* in kilobytes on most other platforms */
5212 r.ru_maxrss
5213#endif
5214 );
5216 "!\t%ld/%ld [%ld/%ld] filesystem blocks in/out\n",
5217 r.ru_inblock - Save_r.ru_inblock,
5218 /* they only drink coffee at dec */
5219 r.ru_oublock - Save_r.ru_oublock,
5220 r.ru_inblock, r.ru_oublock);
5222 "!\t%ld/%ld [%ld/%ld] page faults/reclaims, %ld [%ld] swaps\n",
5223 r.ru_majflt - Save_r.ru_majflt,
5224 r.ru_minflt - Save_r.ru_minflt,
5225 r.ru_majflt, r.ru_minflt,
5226 r.ru_nswap - Save_r.ru_nswap,
5227 r.ru_nswap);
5229 "!\t%ld [%ld] signals rcvd, %ld/%ld [%ld/%ld] messages rcvd/sent\n",
5230 r.ru_nsignals - Save_r.ru_nsignals,
5231 r.ru_nsignals,
5232 r.ru_msgrcv - Save_r.ru_msgrcv,
5233 r.ru_msgsnd - Save_r.ru_msgsnd,
5234 r.ru_msgrcv, r.ru_msgsnd);
5236 "!\t%ld/%ld [%ld/%ld] voluntary/involuntary context switches\n",
5237 r.ru_nvcsw - Save_r.ru_nvcsw,
5238 r.ru_nivcsw - Save_r.ru_nivcsw,
5239 r.ru_nvcsw, r.ru_nivcsw);
5240#endif /* !WIN32 */
5241
5242 /* remove trailing newline */
5243 if (str.data[str.len - 1] == '\n')
5244 str.data[--str.len] = '\0';
5245
5246 ereport(LOG,
5247 (errmsg_internal("%s", title),
5248 errdetail_internal("%s", str.data)));
5249
5250 pfree(str.data);
5251}
5252
5253/*
5254 * on_proc_exit handler to log end of session
5255 */
5256static void
5258{
5259 Port *port = MyProcPort;
5260 long secs;
5261 int usecs;
5262 int msecs;
5263 int hours,
5264 minutes,
5265 seconds;
5266
5269 &secs, &usecs);
5270 msecs = usecs / 1000;
5271
5276
5277 ereport(LOG,
5278 (errmsg("disconnection: session time: %d:%02d:%02d.%03d "
5279 "user=%s database=%s host=%s%s%s",
5281 port->user_name, port->database_name, port->remote_host,
5282 port->remote_port[0] ? " port=" : "", port->remote_port)));
5283}
5284
5285/*
5286 * Start statement timeout timer, if enabled.
5287 *
5288 * If there's already a timeout running, don't restart the timer. That
5289 * enables compromises between accuracy of timeouts and cost of starting a
5290 * timeout.
5291 */
5292static void
5294{
5295 /* must be within an xact */
5297
5298 if (StatementTimeout > 0
5300 {
5303 }
5304 else
5305 {
5308 }
5309}
5310
5311/*
5312 * Disable statement timeout, if active.
5313 */
5314static 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:6066
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:1462
#define Assert(condition)
Definition c.h:943
int16_t int16
Definition c.h:619
int32_t int32
Definition c.h:620
uint64_t uint64
Definition c.h:625
#define unlikely(x)
Definition c.h:438
uint32_t uint32
Definition c.h:624
#define pg_fallthrough
Definition c.h:161
uint32 result
memcpy(sums, checksumBaseOffsets, sizeof(checksumBaseOffsets))
const char * GetCommandTagNameAndLen(CommandTag commandTag, Size *len)
Definition cmdtag.c:53
CommandTag
Definition cmdtag.h:23
#define __darwin__
Definition darwin.h:3
#define SECS_PER_HOUR
Definition timestamp.h:127
#define SECS_PER_MINUTE
Definition timestamp.h:128
#define TIMESTAMP_MINUS_INFINITY
Definition timestamp.h:150
void EndCommand(const QueryCompletion *qc, CommandDest dest, bool force_undecorated_output)
Definition dest.c: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:1323
void EmitErrorReport(void)
Definition elog.c:1883
ErrorContextCallback * error_context_stack
Definition elog.c:100
void FlushErrorState(void)
Definition elog.c:2063
int errcode(int sqlerrcode)
Definition elog.c:875
#define _(x)
Definition elog.c:96
sigjmp_buf * PG_exception_stack
Definition elog.c:102
int int errhidestmt(bool hide_stmt)
#define LOG
Definition elog.h:32
int int errdetail_internal(const char *fmt,...) pg_attribute_printf(1
#define errcontext
Definition elog.h:200
int errhint(const char *fmt,...) pg_attribute_printf(1
#define COMMERROR
Definition elog.h:34
int errdetail(const char *fmt,...) pg_attribute_printf(1
#define WARNING_CLIENT_ONLY
Definition elog.h:39
#define FATAL
Definition elog.h:42
int int errmsg_internal(const char *fmt,...) pg_attribute_printf(1
#define WARNING
Definition elog.h:37
#define DEBUG2
Definition elog.h:30
#define DEBUG1
Definition elog.h:31
#define ERROR
Definition elog.h:40
#define elog(elevel,...)
Definition elog.h:228
#define ereport(elevel,...)
Definition elog.h:152
bool equal(const void *a, const void *b)
Definition equalfuncs.c:223
void EventTriggerOnLogin(void)
void HandleFunctionRequest(StringInfo msgBuf)
Definition fastpath.c:188
void set_max_safe_fds(void)
Definition fd.c:1045
#define ERRCODE_PROTOCOL_VIOLATION
Definition fe-connect.c:96
#define palloc_array(type, count)
Definition fe_memutils.h: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:1906
void getTypeInputInfo(Oid type, Oid *typInput, Oid *typIOParam)
Definition lsyscache.c:3069
void getTypeBinaryInputInfo(Oid type, Oid *typReceive, Oid *typIOParam)
Definition lsyscache.c:3135
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 PG_SIG_IGN
Definition port.h:551
#define snprintf
Definition port.h:260
#define printf(...)
Definition port.h:266
#define PG_SIG_DFL
Definition port.h:550
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:5315
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:3675
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:3746
void process_postgres_switches(int argc, char *argv[], GucContext ctx, const char **dbname)
Definition postgres.c:3874
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:5257
static void forbidden_in_wal_sender(char firstchar)
Definition postgres.c:5121
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:3204
void PostgresSingleUserMain(int argc, char *argv[], const char *username)
Definition postgres.c:4130
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:3760
static bool UseSemiNewlineNewline
Definition postgres.c:169
static CachedPlanSource * unnamed_stmt_psrc
Definition postgres.c:164
void FloatExceptionHandler(SIGNAL_ARGS)
Definition postgres.c:3081
int client_connection_check_interval
Definition postgres.c:108
bool check_log_stats(bool *newval, void **extra, GucSource source)
Definition postgres.c:3660
static bool EchoQuery
Definition postgres.c:168
void StatementCancelHandler(SIGNAL_ARGS)
Definition postgres.c:3064
CommandDest whereToSendOutput
Definition postgres.c:97
static bool ignore_till_sync
Definition postgres.c:157
static void ProcessRecoveryConflictInterrupt(RecoveryConflictReason reason)
Definition postgres.c:3108
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:3792
static void enable_statement_timeout(void)
Definition postgres.c:5293
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:5138
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:3834
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:5148
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:3310
static int SocketBackend(StringInfo inBuf)
Definition postgres.c:364
void ProcessClientReadInterrupt(bool blocked)
Definition postgres.c:513
void ProcessInterrupts(void)
Definition postgres.c:3361
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:4273
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:5137
bool check_client_connection_check_interval(int *newval, void **extra, GucSource source)
Definition postgres.c:3625
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:5141
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:3694
static void exec_describe_portal_message(const char *portal_name)
Definition postgres.c:2732
void HandleRecoveryConflictInterrupt(void)
Definition postgres.c:3097
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:3646
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:374
BackgroundWorker * MyBgworkerEntry
Definition postmaster.c:201
@ DISPATCH_POSTMASTER
Definition postmaster.h:139
int pq_getmessage(StringInfo s, int maxlen)
Definition pqcomm.c:1204
int pq_getbyte(void)
Definition pqcomm.c:964
bool pq_is_reading_msg(void)
Definition pqcomm.c:1182
bool pq_check_connection(void)
Definition pqcomm.c:2057
void pq_startmsgread(void)
Definition pqcomm.c:1142
uint32 ProtocolVersion
Definition pqcomm.h:132
#define PG_PROTOCOL(m, n)
Definition pqcomm.h:89
unsigned int pq_getmsgint(StringInfo msg, int b)
Definition pqformat.c:414
void pq_sendbytes(StringInfo buf, const void *data, int datalen)
Definition pqformat.c:126
void pq_getmsgend(StringInfo msg)
Definition pqformat.c:634
const char * pq_getmsgstring(StringInfo msg)
Definition pqformat.c:578
void pq_putemptymessage(char msgtype)
Definition pqformat.c:387
void pq_endmessage(StringInfo buf)
Definition pqformat.c:296
int pq_getmsgbyte(StringInfo msg)
Definition pqformat.c:398
void pq_beginmessage(StringInfo buf, char msgtype)
Definition pqformat.c:88
const char * pq_getmsgbytes(StringInfo msg, int datalen)
Definition pqformat.c:507
void pq_beginmessage_reuse(StringInfo buf, char msgtype)
Definition pqformat.c:109
void pq_endmessage_reuse(StringInfo buf)
Definition pqformat.c:313
static void pq_sendint32(StringInfo buf, uint32 i)
Definition pqformat.h:144
static void pq_sendint16(StringInfo buf, uint16 i)
Definition pqformat.h:136
void PortalSetResultFormat(Portal portal, int nFormats, int16 *formats)
Definition pquery.c:620
void PortalStart(Portal portal, ParamListInfo params, int eflags, Snapshot snapshot)
Definition pquery.c:430
List * FetchPortalTargetList(Portal portal)
Definition pquery.c:323
bool PortalRun(Portal portal, long count, bool isTopLevel, DestReceiver *dest, DestReceiver *altdest, QueryCompletion *qc)
Definition pquery.c:681
char * c
static int fb(int x)
void SetRemoteDestReceiverParams(DestReceiver *self, Portal portal)
Definition printtup.c:101
void SendRowDescriptionMessage(StringInfo buf, TupleDesc typeinfo, List *targetlist, int16 *formats)
Definition printtup.c:167
void ProcessProcSignalBarrier(void)
Definition procsignal.c:503
void procsignal_sigusr1_handler(SIGNAL_ARGS)
Definition procsignal.c:688
#define MAX_CANCEL_KEY_LENGTH
Definition procsignal.h:67
#define PqMsg_CloseComplete
Definition protocol.h:40
#define PqMsg_CopyDone
Definition protocol.h:64
#define PqMsg_BindComplete
Definition protocol.h:39
#define PqMsg_CopyData
Definition protocol.h:65
#define PqMsg_ParameterDescription
Definition protocol.h:58
#define PqMsg_FunctionCall
Definition protocol.h:23
#define PqMsg_Describe
Definition protocol.h:21
#define PqMsg_NoData
Definition protocol.h:56
#define PqMsg_PortalSuspended
Definition protocol.h:57
#define PqMsg_Parse
Definition protocol.h:25
#define PqMsg_Bind
Definition protocol.h:19
#define PqMsg_Sync
Definition protocol.h:27
#define PqMsg_CopyFail
Definition protocol.h:29
#define PqMsg_Flush
Definition protocol.h:24
#define PqMsg_BackendKeyData
Definition protocol.h:48
#define PqMsg_Query
Definition protocol.h:26
#define PqMsg_Terminate
Definition protocol.h:28
#define PqMsg_Execute
Definition protocol.h:22
#define PqMsg_Close
Definition protocol.h:20
#define PqMsg_ParseComplete
Definition protocol.h:38
void set_ps_display_with_len(const char *activity, size_t len)
Definition ps_status.c:470
static void set_ps_display(const char *activity)
Definition ps_status.h:40
volatile sig_atomic_t RepackMessagePending
Definition repack.c:147
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:1347
volatile sig_atomic_t SlotSyncShutdownPending
Definition slotsync.c:159
Snapshot GetTransactionSnapshot(void)
Definition snapmgr.c:272
void PushActiveSnapshot(Snapshot snapshot)
Definition snapmgr.c:682
bool ActiveSnapshotSet(void)
Definition snapmgr.c:812
void InvalidateCatalogSnapshotConditionally(void)
Definition snapmgr.c:477
void PopActiveSnapshot(void)
Definition snapmgr.c:775
#define InvalidSnapshot
Definition snapshot.h:119
int IdleSessionTimeout
Definition proc.c:67
PGPROC * MyProc
Definition proc.c:71
int StatementTimeout
Definition proc.c:63
int IdleInTransactionSessionTimeout
Definition proc.c:65
int TransactionTimeout
Definition proc.c:66
void LockErrorCleanup(void)
Definition proc.c:818
void InitProcess(void)
Definition proc.c:392
void CheckDeadLockAlert(void)
Definition proc.c:1914
RecoveryConflictReason
Definition standby.h:32
@ RECOVERY_CONFLICT_TABLESPACE
Definition standby.h:37
@ RECOVERY_CONFLICT_SNAPSHOT
Definition standby.h:43
@ RECOVERY_CONFLICT_LOCK
Definition standby.h:40
@ RECOVERY_CONFLICT_DATABASE
Definition standby.h:34
@ RECOVERY_CONFLICT_STARTUP_DEADLOCK
Definition standby.h:56
@ RECOVERY_CONFLICT_BUFFERPIN
Definition standby.h:49
@ RECOVERY_CONFLICT_BUFFERPIN_DEADLOCK
Definition standby.h:64
@ RECOVERY_CONFLICT_LOGICALSLOT
Definition standby.h:46
#define NUM_RECOVERY_CONFLICT_REASONS
Definition standby.h:67
char * dbname
Definition streamutil.c:49
void resetStringInfo(StringInfo str)
Definition stringinfo.c:126
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition stringinfo.c:145
void appendStringInfoString(StringInfo str, const char *s)
Definition stringinfo.c:230
void appendStringInfoChar(StringInfo str, char ch)
Definition stringinfo.c:242
void initStringInfo(StringInfo str)
Definition stringinfo.c:97
static void initReadOnlyStringInfo(StringInfo str, char *data, int len)
Definition stringinfo.h:157
void appendStringInfoStringQuoted(StringInfo str, const char *s, int maxlen)
char bgw_type[BGW_MAXLEN]
Definition bgworker.h:99
const char * portalName
Definition postgres.c: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:2385
LogStmtLevel GetCommandLogLevel(Node *parsetree)
Definition utility.c:3290
static uint64 TimestampDifferenceMicroseconds(TimestampTz start_time, TimestampTz stop_time)
Definition timestamp.h:90
#define NS_PER_US
Definition uuid.c:33
bool SplitIdentifierString(char *rawstring, char separator, List **namelist)
Definition varlena.c: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:5194
void LocalProcessControlFile(bool reset)
Definition xlog.c:5275