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