1 /*-------------------------------------------------------------------------
4 * POSTGRES C Backend Interface
6 * Portions Copyright (c) 1996-2024, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
11 * src/backend/tcop/postgres.c
14 * this is the "main" module of the postgres backend and
15 * hence the main module of the "traffic cop".
17 *-------------------------------------------------------------------------
26 #include <sys/resource.h>
27 #include <sys/socket.h>
31 #include <valgrind/valgrind.h>
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"
39 #include "commands/event_trigger.h"
40 #include "commands/prepare.h"
41 #include "common/pg_prng.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"
56 #include "postmaster/autovacuum.h"
57 #include "postmaster/interrupt.h"
58 #include "postmaster/postmaster.h"
59 #include "replication/logicallauncher.h"
60 #include "replication/logicalworker.h"
61 #include "replication/slot.h"
62 #include "replication/walsender.h"
63 #include "rewrite/rewriteHandler.h"
64 #include "storage/bufmgr.h"
65 #include "storage/ipc.h"
66 #include "storage/pmsignal.h"
67 #include "storage/proc.h"
68 #include "storage/procsignal.h"
69 #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"
75 #include "utils/injection_point.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"
88 const char *debug_query_string
; /* client-supplied query string */
90 /* Note: whereToSendOutput is initialized for the bootstrap/standalone case */
91 CommandDest whereToSendOutput
= DestDebug
;
93 /* flag for logging end of session */
94 bool Log_disconnections
= false;
96 int log_statement
= LOGSTMT_NONE
;
98 /* GUC variable for maximum stack depth (measured in kilobytes) */
99 int max_stack_depth
= 100;
101 /* wait N seconds to allow attach from a debugger */
102 int PostAuthDelay
= 0;
104 /* Time between checks that the client is still connected. */
105 int client_connection_check_interval
= 0;
107 /* flags for non-system relation kinds to restrict use */
108 int restrict_nonsystem_relation_kind
;
111 * private typedefs etc
115 /* type of argument for bind_param_error_callback */
116 typedef struct BindParamCbData
118 const char *portalName
;
119 int paramno
; /* zero-based param number, or -1 initially */
120 const char *paramval
; /* textual input string, if available */
128 /* max_stack_depth converted to bytes for speed of checking */
129 static long max_stack_depth_bytes
= 100 * 1024L;
132 * Stack base pointer -- initialized by PostmasterMain and inherited by
133 * subprocesses (but see also InitPostmasterChild).
135 static char *stack_base_ptr
= NULL
;
138 * Flag to keep track of whether we have started a transaction.
139 * For extended query protocol this has to be remembered across messages.
141 static bool xact_started
= false;
144 * Flag to indicate that we are doing the outer loop's read-from-client,
145 * as opposed to any random read from client that might happen within
146 * commands like COPY FROM STDIN.
148 static bool DoingCommandRead
= false;
151 * Flags to implement skip-till-Sync-after-error behavior for messages of
152 * the extended query protocol.
154 static bool doing_extended_query_message
= false;
155 static bool ignore_till_sync
= false;
158 * If an unnamed prepared statement exists, it's stored here.
159 * We keep it separate from the hashtable kept by commands/prepare.c
160 * in order to reduce overhead for short-lived queries.
162 static CachedPlanSource
*unnamed_stmt_psrc
= NULL
;
164 /* assorted command-line switches */
165 static const char *userDoption
= NULL
; /* -D switch */
166 static bool EchoQuery
= false; /* -E switch */
167 static bool UseSemiNewlineNewline
= false; /* -j switch */
169 /* whether or not, and why, we were canceled by conflict with recovery */
170 static volatile sig_atomic_t RecoveryConflictPending
= false;
171 static volatile sig_atomic_t RecoveryConflictPendingReasons
[NUM_PROCSIGNALS
];
173 /* reused buffer to pass to SendRowDescriptionMessage() */
174 static MemoryContext row_description_context
= NULL
;
175 static StringInfoData row_description_buf
;
177 /* ----------------------------------------------------------------
178 * decls for routines only used in this file
179 * ----------------------------------------------------------------
181 static int InteractiveBackend(StringInfo inBuf
);
182 static int interactive_getc(void);
183 static int SocketBackend(StringInfo inBuf
);
184 static int ReadCommand(StringInfo inBuf
);
185 static void forbidden_in_wal_sender(char firstchar
);
186 static bool check_log_statement(List
*stmt_list
);
187 static int errdetail_execute(List
*raw_parsetree_list
);
188 static int errdetail_params(ParamListInfo params
);
189 static int errdetail_abort(void);
190 static void bind_param_error_callback(void *arg
);
191 static void start_xact_command(void);
192 static void finish_xact_command(void);
193 static bool IsTransactionExitStmt(Node
*parsetree
);
194 static bool IsTransactionExitStmtList(List
*pstmts
);
195 static bool IsTransactionStmtList(List
*pstmts
);
196 static void drop_unnamed_stmt(void);
197 static void log_disconnections(int code
, Datum arg
);
198 static void enable_statement_timeout(void);
199 static void disable_statement_timeout(void);
202 /* ----------------------------------------------------------------
203 * infrastructure for valgrind debugging
204 * ----------------------------------------------------------------
207 /* This variable should be set at the top of the main loop. */
208 static unsigned int old_valgrind_error_count
;
211 * If Valgrind detected any errors since old_valgrind_error_count was updated,
212 * report the current query as the cause. This should be called at the end
213 * of message processing.
216 valgrind_report_error_query(const char *query
)
218 unsigned int valgrind_error_count
= VALGRIND_COUNT_ERRORS
;
220 if (unlikely(valgrind_error_count
!= old_valgrind_error_count
) &&
222 VALGRIND_PRINTF("Valgrind detected %u error(s) during execution of \"%s\"\n",
223 valgrind_error_count
- old_valgrind_error_count
,
227 #else /* !USE_VALGRIND */
228 #define valgrind_report_error_query(query) ((void) 0)
229 #endif /* USE_VALGRIND */
232 /* ----------------------------------------------------------------
233 * routines to obtain user input
234 * ----------------------------------------------------------------
238 * InteractiveBackend() is called for user interactive connections
240 * the string entered by the user is placed in its parameter inBuf,
241 * and we act like a Q message was received.
243 * EOF is returned if end-of-file input is seen; time to shut down.
248 InteractiveBackend(StringInfo inBuf
)
250 int c
; /* character read from getc() */
253 * display a prompt and obtain input from the user
258 resetStringInfo(inBuf
);
261 * Read characters until EOF or the appropriate delimiter is seen.
263 while ((c
= interactive_getc()) != EOF
)
267 if (UseSemiNewlineNewline
)
270 * In -j mode, semicolon followed by two newlines ends the
271 * command; otherwise treat newline as regular character.
273 if (inBuf
->len
> 1 &&
274 inBuf
->data
[inBuf
->len
- 1] == '\n' &&
275 inBuf
->data
[inBuf
->len
- 2] == ';')
277 /* might as well drop the second newline */
284 * In plain mode, newline ends the command unless preceded by
287 if (inBuf
->len
> 0 &&
288 inBuf
->data
[inBuf
->len
- 1] == '\\')
290 /* discard backslash from inBuf */
291 inBuf
->data
[--inBuf
->len
] = '\0';
292 /* discard newline too */
297 /* keep the newline character, but end the command */
298 appendStringInfoChar(inBuf
, '\n');
304 /* Not newline, or newline treated as regular character */
305 appendStringInfoChar(inBuf
, (char) c
);
308 /* No input before EOF signal means time to quit. */
309 if (c
== EOF
&& inBuf
->len
== 0)
313 * otherwise we have a user query so process it.
316 /* Add '\0' to make it look the same as message case. */
317 appendStringInfoChar(inBuf
, (char) '\0');
320 * if the query echo flag was given, print the query..
323 printf("statement: %s\n", inBuf
->data
);
330 * interactive_getc -- collect one character from stdin
332 * Even though we are not reading from a "client" process, we still want to
333 * respond to signals, particularly SIGTERM/SIGQUIT.
336 interactive_getc(void)
341 * This will not process catchup interrupts or notifications while
342 * reading. But those can't really be relevant for a standalone backend
343 * anyway. To properly handle SIGTERM there's a hack in die() that
344 * directly processes interrupts at this stage...
346 CHECK_FOR_INTERRUPTS();
350 ProcessClientReadInterrupt(false);
356 * SocketBackend() Is called for frontend-backend connections
358 * Returns the message type code, and loads message body data into inBuf.
360 * EOF is returned if the connection is lost.
364 SocketBackend(StringInfo inBuf
)
370 * Get message type code from the frontend.
372 HOLD_CANCEL_INTERRUPTS();
374 qtype
= pq_getbyte();
376 if (qtype
== EOF
) /* frontend disconnected */
378 if (IsTransactionState())
380 (errcode(ERRCODE_CONNECTION_FAILURE
),
381 errmsg("unexpected EOF on client connection with an open transaction")));
385 * Can't send DEBUG log messages to client at this point. Since
386 * we're disconnecting right away, we don't need to restore
389 whereToSendOutput
= DestNone
;
391 (errcode(ERRCODE_CONNECTION_DOES_NOT_EXIST
),
392 errmsg_internal("unexpected EOF on client connection")));
398 * Validate message type code before trying to read body; if we have lost
399 * sync, better to say "command unknown" than to run out of memory because
400 * we used garbage as a length word. We can also select a type-dependent
401 * limit on what a sane length word could be. (The limit could be chosen
402 * more granularly, but it's not clear it's worth fussing over.)
404 * This also gives us a place to set the doing_extended_query_message flag
405 * as soon as possible.
410 maxmsglen
= PQ_LARGE_MESSAGE_LIMIT
;
411 doing_extended_query_message
= false;
414 case PqMsg_FunctionCall
:
415 maxmsglen
= PQ_LARGE_MESSAGE_LIMIT
;
416 doing_extended_query_message
= false;
419 case PqMsg_Terminate
:
420 maxmsglen
= PQ_SMALL_MESSAGE_LIMIT
;
421 doing_extended_query_message
= false;
422 ignore_till_sync
= false;
427 maxmsglen
= PQ_LARGE_MESSAGE_LIMIT
;
428 doing_extended_query_message
= true;
435 maxmsglen
= PQ_SMALL_MESSAGE_LIMIT
;
436 doing_extended_query_message
= true;
440 maxmsglen
= PQ_SMALL_MESSAGE_LIMIT
;
441 /* stop any active skip-till-Sync */
442 ignore_till_sync
= false;
443 /* mark not-extended, so that a new error doesn't begin skip */
444 doing_extended_query_message
= false;
448 maxmsglen
= PQ_LARGE_MESSAGE_LIMIT
;
449 doing_extended_query_message
= false;
454 maxmsglen
= PQ_SMALL_MESSAGE_LIMIT
;
455 doing_extended_query_message
= false;
461 * Otherwise we got garbage from the frontend. We treat this as
462 * fatal because we have probably lost message boundary sync, and
463 * there's no good way to recover.
466 (errcode(ERRCODE_PROTOCOL_VIOLATION
),
467 errmsg("invalid frontend message type %d", qtype
)));
468 maxmsglen
= 0; /* keep compiler quiet */
473 * In protocol version 3, all frontend messages have a length word next
474 * after the type code; we can read the message contents independently of
477 if (pq_getmessage(inBuf
, maxmsglen
))
478 return EOF
; /* suitable message already logged */
479 RESUME_CANCEL_INTERRUPTS();
485 * ReadCommand reads a command from either the frontend or
486 * standard input, places it in inBuf, and returns the
487 * message type code (first byte of the message).
488 * EOF is returned if end of file.
492 ReadCommand(StringInfo inBuf
)
496 if (whereToSendOutput
== DestRemote
)
497 result
= SocketBackend(inBuf
);
499 result
= InteractiveBackend(inBuf
);
504 * ProcessClientReadInterrupt() - Process interrupts specific to client reads
506 * This is called just before and after low-level reads.
507 * 'blocked' is true if no data was available to read and we plan to retry,
508 * false if about to read or done reading.
510 * Must preserve errno!
513 ProcessClientReadInterrupt(bool blocked
)
515 int save_errno
= errno
;
517 if (DoingCommandRead
)
519 /* Check for general interrupts that arrived before/while reading */
520 CHECK_FOR_INTERRUPTS();
522 /* Process sinval catchup interrupts, if any */
523 if (catchupInterruptPending
)
524 ProcessCatchupInterrupt();
526 /* Process notify interrupts, if any */
527 if (notifyInterruptPending
)
528 ProcessNotifyInterrupt(true);
530 else if (ProcDiePending
)
533 * We're dying. If there is no data available to read, then it's safe
534 * (and sane) to handle that now. If we haven't tried to read yet,
535 * make sure the process latch is set, so that if there is no data
536 * then we'll come back here and die. If we're done reading, also
537 * make sure the process latch is set, as we might've undesirably
538 * cleared it while reading.
541 CHECK_FOR_INTERRUPTS();
550 * ProcessClientWriteInterrupt() - Process interrupts specific to client writes
552 * This is called just before and after low-level writes.
553 * 'blocked' is true if no data could be written and we plan to retry,
554 * false if about to write or done writing.
556 * Must preserve errno!
559 ProcessClientWriteInterrupt(bool blocked
)
561 int save_errno
= errno
;
566 * We're dying. If it's not possible to write, then we should handle
567 * that immediately, else a stuck client could indefinitely delay our
568 * response to the signal. If we haven't tried to write yet, make
569 * sure the process latch is set, so that if the write would block
570 * then we'll come back here and die. If we're done writing, also
571 * make sure the process latch is set, as we might've undesirably
572 * cleared it while writing.
577 * Don't mess with whereToSendOutput if ProcessInterrupts wouldn't
578 * service ProcDiePending.
580 if (InterruptHoldoffCount
== 0 && CritSectionCount
== 0)
583 * We don't want to send the client the error message, as a)
584 * that would possibly block again, and b) it would likely
585 * lead to loss of protocol sync because we may have already
586 * sent a partial protocol message.
588 if (whereToSendOutput
== DestRemote
)
589 whereToSendOutput
= DestNone
;
591 CHECK_FOR_INTERRUPTS();
602 * Do raw parsing (only).
604 * A list of parsetrees (RawStmt nodes) is returned, since there might be
605 * multiple commands in the given string.
607 * NOTE: for interactive queries, it is important to keep this routine
608 * separate from the analysis & rewrite stages. Analysis and rewriting
609 * cannot be done in an aborted transaction, since they require access to
610 * database tables. So, we rely on the raw parser to determine whether
611 * we've seen a COMMIT or ABORT command; when we are in abort state, other
612 * commands are not processed any further than the raw parse stage.
615 pg_parse_query(const char *query_string
)
617 List
*raw_parsetree_list
;
619 TRACE_POSTGRESQL_QUERY_PARSE_START(query_string
);
621 if (log_parser_stats
)
624 raw_parsetree_list
= raw_parser(query_string
, RAW_PARSE_DEFAULT
);
626 if (log_parser_stats
)
627 ShowUsage("PARSER STATISTICS");
629 #ifdef DEBUG_NODE_TESTS_ENABLED
631 /* Optional debugging check: pass raw parsetrees through copyObject() */
632 if (Debug_copy_parse_plan_trees
)
634 List
*new_list
= copyObject(raw_parsetree_list
);
636 /* This checks both copyObject() and the equal() routines... */
637 if (!equal(new_list
, raw_parsetree_list
))
638 elog(WARNING
, "copyObject() failed to produce an equal raw parse tree");
640 raw_parsetree_list
= new_list
;
644 * Optional debugging check: pass raw parsetrees through
647 if (Debug_write_read_parse_plan_trees
)
649 char *str
= nodeToStringWithLocations(raw_parsetree_list
);
650 List
*new_list
= stringToNodeWithLocations(str
);
653 /* This checks both outfuncs/readfuncs and the equal() routines... */
654 if (!equal(new_list
, raw_parsetree_list
))
655 elog(WARNING
, "outfuncs/readfuncs failed to produce an equal raw parse tree");
657 raw_parsetree_list
= new_list
;
660 #endif /* DEBUG_NODE_TESTS_ENABLED */
662 TRACE_POSTGRESQL_QUERY_PARSE_DONE(query_string
);
664 return raw_parsetree_list
;
668 * Given a raw parsetree (gram.y output), and optionally information about
669 * types of parameter symbols ($n), perform parse analysis and rule rewriting.
671 * A list of Query nodes is returned, since either the analyzer or the
672 * rewriter might expand one query to several.
674 * NOTE: for reasons mentioned above, this must be separate from raw parsing.
677 pg_analyze_and_rewrite_fixedparams(RawStmt
*parsetree
,
678 const char *query_string
,
679 const Oid
*paramTypes
,
681 QueryEnvironment
*queryEnv
)
684 List
*querytree_list
;
686 TRACE_POSTGRESQL_QUERY_REWRITE_START(query_string
);
689 * (1) Perform parse analysis.
691 if (log_parser_stats
)
694 query
= parse_analyze_fixedparams(parsetree
, query_string
, paramTypes
, numParams
,
697 if (log_parser_stats
)
698 ShowUsage("PARSE ANALYSIS STATISTICS");
701 * (2) Rewrite the queries, as necessary
703 querytree_list
= pg_rewrite_query(query
);
705 TRACE_POSTGRESQL_QUERY_REWRITE_DONE(query_string
);
707 return querytree_list
;
711 * Do parse analysis and rewriting. This is the same as
712 * pg_analyze_and_rewrite_fixedparams except that it's okay to deduce
713 * information about $n symbol datatypes from context.
716 pg_analyze_and_rewrite_varparams(RawStmt
*parsetree
,
717 const char *query_string
,
720 QueryEnvironment
*queryEnv
)
723 List
*querytree_list
;
725 TRACE_POSTGRESQL_QUERY_REWRITE_START(query_string
);
728 * (1) Perform parse analysis.
730 if (log_parser_stats
)
733 query
= parse_analyze_varparams(parsetree
, query_string
, paramTypes
, numParams
,
737 * Check all parameter types got determined.
739 for (int i
= 0; i
< *numParams
; i
++)
741 Oid ptype
= (*paramTypes
)[i
];
743 if (ptype
== InvalidOid
|| ptype
== UNKNOWNOID
)
745 (errcode(ERRCODE_INDETERMINATE_DATATYPE
),
746 errmsg("could not determine data type of parameter $%d",
750 if (log_parser_stats
)
751 ShowUsage("PARSE ANALYSIS STATISTICS");
754 * (2) Rewrite the queries, as necessary
756 querytree_list
= pg_rewrite_query(query
);
758 TRACE_POSTGRESQL_QUERY_REWRITE_DONE(query_string
);
760 return querytree_list
;
764 * Do parse analysis and rewriting. This is the same as
765 * pg_analyze_and_rewrite_fixedparams except that, instead of a fixed list of
766 * parameter datatypes, a parser callback is supplied that can do
767 * external-parameter resolution and possibly other things.
770 pg_analyze_and_rewrite_withcb(RawStmt
*parsetree
,
771 const char *query_string
,
772 ParserSetupHook parserSetup
,
773 void *parserSetupArg
,
774 QueryEnvironment
*queryEnv
)
777 List
*querytree_list
;
779 TRACE_POSTGRESQL_QUERY_REWRITE_START(query_string
);
782 * (1) Perform parse analysis.
784 if (log_parser_stats
)
787 query
= parse_analyze_withcb(parsetree
, query_string
, parserSetup
, parserSetupArg
,
790 if (log_parser_stats
)
791 ShowUsage("PARSE ANALYSIS STATISTICS");
794 * (2) Rewrite the queries, as necessary
796 querytree_list
= pg_rewrite_query(query
);
798 TRACE_POSTGRESQL_QUERY_REWRITE_DONE(query_string
);
800 return querytree_list
;
804 * Perform rewriting of a query produced by parse analysis.
806 * Note: query must just have come from the parser, because we do not do
807 * AcquireRewriteLocks() on it.
810 pg_rewrite_query(Query
*query
)
812 List
*querytree_list
;
814 if (Debug_print_parse
)
815 elog_node_display(LOG
, "parse tree", query
,
818 if (log_parser_stats
)
821 if (query
->commandType
== CMD_UTILITY
)
823 /* don't rewrite utilities, just dump 'em into result list */
824 querytree_list
= list_make1(query
);
828 /* rewrite regular queries */
829 querytree_list
= QueryRewrite(query
);
832 if (log_parser_stats
)
833 ShowUsage("REWRITER STATISTICS");
835 #ifdef DEBUG_NODE_TESTS_ENABLED
837 /* Optional debugging check: pass querytree through copyObject() */
838 if (Debug_copy_parse_plan_trees
)
842 new_list
= copyObject(querytree_list
);
843 /* This checks both copyObject() and the equal() routines... */
844 if (!equal(new_list
, querytree_list
))
845 elog(WARNING
, "copyObject() failed to produce an equal rewritten parse tree");
847 querytree_list
= new_list
;
850 /* Optional debugging check: pass querytree through outfuncs/readfuncs */
851 if (Debug_write_read_parse_plan_trees
)
853 List
*new_list
= NIL
;
856 foreach(lc
, querytree_list
)
858 Query
*curr_query
= lfirst_node(Query
, lc
);
859 char *str
= nodeToStringWithLocations(curr_query
);
860 Query
*new_query
= stringToNodeWithLocations(str
);
863 * queryId is not saved in stored rules, but we must preserve it
864 * here to avoid breaking pg_stat_statements.
866 new_query
->queryId
= curr_query
->queryId
;
868 new_list
= lappend(new_list
, new_query
);
872 /* This checks both outfuncs/readfuncs and the equal() routines... */
873 if (!equal(new_list
, querytree_list
))
874 elog(WARNING
, "outfuncs/readfuncs failed to produce an equal rewritten parse tree");
876 querytree_list
= new_list
;
879 #endif /* DEBUG_NODE_TESTS_ENABLED */
881 if (Debug_print_rewritten
)
882 elog_node_display(LOG
, "rewritten parse tree", querytree_list
,
885 return querytree_list
;
890 * Generate a plan for a single already-rewritten query.
891 * This is a thin wrapper around planner() and takes the same parameters.
894 pg_plan_query(Query
*querytree
, const char *query_string
, int cursorOptions
,
895 ParamListInfo boundParams
)
899 /* Utility commands have no plans. */
900 if (querytree
->commandType
== CMD_UTILITY
)
903 /* Planner must have a snapshot in case it calls user-defined functions. */
904 Assert(ActiveSnapshotSet());
906 TRACE_POSTGRESQL_QUERY_PLAN_START();
908 if (log_planner_stats
)
911 /* call the optimizer */
912 plan
= planner(querytree
, query_string
, cursorOptions
, boundParams
);
914 if (log_planner_stats
)
915 ShowUsage("PLANNER STATISTICS");
917 #ifdef DEBUG_NODE_TESTS_ENABLED
919 /* Optional debugging check: pass plan tree through copyObject() */
920 if (Debug_copy_parse_plan_trees
)
922 PlannedStmt
*new_plan
= copyObject(plan
);
925 * equal() currently does not have routines to compare Plan nodes, so
926 * don't try to test equality here. Perhaps fix someday?
929 /* This checks both copyObject() and the equal() routines... */
930 if (!equal(new_plan
, plan
))
931 elog(WARNING
, "copyObject() failed to produce an equal plan tree");
937 /* Optional debugging check: pass plan tree through outfuncs/readfuncs */
938 if (Debug_write_read_parse_plan_trees
)
941 PlannedStmt
*new_plan
;
943 str
= nodeToStringWithLocations(plan
);
944 new_plan
= stringToNodeWithLocations(str
);
948 * equal() currently does not have routines to compare Plan nodes, so
949 * don't try to test equality here. Perhaps fix someday?
952 /* This checks both outfuncs/readfuncs and the equal() routines... */
953 if (!equal(new_plan
, plan
))
954 elog(WARNING
, "outfuncs/readfuncs failed to produce an equal plan tree");
960 #endif /* DEBUG_NODE_TESTS_ENABLED */
963 * Print plan if debugging.
965 if (Debug_print_plan
)
966 elog_node_display(LOG
, "plan", plan
, Debug_pretty_print
);
968 TRACE_POSTGRESQL_QUERY_PLAN_DONE();
974 * Generate plans for a list of already-rewritten queries.
976 * For normal optimizable statements, invoke the planner. For utility
977 * statements, just make a wrapper PlannedStmt node.
979 * The result is a list of PlannedStmt nodes.
982 pg_plan_queries(List
*querytrees
, const char *query_string
, int cursorOptions
,
983 ParamListInfo boundParams
)
985 List
*stmt_list
= NIL
;
986 ListCell
*query_list
;
988 foreach(query_list
, querytrees
)
990 Query
*query
= lfirst_node(Query
, query_list
);
993 if (query
->commandType
== CMD_UTILITY
)
995 /* Utility commands require no planning. */
996 stmt
= makeNode(PlannedStmt
);
997 stmt
->commandType
= CMD_UTILITY
;
998 stmt
->canSetTag
= query
->canSetTag
;
999 stmt
->utilityStmt
= query
->utilityStmt
;
1000 stmt
->stmt_location
= query
->stmt_location
;
1001 stmt
->stmt_len
= query
->stmt_len
;
1002 stmt
->queryId
= query
->queryId
;
1006 stmt
= pg_plan_query(query
, query_string
, cursorOptions
,
1010 stmt_list
= lappend(stmt_list
, stmt
);
1020 * Execute a "simple Query" protocol message.
1023 exec_simple_query(const char *query_string
)
1025 CommandDest dest
= whereToSendOutput
;
1026 MemoryContext oldcontext
;
1027 List
*parsetree_list
;
1028 ListCell
*parsetree_item
;
1029 bool save_log_statement_stats
= log_statement_stats
;
1030 bool was_logged
= false;
1031 bool use_implicit_block
;
1035 * Report query to various monitoring facilities.
1037 debug_query_string
= query_string
;
1039 pgstat_report_activity(STATE_RUNNING
, query_string
);
1041 TRACE_POSTGRESQL_QUERY_START(query_string
);
1044 * We use save_log_statement_stats so ShowUsage doesn't report incorrect
1045 * results because ResetUsage wasn't called.
1047 if (save_log_statement_stats
)
1051 * Start up a transaction command. All queries generated by the
1052 * query_string will be in this same command block, *unless* we find a
1053 * BEGIN/COMMIT/ABORT statement; we have to force a new xact command after
1054 * one of those, else bad things will happen in xact.c. (Note that this
1055 * will normally change current memory context.)
1057 start_xact_command();
1060 * Zap any pre-existing unnamed statement. (While not strictly necessary,
1061 * it seems best to define simple-Query mode as if it used the unnamed
1062 * statement and portal; this ensures we recover any storage used by prior
1063 * unnamed operations.)
1065 drop_unnamed_stmt();
1068 * Switch to appropriate context for constructing parsetrees.
1070 oldcontext
= MemoryContextSwitchTo(MessageContext
);
1073 * Do basic parsing of the query or queries (this should be safe even if
1074 * we are in aborted transaction state!)
1076 parsetree_list
= pg_parse_query(query_string
);
1078 /* Log immediately if dictated by log_statement */
1079 if (check_log_statement(parsetree_list
))
1082 (errmsg("statement: %s", query_string
),
1084 errdetail_execute(parsetree_list
)));
1089 * Switch back to transaction context to enter the loop.
1091 MemoryContextSwitchTo(oldcontext
);
1094 * For historical reasons, if multiple SQL statements are given in a
1095 * single "simple Query" message, we execute them as a single transaction,
1096 * unless explicit transaction control commands are included to make
1097 * portions of the list be separate transactions. To represent this
1098 * behavior properly in the transaction machinery, we use an "implicit"
1099 * transaction block.
1101 use_implicit_block
= (list_length(parsetree_list
) > 1);
1104 * Run through the raw parsetree(s) and process each one.
1106 foreach(parsetree_item
, parsetree_list
)
1108 RawStmt
*parsetree
= lfirst_node(RawStmt
, parsetree_item
);
1109 bool snapshot_set
= false;
1110 CommandTag commandTag
;
1112 MemoryContext per_parsetree_context
= NULL
;
1113 List
*querytree_list
,
1116 DestReceiver
*receiver
;
1118 const char *cmdtagname
;
1121 pgstat_report_query_id(0, true);
1124 * Get the command name for use in status display (it also becomes the
1125 * default completion tag, down inside PortalRun). Set ps_status and
1126 * do any special start-of-SQL-command processing needed by the
1129 commandTag
= CreateCommandTag(parsetree
->stmt
);
1130 cmdtagname
= GetCommandTagNameAndLen(commandTag
, &cmdtaglen
);
1132 set_ps_display_with_len(cmdtagname
, cmdtaglen
);
1134 BeginCommand(commandTag
, dest
);
1137 * If we are in an aborted transaction, reject all commands except
1138 * COMMIT/ABORT. It is important that this test occur before we try
1139 * to do parse analysis, rewrite, or planning, since all those phases
1140 * try to do database accesses, which may fail in abort state. (It
1141 * might be safe to allow some additional utility commands in this
1142 * state, but not many...)
1144 if (IsAbortedTransactionBlockState() &&
1145 !IsTransactionExitStmt(parsetree
->stmt
))
1147 (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION
),
1148 errmsg("current transaction is aborted, "
1149 "commands ignored until end of transaction block"),
1150 errdetail_abort()));
1152 /* Make sure we are in a transaction command */
1153 start_xact_command();
1156 * If using an implicit transaction block, and we're not already in a
1157 * transaction block, start an implicit block to force this statement
1158 * to be grouped together with any following ones. (We must do this
1159 * each time through the loop; otherwise, a COMMIT/ROLLBACK in the
1160 * list would cause later statements to not be grouped.)
1162 if (use_implicit_block
)
1163 BeginImplicitTransactionBlock();
1165 /* If we got a cancel signal in parsing or prior command, quit */
1166 CHECK_FOR_INTERRUPTS();
1169 * Set up a snapshot if parse analysis/planning will need one.
1171 if (analyze_requires_snapshot(parsetree
))
1173 PushActiveSnapshot(GetTransactionSnapshot());
1174 snapshot_set
= true;
1178 * OK to analyze, rewrite, and plan this query.
1180 * Switch to appropriate context for constructing query and plan trees
1181 * (these can't be in the transaction context, as that will get reset
1182 * when the command is COMMIT/ROLLBACK). If we have multiple
1183 * parsetrees, we use a separate context for each one, so that we can
1184 * free that memory before moving on to the next one. But for the
1185 * last (or only) parsetree, just use MessageContext, which will be
1186 * reset shortly after completion anyway. In event of an error, the
1187 * per_parsetree_context will be deleted when MessageContext is reset.
1189 if (lnext(parsetree_list
, parsetree_item
) != NULL
)
1191 per_parsetree_context
=
1192 AllocSetContextCreate(MessageContext
,
1193 "per-parsetree message context",
1194 ALLOCSET_DEFAULT_SIZES
);
1195 oldcontext
= MemoryContextSwitchTo(per_parsetree_context
);
1198 oldcontext
= MemoryContextSwitchTo(MessageContext
);
1200 querytree_list
= pg_analyze_and_rewrite_fixedparams(parsetree
, query_string
,
1203 plantree_list
= pg_plan_queries(querytree_list
, query_string
,
1204 CURSOR_OPT_PARALLEL_OK
, NULL
);
1207 * Done with the snapshot used for parsing/planning.
1209 * While it looks promising to reuse the same snapshot for query
1210 * execution (at least for simple protocol), unfortunately it causes
1211 * execution to use a snapshot that has been acquired before locking
1212 * any of the tables mentioned in the query. This creates user-
1213 * visible anomalies, so refrain. Refer to
1214 * https://postgr.es/m/flat/5075D8DF.6050500@fuzzy.cz for details.
1217 PopActiveSnapshot();
1219 /* If we got a cancel signal in analysis or planning, quit */
1220 CHECK_FOR_INTERRUPTS();
1223 * Create unnamed portal to run the query or queries in. If there
1224 * already is one, silently drop it.
1226 portal
= CreatePortal("", true, true);
1227 /* Don't display the portal in pg_cursors */
1228 portal
->visible
= false;
1231 * We don't have to copy anything into the portal, because everything
1232 * we are passing here is in MessageContext or the
1233 * per_parsetree_context, and so will outlive the portal anyway.
1235 PortalDefineQuery(portal
,
1243 * Start the portal. No parameters here.
1245 PortalStart(portal
, NULL
, 0, InvalidSnapshot
);
1248 * Select the appropriate output format: text unless we are doing a
1249 * FETCH from a binary cursor. (Pretty grotty to have to do this here
1250 * --- but it avoids grottiness in other places. Ah, the joys of
1251 * backward compatibility...)
1253 format
= 0; /* TEXT is default */
1254 if (IsA(parsetree
->stmt
, FetchStmt
))
1256 FetchStmt
*stmt
= (FetchStmt
*) parsetree
->stmt
;
1260 Portal fportal
= GetPortalByName(stmt
->portalname
);
1262 if (PortalIsValid(fportal
) &&
1263 (fportal
->cursorOptions
& CURSOR_OPT_BINARY
))
1264 format
= 1; /* BINARY */
1267 PortalSetResultFormat(portal
, 1, &format
);
1270 * Now we can create the destination receiver object.
1272 receiver
= CreateDestReceiver(dest
);
1273 if (dest
== DestRemote
)
1274 SetRemoteDestReceiverParams(receiver
, portal
);
1277 * Switch back to transaction context for execution.
1279 MemoryContextSwitchTo(oldcontext
);
1282 * Run the portal to completion, and then drop it (and the receiver).
1284 (void) PortalRun(portal
,
1286 true, /* always top level */
1292 receiver
->rDestroy(receiver
);
1294 PortalDrop(portal
, false);
1296 if (lnext(parsetree_list
, parsetree_item
) == NULL
)
1299 * If this is the last parsetree of the query string, close down
1300 * transaction statement before reporting command-complete. This
1301 * is so that any end-of-transaction errors are reported before
1302 * the command-complete message is issued, to avoid confusing
1303 * clients who will expect either a command-complete message or an
1304 * error, not one and then the other. Also, if we're using an
1305 * implicit transaction block, we must close that out first.
1307 if (use_implicit_block
)
1308 EndImplicitTransactionBlock();
1309 finish_xact_command();
1311 else if (IsA(parsetree
->stmt
, TransactionStmt
))
1314 * If this was a transaction control statement, commit it. We will
1315 * start a new xact command for the next command.
1317 finish_xact_command();
1322 * We had better not see XACT_FLAGS_NEEDIMMEDIATECOMMIT set if
1323 * we're not calling finish_xact_command(). (The implicit
1324 * transaction block should have prevented it from getting set.)
1326 Assert(!(MyXactFlags
& XACT_FLAGS_NEEDIMMEDIATECOMMIT
));
1329 * We need a CommandCounterIncrement after every query, except
1330 * those that start or end a transaction block.
1332 CommandCounterIncrement();
1335 * Disable statement timeout between queries of a multi-query
1336 * string, so that the timeout applies separately to each query.
1337 * (Our next loop iteration will start a fresh timeout.)
1339 disable_statement_timeout();
1343 * Tell client that we're done with this query. Note we emit exactly
1344 * one EndCommand report for each raw parsetree, thus one for each SQL
1345 * command the client sent, regardless of rewriting. (But a command
1346 * aborted by error will not send an EndCommand report at all.)
1348 EndCommand(&qc
, dest
, false);
1350 /* Now we may drop the per-parsetree context, if one was created. */
1351 if (per_parsetree_context
)
1352 MemoryContextDelete(per_parsetree_context
);
1353 } /* end loop over parsetrees */
1356 * Close down transaction statement, if one is open. (This will only do
1357 * something if the parsetree list was empty; otherwise the last loop
1358 * iteration already did it.)
1360 finish_xact_command();
1363 * If there were no parsetrees, return EmptyQueryResponse message.
1365 if (!parsetree_list
)
1369 * Emit duration logging if appropriate.
1371 switch (check_log_duration(msec_str
, was_logged
))
1375 (errmsg("duration: %s ms", msec_str
),
1376 errhidestmt(true)));
1380 (errmsg("duration: %s ms statement: %s",
1381 msec_str
, query_string
),
1383 errdetail_execute(parsetree_list
)));
1387 if (save_log_statement_stats
)
1388 ShowUsage("QUERY STATISTICS");
1390 TRACE_POSTGRESQL_QUERY_DONE(query_string
);
1392 debug_query_string
= NULL
;
1396 * exec_parse_message
1398 * Execute a "Parse" protocol message.
1401 exec_parse_message(const char *query_string
, /* string to execute */
1402 const char *stmt_name
, /* name for prepared stmt */
1403 Oid
*paramTypes
, /* parameter types */
1404 int numParams
) /* number of parameters */
1406 MemoryContext unnamed_stmt_context
= NULL
;
1407 MemoryContext oldcontext
;
1408 List
*parsetree_list
;
1409 RawStmt
*raw_parse_tree
;
1410 List
*querytree_list
;
1411 CachedPlanSource
*psrc
;
1413 bool save_log_statement_stats
= log_statement_stats
;
1417 * Report query to various monitoring facilities.
1419 debug_query_string
= query_string
;
1421 pgstat_report_activity(STATE_RUNNING
, query_string
);
1423 set_ps_display("PARSE");
1425 if (save_log_statement_stats
)
1429 (errmsg_internal("parse %s: %s",
1430 *stmt_name
? stmt_name
: "<unnamed>",
1434 * Start up a transaction command so we can run parse analysis etc. (Note
1435 * that this will normally change current memory context.) Nothing happens
1436 * if we are already in one. This also arms the statement timeout if
1439 start_xact_command();
1442 * Switch to appropriate context for constructing parsetrees.
1444 * We have two strategies depending on whether the prepared statement is
1445 * named or not. For a named prepared statement, we do parsing in
1446 * MessageContext and copy the finished trees into the prepared
1447 * statement's plancache entry; then the reset of MessageContext releases
1448 * temporary space used by parsing and rewriting. For an unnamed prepared
1449 * statement, we assume the statement isn't going to hang around long, so
1450 * getting rid of temp space quickly is probably not worth the costs of
1451 * copying parse trees. So in this case, we create the plancache entry's
1452 * query_context here, and do all the parsing work therein.
1454 is_named
= (stmt_name
[0] != '\0');
1457 /* Named prepared statement --- parse in MessageContext */
1458 oldcontext
= MemoryContextSwitchTo(MessageContext
);
1462 /* Unnamed prepared statement --- release any prior unnamed stmt */
1463 drop_unnamed_stmt();
1464 /* Create context for parsing */
1465 unnamed_stmt_context
=
1466 AllocSetContextCreate(MessageContext
,
1467 "unnamed prepared statement",
1468 ALLOCSET_DEFAULT_SIZES
);
1469 oldcontext
= MemoryContextSwitchTo(unnamed_stmt_context
);
1473 * Do basic parsing of the query or queries (this should be safe even if
1474 * we are in aborted transaction state!)
1476 parsetree_list
= pg_parse_query(query_string
);
1479 * We only allow a single user statement in a prepared statement. This is
1480 * mainly to keep the protocol simple --- otherwise we'd need to worry
1481 * about multiple result tupdescs and things like that.
1483 if (list_length(parsetree_list
) > 1)
1485 (errcode(ERRCODE_SYNTAX_ERROR
),
1486 errmsg("cannot insert multiple commands into a prepared statement")));
1488 if (parsetree_list
!= NIL
)
1490 bool snapshot_set
= false;
1492 raw_parse_tree
= linitial_node(RawStmt
, parsetree_list
);
1495 * If we are in an aborted transaction, reject all commands except
1496 * COMMIT/ROLLBACK. It is important that this test occur before we
1497 * try to do parse analysis, rewrite, or planning, since all those
1498 * phases try to do database accesses, which may fail in abort state.
1499 * (It might be safe to allow some additional utility commands in this
1500 * state, but not many...)
1502 if (IsAbortedTransactionBlockState() &&
1503 !IsTransactionExitStmt(raw_parse_tree
->stmt
))
1505 (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION
),
1506 errmsg("current transaction is aborted, "
1507 "commands ignored until end of transaction block"),
1508 errdetail_abort()));
1511 * Create the CachedPlanSource before we do parse analysis, since it
1512 * needs to see the unmodified raw parse tree.
1514 psrc
= CreateCachedPlan(raw_parse_tree
, query_string
,
1515 CreateCommandTag(raw_parse_tree
->stmt
));
1518 * Set up a snapshot if parse analysis will need one.
1520 if (analyze_requires_snapshot(raw_parse_tree
))
1522 PushActiveSnapshot(GetTransactionSnapshot());
1523 snapshot_set
= true;
1527 * Analyze and rewrite the query. Note that the originally specified
1528 * parameter set is not required to be complete, so we have to use
1529 * pg_analyze_and_rewrite_varparams().
1531 querytree_list
= pg_analyze_and_rewrite_varparams(raw_parse_tree
,
1537 /* Done with the snapshot used for parsing */
1539 PopActiveSnapshot();
1543 /* Empty input string. This is legal. */
1544 raw_parse_tree
= NULL
;
1545 psrc
= CreateCachedPlan(raw_parse_tree
, query_string
,
1547 querytree_list
= NIL
;
1551 * CachedPlanSource must be a direct child of MessageContext before we
1552 * reparent unnamed_stmt_context under it, else we have a disconnected
1553 * circular subgraph. Klugy, but less so than flipping contexts even more
1556 if (unnamed_stmt_context
)
1557 MemoryContextSetParent(psrc
->context
, MessageContext
);
1559 /* Finish filling in the CachedPlanSource */
1560 CompleteCachedPlan(psrc
,
1562 unnamed_stmt_context
,
1567 CURSOR_OPT_PARALLEL_OK
, /* allow parallel mode */
1568 true); /* fixed result */
1570 /* If we got a cancel signal during analysis, quit */
1571 CHECK_FOR_INTERRUPTS();
1576 * Store the query as a prepared statement.
1578 StorePreparedStatement(stmt_name
, psrc
, false);
1583 * We just save the CachedPlanSource into unnamed_stmt_psrc.
1585 SaveCachedPlan(psrc
);
1586 unnamed_stmt_psrc
= psrc
;
1589 MemoryContextSwitchTo(oldcontext
);
1592 * We do NOT close the open transaction command here; that only happens
1593 * when the client sends Sync. Instead, do CommandCounterIncrement just
1594 * in case something happened during parse/plan.
1596 CommandCounterIncrement();
1599 * Send ParseComplete.
1601 if (whereToSendOutput
== DestRemote
)
1602 pq_putemptymessage(PqMsg_ParseComplete
);
1605 * Emit duration logging if appropriate.
1607 switch (check_log_duration(msec_str
, false))
1611 (errmsg("duration: %s ms", msec_str
),
1612 errhidestmt(true)));
1616 (errmsg("duration: %s ms parse %s: %s",
1618 *stmt_name
? stmt_name
: "<unnamed>",
1620 errhidestmt(true)));
1624 if (save_log_statement_stats
)
1625 ShowUsage("PARSE MESSAGE STATISTICS");
1627 debug_query_string
= NULL
;
1633 * Process a "Bind" message to create a portal from a prepared statement
1636 exec_bind_message(StringInfo input_message
)
1638 const char *portal_name
;
1639 const char *stmt_name
;
1641 int16
*pformats
= NULL
;
1644 int16
*rformats
= NULL
;
1645 CachedPlanSource
*psrc
;
1649 char *saved_stmt_name
;
1650 ParamListInfo params
;
1651 MemoryContext oldContext
;
1652 bool save_log_statement_stats
= log_statement_stats
;
1653 bool snapshot_set
= false;
1655 ParamsErrorCbData params_data
;
1656 ErrorContextCallback params_errcxt
;
1659 /* Get the fixed part of the message */
1660 portal_name
= pq_getmsgstring(input_message
);
1661 stmt_name
= pq_getmsgstring(input_message
);
1664 (errmsg_internal("bind %s to %s",
1665 *portal_name
? portal_name
: "<unnamed>",
1666 *stmt_name
? stmt_name
: "<unnamed>")));
1668 /* Find prepared statement */
1669 if (stmt_name
[0] != '\0')
1671 PreparedStatement
*pstmt
;
1673 pstmt
= FetchPreparedStatement(stmt_name
, true);
1674 psrc
= pstmt
->plansource
;
1678 /* special-case the unnamed statement */
1679 psrc
= unnamed_stmt_psrc
;
1682 (errcode(ERRCODE_UNDEFINED_PSTATEMENT
),
1683 errmsg("unnamed prepared statement does not exist")));
1687 * Report query to various monitoring facilities.
1689 debug_query_string
= psrc
->query_string
;
1691 pgstat_report_activity(STATE_RUNNING
, psrc
->query_string
);
1693 foreach(lc
, psrc
->query_list
)
1695 Query
*query
= lfirst_node(Query
, lc
);
1697 if (query
->queryId
!= UINT64CONST(0))
1699 pgstat_report_query_id(query
->queryId
, false);
1704 set_ps_display("BIND");
1706 if (save_log_statement_stats
)
1710 * Start up a transaction command so we can call functions etc. (Note that
1711 * this will normally change current memory context.) Nothing happens if
1712 * we are already in one. This also arms the statement timeout if
1715 start_xact_command();
1717 /* Switch back to message context */
1718 MemoryContextSwitchTo(MessageContext
);
1720 /* Get the parameter format codes */
1721 numPFormats
= pq_getmsgint(input_message
, 2);
1722 if (numPFormats
> 0)
1724 pformats
= palloc_array(int16
, numPFormats
);
1725 for (int i
= 0; i
< numPFormats
; i
++)
1726 pformats
[i
] = pq_getmsgint(input_message
, 2);
1729 /* Get the parameter value count */
1730 numParams
= pq_getmsgint(input_message
, 2);
1732 if (numPFormats
> 1 && numPFormats
!= numParams
)
1734 (errcode(ERRCODE_PROTOCOL_VIOLATION
),
1735 errmsg("bind message has %d parameter formats but %d parameters",
1736 numPFormats
, numParams
)));
1738 if (numParams
!= psrc
->num_params
)
1740 (errcode(ERRCODE_PROTOCOL_VIOLATION
),
1741 errmsg("bind message supplies %d parameters, but prepared statement \"%s\" requires %d",
1742 numParams
, stmt_name
, psrc
->num_params
)));
1745 * If we are in aborted transaction state, the only portals we can
1746 * actually run are those containing COMMIT or ROLLBACK commands. We
1747 * disallow binding anything else to avoid problems with infrastructure
1748 * that expects to run inside a valid transaction. We also disallow
1749 * binding any parameters, since we can't risk calling user-defined I/O
1752 if (IsAbortedTransactionBlockState() &&
1753 (!(psrc
->raw_parse_tree
&&
1754 IsTransactionExitStmt(psrc
->raw_parse_tree
->stmt
)) ||
1757 (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION
),
1758 errmsg("current transaction is aborted, "
1759 "commands ignored until end of transaction block"),
1760 errdetail_abort()));
1763 * Create the portal. Allow silent replacement of an existing portal only
1764 * if the unnamed portal is specified.
1766 if (portal_name
[0] == '\0')
1767 portal
= CreatePortal(portal_name
, true, true);
1769 portal
= CreatePortal(portal_name
, false, false);
1772 * Prepare to copy stuff into the portal's memory context. We do all this
1773 * copying first, because it could possibly fail (out-of-memory) and we
1774 * don't want a failure to occur between GetCachedPlan and
1775 * PortalDefineQuery; that would result in leaking our plancache refcount.
1777 oldContext
= MemoryContextSwitchTo(portal
->portalContext
);
1779 /* Copy the plan's query string into the portal */
1780 query_string
= pstrdup(psrc
->query_string
);
1782 /* Likewise make a copy of the statement name, unless it's unnamed */
1784 saved_stmt_name
= pstrdup(stmt_name
);
1786 saved_stmt_name
= NULL
;
1789 * Set a snapshot if we have parameters to fetch (since the input
1790 * functions might need it) or the query isn't a utility command (and
1791 * hence could require redoing parse analysis and planning). We keep the
1792 * snapshot active till we're done, so that plancache.c doesn't have to
1795 if (numParams
> 0 ||
1796 (psrc
->raw_parse_tree
&&
1797 analyze_requires_snapshot(psrc
->raw_parse_tree
)))
1799 PushActiveSnapshot(GetTransactionSnapshot());
1800 snapshot_set
= true;
1804 * Fetch parameters, if any, and store in the portal's memory context.
1808 char **knownTextValues
= NULL
; /* allocate on first use */
1809 BindParamCbData one_param_data
;
1812 * Set up an error callback so that if there's an error in this phase,
1813 * we can report the specific parameter causing the problem.
1815 one_param_data
.portalName
= portal
->name
;
1816 one_param_data
.paramno
= -1;
1817 one_param_data
.paramval
= NULL
;
1818 params_errcxt
.previous
= error_context_stack
;
1819 params_errcxt
.callback
= bind_param_error_callback
;
1820 params_errcxt
.arg
= (void *) &one_param_data
;
1821 error_context_stack
= ¶ms_errcxt
;
1823 params
= makeParamList(numParams
);
1825 for (int paramno
= 0; paramno
< numParams
; paramno
++)
1827 Oid ptype
= psrc
->param_types
[paramno
];
1831 StringInfoData pbuf
;
1835 one_param_data
.paramno
= paramno
;
1836 one_param_data
.paramval
= NULL
;
1838 plength
= pq_getmsgint(input_message
, 4);
1839 isNull
= (plength
== -1);
1846 * Rather than copying data around, we just initialize a
1847 * StringInfo pointing to the correct portion of the message
1848 * buffer. We assume we can scribble on the message buffer to
1849 * add a trailing NUL which is required for the input function
1852 pvalue
= unconstify(char *, pq_getmsgbytes(input_message
, plength
));
1853 csave
= pvalue
[plength
];
1854 pvalue
[plength
] = '\0';
1855 initReadOnlyStringInfo(&pbuf
, pvalue
, plength
);
1859 pbuf
.data
= NULL
; /* keep compiler quiet */
1863 if (numPFormats
> 1)
1864 pformat
= pformats
[paramno
];
1865 else if (numPFormats
> 0)
1866 pformat
= pformats
[0];
1868 pformat
= 0; /* default = text */
1870 if (pformat
== 0) /* text mode */
1876 getTypeInputInfo(ptype
, &typinput
, &typioparam
);
1879 * We have to do encoding conversion before calling the
1885 pstring
= pg_client_to_server(pbuf
.data
, plength
);
1887 /* Now we can log the input string in case of error */
1888 one_param_data
.paramval
= pstring
;
1890 pval
= OidInputFunctionCall(typinput
, pstring
, typioparam
, -1);
1892 one_param_data
.paramval
= NULL
;
1895 * If we might need to log parameters later, save a copy of
1896 * the converted string in MessageContext; then free the
1897 * result of encoding conversion, if any was done.
1901 if (log_parameter_max_length_on_error
!= 0)
1903 MemoryContext oldcxt
;
1905 oldcxt
= MemoryContextSwitchTo(MessageContext
);
1907 if (knownTextValues
== NULL
)
1908 knownTextValues
= palloc0_array(char *, numParams
);
1910 if (log_parameter_max_length_on_error
< 0)
1911 knownTextValues
[paramno
] = pstrdup(pstring
);
1915 * We can trim the saved string, knowing that we
1916 * won't print all of it. But we must copy at
1917 * least two more full characters than
1918 * BuildParamLogString wants to use; otherwise it
1919 * might fail to include the trailing ellipsis.
1921 knownTextValues
[paramno
] =
1923 log_parameter_max_length_on_error
1924 + 2 * MAX_MULTIBYTE_CHAR_LEN
);
1927 MemoryContextSwitchTo(oldcxt
);
1929 if (pstring
!= pbuf
.data
)
1933 else if (pformat
== 1) /* binary mode */
1940 * Call the parameter type's binary input converter
1942 getTypeBinaryInputInfo(ptype
, &typreceive
, &typioparam
);
1949 pval
= OidReceiveFunctionCall(typreceive
, bufptr
, typioparam
, -1);
1951 /* Trouble if it didn't eat the whole buffer */
1952 if (!isNull
&& pbuf
.cursor
!= pbuf
.len
)
1954 (errcode(ERRCODE_INVALID_BINARY_REPRESENTATION
),
1955 errmsg("incorrect binary data format in bind parameter %d",
1961 (errcode(ERRCODE_INVALID_PARAMETER_VALUE
),
1962 errmsg("unsupported format code: %d",
1964 pval
= 0; /* keep compiler quiet */
1967 /* Restore message buffer contents */
1969 pbuf
.data
[plength
] = csave
;
1971 params
->params
[paramno
].value
= pval
;
1972 params
->params
[paramno
].isnull
= isNull
;
1975 * We mark the params as CONST. This ensures that any custom plan
1976 * makes full use of the parameter values.
1978 params
->params
[paramno
].pflags
= PARAM_FLAG_CONST
;
1979 params
->params
[paramno
].ptype
= ptype
;
1982 /* Pop the per-parameter error callback */
1983 error_context_stack
= error_context_stack
->previous
;
1986 * Once all parameters have been received, prepare for printing them
1987 * in future errors, if configured to do so. (This is saved in the
1988 * portal, so that they'll appear when the query is executed later.)
1990 if (log_parameter_max_length_on_error
!= 0)
1991 params
->paramValuesStr
=
1992 BuildParamLogString(params
,
1994 log_parameter_max_length_on_error
);
1999 /* Done storing stuff in portal's context */
2000 MemoryContextSwitchTo(oldContext
);
2003 * Set up another error callback so that all the parameters are logged if
2004 * we get an error during the rest of the BIND processing.
2006 params_data
.portalName
= portal
->name
;
2007 params_data
.params
= params
;
2008 params_errcxt
.previous
= error_context_stack
;
2009 params_errcxt
.callback
= ParamsErrorCallback
;
2010 params_errcxt
.arg
= (void *) ¶ms_data
;
2011 error_context_stack
= ¶ms_errcxt
;
2013 /* Get the result format codes */
2014 numRFormats
= pq_getmsgint(input_message
, 2);
2015 if (numRFormats
> 0)
2017 rformats
= palloc_array(int16
, numRFormats
);
2018 for (int i
= 0; i
< numRFormats
; i
++)
2019 rformats
[i
] = pq_getmsgint(input_message
, 2);
2022 pq_getmsgend(input_message
);
2025 * Obtain a plan from the CachedPlanSource. Any cruft from (re)planning
2026 * will be generated in MessageContext. The plan refcount will be
2027 * assigned to the Portal, so it will be released at portal destruction.
2029 cplan
= GetCachedPlan(psrc
, params
, NULL
, NULL
);
2032 * Now we can define the portal.
2034 * DO NOT put any code that could possibly throw an error between the
2035 * above GetCachedPlan call and here.
2037 PortalDefineQuery(portal
,
2044 /* Done with the snapshot used for parameter I/O and parsing/planning */
2046 PopActiveSnapshot();
2049 * And we're ready to start portal execution.
2051 PortalStart(portal
, params
, 0, InvalidSnapshot
);
2054 * Apply the result format requests to the portal.
2056 PortalSetResultFormat(portal
, numRFormats
, rformats
);
2059 * Done binding; remove the parameters error callback. Entries emitted
2060 * later determine independently whether to log the parameters or not.
2062 error_context_stack
= error_context_stack
->previous
;
2065 * Send BindComplete.
2067 if (whereToSendOutput
== DestRemote
)
2068 pq_putemptymessage(PqMsg_BindComplete
);
2071 * Emit duration logging if appropriate.
2073 switch (check_log_duration(msec_str
, false))
2077 (errmsg("duration: %s ms", msec_str
),
2078 errhidestmt(true)));
2082 (errmsg("duration: %s ms bind %s%s%s: %s",
2084 *stmt_name
? stmt_name
: "<unnamed>",
2085 *portal_name
? "/" : "",
2086 *portal_name
? portal_name
: "",
2087 psrc
->query_string
),
2089 errdetail_params(params
)));
2093 if (save_log_statement_stats
)
2094 ShowUsage("BIND MESSAGE STATISTICS");
2096 valgrind_report_error_query(debug_query_string
);
2098 debug_query_string
= NULL
;
2102 * exec_execute_message
2104 * Process an "Execute" message for a portal
2107 exec_execute_message(const char *portal_name
, long max_rows
)
2110 DestReceiver
*receiver
;
2114 const char *sourceText
;
2115 const char *prepStmtName
;
2116 ParamListInfo portalParams
;
2117 bool save_log_statement_stats
= log_statement_stats
;
2118 bool is_xact_command
;
2119 bool execute_is_fetch
;
2120 bool was_logged
= false;
2122 ParamsErrorCbData params_data
;
2123 ErrorContextCallback params_errcxt
;
2124 const char *cmdtagname
;
2128 /* Adjust destination to tell printtup.c what to do */
2129 dest
= whereToSendOutput
;
2130 if (dest
== DestRemote
)
2131 dest
= DestRemoteExecute
;
2133 portal
= GetPortalByName(portal_name
);
2134 if (!PortalIsValid(portal
))
2136 (errcode(ERRCODE_UNDEFINED_CURSOR
),
2137 errmsg("portal \"%s\" does not exist", portal_name
)));
2140 * If the original query was a null string, just return
2141 * EmptyQueryResponse.
2143 if (portal
->commandTag
== CMDTAG_UNKNOWN
)
2145 Assert(portal
->stmts
== NIL
);
2150 /* Does the portal contain a transaction command? */
2151 is_xact_command
= IsTransactionStmtList(portal
->stmts
);
2154 * We must copy the sourceText and prepStmtName into MessageContext in
2155 * case the portal is destroyed during finish_xact_command. We do not
2156 * make a copy of the portalParams though, preferring to just not print
2157 * them in that case.
2159 sourceText
= pstrdup(portal
->sourceText
);
2160 if (portal
->prepStmtName
)
2161 prepStmtName
= pstrdup(portal
->prepStmtName
);
2163 prepStmtName
= "<unnamed>";
2164 portalParams
= portal
->portalParams
;
2167 * Report query to various monitoring facilities.
2169 debug_query_string
= sourceText
;
2171 pgstat_report_activity(STATE_RUNNING
, sourceText
);
2173 foreach(lc
, portal
->stmts
)
2175 PlannedStmt
*stmt
= lfirst_node(PlannedStmt
, lc
);
2177 if (stmt
->queryId
!= UINT64CONST(0))
2179 pgstat_report_query_id(stmt
->queryId
, false);
2184 cmdtagname
= GetCommandTagNameAndLen(portal
->commandTag
, &cmdtaglen
);
2186 set_ps_display_with_len(cmdtagname
, cmdtaglen
);
2188 if (save_log_statement_stats
)
2191 BeginCommand(portal
->commandTag
, dest
);
2194 * Create dest receiver in MessageContext (we don't want it in transaction
2195 * context, because that may get deleted if portal contains VACUUM).
2197 receiver
= CreateDestReceiver(dest
);
2198 if (dest
== DestRemoteExecute
)
2199 SetRemoteDestReceiverParams(receiver
, portal
);
2202 * Ensure we are in a transaction command (this should normally be the
2203 * case already due to prior BIND).
2205 start_xact_command();
2208 * If we re-issue an Execute protocol request against an existing portal,
2209 * then we are only fetching more rows rather than completely re-executing
2210 * the query from the start. atStart is never reset for a v3 portal, so we
2211 * are safe to use this check.
2213 execute_is_fetch
= !portal
->atStart
;
2215 /* Log immediately if dictated by log_statement */
2216 if (check_log_statement(portal
->stmts
))
2219 (errmsg("%s %s%s%s: %s",
2221 _("execute fetch from") :
2224 *portal_name
? "/" : "",
2225 *portal_name
? portal_name
: "",
2228 errdetail_params(portalParams
)));
2233 * If we are in aborted transaction state, the only portals we can
2234 * actually run are those containing COMMIT or ROLLBACK commands.
2236 if (IsAbortedTransactionBlockState() &&
2237 !IsTransactionExitStmtList(portal
->stmts
))
2239 (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION
),
2240 errmsg("current transaction is aborted, "
2241 "commands ignored until end of transaction block"),
2242 errdetail_abort()));
2244 /* Check for cancel signal before we start execution */
2245 CHECK_FOR_INTERRUPTS();
2248 * Okay to run the portal. Set the error callback so that parameters are
2249 * logged. The parameters must have been saved during the bind phase.
2251 params_data
.portalName
= portal
->name
;
2252 params_data
.params
= portalParams
;
2253 params_errcxt
.previous
= error_context_stack
;
2254 params_errcxt
.callback
= ParamsErrorCallback
;
2255 params_errcxt
.arg
= (void *) ¶ms_data
;
2256 error_context_stack
= ¶ms_errcxt
;
2259 max_rows
= FETCH_ALL
;
2261 completed
= PortalRun(portal
,
2263 true, /* always top level */
2264 !execute_is_fetch
&& max_rows
== FETCH_ALL
,
2269 receiver
->rDestroy(receiver
);
2271 /* Done executing; remove the params error callback */
2272 error_context_stack
= error_context_stack
->previous
;
2276 if (is_xact_command
|| (MyXactFlags
& XACT_FLAGS_NEEDIMMEDIATECOMMIT
))
2279 * If this was a transaction control statement, commit it. We
2280 * will start a new xact command for the next command (if any).
2281 * Likewise if the statement required immediate commit. Without
2282 * this provision, we wouldn't force commit until Sync is
2283 * received, which creates a hazard if the client tries to
2284 * pipeline immediate-commit statements.
2286 finish_xact_command();
2289 * These commands typically don't have any parameters, and even if
2290 * one did we couldn't print them now because the storage went
2291 * away during finish_xact_command. So pretend there were none.
2293 portalParams
= NULL
;
2298 * We need a CommandCounterIncrement after every query, except
2299 * those that start or end a transaction block.
2301 CommandCounterIncrement();
2304 * Set XACT_FLAGS_PIPELINING whenever we complete an Execute
2305 * message without immediately committing the transaction.
2307 MyXactFlags
|= XACT_FLAGS_PIPELINING
;
2310 * Disable statement timeout whenever we complete an Execute
2311 * message. The next protocol message will start a fresh timeout.
2313 disable_statement_timeout();
2316 /* Send appropriate CommandComplete to client */
2317 EndCommand(&qc
, dest
, false);
2321 /* Portal run not complete, so send PortalSuspended */
2322 if (whereToSendOutput
== DestRemote
)
2323 pq_putemptymessage(PqMsg_PortalSuspended
);
2326 * Set XACT_FLAGS_PIPELINING whenever we suspend an Execute message,
2329 MyXactFlags
|= XACT_FLAGS_PIPELINING
;
2333 * Emit duration logging if appropriate.
2335 switch (check_log_duration(msec_str
, was_logged
))
2339 (errmsg("duration: %s ms", msec_str
),
2340 errhidestmt(true)));
2344 (errmsg("duration: %s ms %s %s%s%s: %s",
2347 _("execute fetch from") :
2350 *portal_name
? "/" : "",
2351 *portal_name
? portal_name
: "",
2354 errdetail_params(portalParams
)));
2358 if (save_log_statement_stats
)
2359 ShowUsage("EXECUTE MESSAGE STATISTICS");
2361 valgrind_report_error_query(debug_query_string
);
2363 debug_query_string
= NULL
;
2367 * check_log_statement
2368 * Determine whether command should be logged because of log_statement
2370 * stmt_list can be either raw grammar output or a list of planned
2374 check_log_statement(List
*stmt_list
)
2376 ListCell
*stmt_item
;
2378 if (log_statement
== LOGSTMT_NONE
)
2380 if (log_statement
== LOGSTMT_ALL
)
2383 /* Else we have to inspect the statement(s) to see whether to log */
2384 foreach(stmt_item
, stmt_list
)
2386 Node
*stmt
= (Node
*) lfirst(stmt_item
);
2388 if (GetCommandLogLevel(stmt
) <= log_statement
)
2396 * check_log_duration
2397 * Determine whether current command's duration should be logged
2398 * We also check if this statement in this transaction must be logged
2399 * (regardless of its duration).
2402 * 0 if no logging is needed
2403 * 1 if just the duration should be logged
2404 * 2 if duration and query details should be logged
2406 * If logging is needed, the duration in msec is formatted into msec_str[],
2407 * which must be a 32-byte buffer.
2409 * was_logged should be true if caller already logged query details (this
2410 * essentially prevents 2 from being returned).
2413 check_log_duration(char *msec_str
, bool was_logged
)
2415 if (log_duration
|| log_min_duration_sample
>= 0 ||
2416 log_min_duration_statement
>= 0 || xact_is_sampled
)
2421 bool exceeded_duration
;
2422 bool exceeded_sample_duration
;
2423 bool in_sample
= false;
2425 TimestampDifference(GetCurrentStatementStartTimestamp(),
2426 GetCurrentTimestamp(),
2428 msecs
= usecs
/ 1000;
2431 * This odd-looking test for log_min_duration_* being exceeded is
2432 * designed to avoid integer overflow with very long durations: don't
2433 * compute secs * 1000 until we've verified it will fit in int.
2435 exceeded_duration
= (log_min_duration_statement
== 0 ||
2436 (log_min_duration_statement
> 0 &&
2437 (secs
> log_min_duration_statement
/ 1000 ||
2438 secs
* 1000 + msecs
>= log_min_duration_statement
)));
2440 exceeded_sample_duration
= (log_min_duration_sample
== 0 ||
2441 (log_min_duration_sample
> 0 &&
2442 (secs
> log_min_duration_sample
/ 1000 ||
2443 secs
* 1000 + msecs
>= log_min_duration_sample
)));
2446 * Do not log if log_statement_sample_rate = 0. Log a sample if
2447 * log_statement_sample_rate <= 1 and avoid unnecessary PRNG call if
2448 * log_statement_sample_rate = 1.
2450 if (exceeded_sample_duration
)
2451 in_sample
= log_statement_sample_rate
!= 0 &&
2452 (log_statement_sample_rate
== 1 ||
2453 pg_prng_double(&pg_global_prng_state
) <= log_statement_sample_rate
);
2455 if (exceeded_duration
|| in_sample
|| log_duration
|| xact_is_sampled
)
2457 snprintf(msec_str
, 32, "%ld.%03d",
2458 secs
* 1000 + msecs
, usecs
% 1000);
2459 if ((exceeded_duration
|| in_sample
|| xact_is_sampled
) && !was_logged
)
2472 * Add an errdetail() line showing the query referenced by an EXECUTE, if any.
2473 * The argument is the raw parsetree list.
2476 errdetail_execute(List
*raw_parsetree_list
)
2478 ListCell
*parsetree_item
;
2480 foreach(parsetree_item
, raw_parsetree_list
)
2482 RawStmt
*parsetree
= lfirst_node(RawStmt
, parsetree_item
);
2484 if (IsA(parsetree
->stmt
, ExecuteStmt
))
2486 ExecuteStmt
*stmt
= (ExecuteStmt
*) parsetree
->stmt
;
2487 PreparedStatement
*pstmt
;
2489 pstmt
= FetchPreparedStatement(stmt
->name
, false);
2492 errdetail("prepare: %s", pstmt
->plansource
->query_string
);
2504 * Add an errdetail() line showing bind-parameter data, if available.
2505 * Note that this is only used for statement logging, so it is controlled
2506 * by log_parameter_max_length not log_parameter_max_length_on_error.
2509 errdetail_params(ParamListInfo params
)
2511 if (params
&& params
->numParams
> 0 && log_parameter_max_length
!= 0)
2515 str
= BuildParamLogString(params
, NULL
, log_parameter_max_length
);
2516 if (str
&& str
[0] != '\0')
2517 errdetail("Parameters: %s", str
);
2526 * Add an errdetail() line showing abort reason, if any.
2529 errdetail_abort(void)
2531 if (MyProc
->recoveryConflictPending
)
2532 errdetail("Abort reason: recovery conflict");
2538 * errdetail_recovery_conflict
2540 * Add an errdetail() line showing conflict source.
2543 errdetail_recovery_conflict(ProcSignalReason reason
)
2547 case PROCSIG_RECOVERY_CONFLICT_BUFFERPIN
:
2548 errdetail("User was holding shared buffer pin for too long.");
2550 case PROCSIG_RECOVERY_CONFLICT_LOCK
:
2551 errdetail("User was holding a relation lock for too long.");
2553 case PROCSIG_RECOVERY_CONFLICT_TABLESPACE
:
2554 errdetail("User was or might have been using tablespace that must be dropped.");
2556 case PROCSIG_RECOVERY_CONFLICT_SNAPSHOT
:
2557 errdetail("User query might have needed to see row versions that must be removed.");
2559 case PROCSIG_RECOVERY_CONFLICT_LOGICALSLOT
:
2560 errdetail("User was using a logical replication slot that must be invalidated.");
2562 case PROCSIG_RECOVERY_CONFLICT_STARTUP_DEADLOCK
:
2563 errdetail("User transaction caused buffer deadlock with recovery.");
2565 case PROCSIG_RECOVERY_CONFLICT_DATABASE
:
2566 errdetail("User was connected to a database that must be dropped.");
2577 * bind_param_error_callback
2579 * Error context callback used while parsing parameters in a Bind message
2582 bind_param_error_callback(void *arg
)
2584 BindParamCbData
*data
= (BindParamCbData
*) arg
;
2588 if (data
->paramno
< 0)
2591 /* If we have a textual value, quote it, and trim if necessary */
2594 initStringInfo(&buf
);
2595 appendStringInfoStringQuoted(&buf
, data
->paramval
,
2596 log_parameter_max_length_on_error
);
2597 quotedval
= buf
.data
;
2602 if (data
->portalName
&& data
->portalName
[0] != '\0')
2605 errcontext("portal \"%s\" parameter $%d = %s",
2606 data
->portalName
, data
->paramno
+ 1, quotedval
);
2608 errcontext("portal \"%s\" parameter $%d",
2609 data
->portalName
, data
->paramno
+ 1);
2614 errcontext("unnamed portal parameter $%d = %s",
2615 data
->paramno
+ 1, quotedval
);
2617 errcontext("unnamed portal parameter $%d",
2626 * exec_describe_statement_message
2628 * Process a "Describe" message for a prepared statement
2631 exec_describe_statement_message(const char *stmt_name
)
2633 CachedPlanSource
*psrc
;
2636 * Start up a transaction command. (Note that this will normally change
2637 * current memory context.) Nothing happens if we are already in one.
2639 start_xact_command();
2641 /* Switch back to message context */
2642 MemoryContextSwitchTo(MessageContext
);
2644 /* Find prepared statement */
2645 if (stmt_name
[0] != '\0')
2647 PreparedStatement
*pstmt
;
2649 pstmt
= FetchPreparedStatement(stmt_name
, true);
2650 psrc
= pstmt
->plansource
;
2654 /* special-case the unnamed statement */
2655 psrc
= unnamed_stmt_psrc
;
2658 (errcode(ERRCODE_UNDEFINED_PSTATEMENT
),
2659 errmsg("unnamed prepared statement does not exist")));
2662 /* Prepared statements shouldn't have changeable result descs */
2663 Assert(psrc
->fixed_result
);
2666 * If we are in aborted transaction state, we can't run
2667 * SendRowDescriptionMessage(), because that needs catalog accesses.
2668 * Hence, refuse to Describe statements that return data. (We shouldn't
2669 * just refuse all Describes, since that might break the ability of some
2670 * clients to issue COMMIT or ROLLBACK commands, if they use code that
2671 * blindly Describes whatever it does.) We can Describe parameters
2672 * without doing anything dangerous, so we don't restrict that.
2674 if (IsAbortedTransactionBlockState() &&
2677 (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION
),
2678 errmsg("current transaction is aborted, "
2679 "commands ignored until end of transaction block"),
2680 errdetail_abort()));
2682 if (whereToSendOutput
!= DestRemote
)
2683 return; /* can't actually do anything... */
2686 * First describe the parameters...
2688 pq_beginmessage_reuse(&row_description_buf
, PqMsg_ParameterDescription
);
2689 pq_sendint16(&row_description_buf
, psrc
->num_params
);
2691 for (int i
= 0; i
< psrc
->num_params
; i
++)
2693 Oid ptype
= psrc
->param_types
[i
];
2695 pq_sendint32(&row_description_buf
, (int) ptype
);
2697 pq_endmessage_reuse(&row_description_buf
);
2700 * Next send RowDescription or NoData to describe the result...
2702 if (psrc
->resultDesc
)
2706 /* Get the plan's primary targetlist */
2707 tlist
= CachedPlanGetTargetList(psrc
, NULL
);
2709 SendRowDescriptionMessage(&row_description_buf
,
2715 pq_putemptymessage(PqMsg_NoData
);
2719 * exec_describe_portal_message
2721 * Process a "Describe" message for a portal
2724 exec_describe_portal_message(const char *portal_name
)
2729 * Start up a transaction command. (Note that this will normally change
2730 * current memory context.) Nothing happens if we are already in one.
2732 start_xact_command();
2734 /* Switch back to message context */
2735 MemoryContextSwitchTo(MessageContext
);
2737 portal
= GetPortalByName(portal_name
);
2738 if (!PortalIsValid(portal
))
2740 (errcode(ERRCODE_UNDEFINED_CURSOR
),
2741 errmsg("portal \"%s\" does not exist", portal_name
)));
2744 * If we are in aborted transaction state, we can't run
2745 * SendRowDescriptionMessage(), because that needs catalog accesses.
2746 * Hence, refuse to Describe portals that return data. (We shouldn't just
2747 * refuse all Describes, since that might break the ability of some
2748 * clients to issue COMMIT or ROLLBACK commands, if they use code that
2749 * blindly Describes whatever it does.)
2751 if (IsAbortedTransactionBlockState() &&
2754 (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION
),
2755 errmsg("current transaction is aborted, "
2756 "commands ignored until end of transaction block"),
2757 errdetail_abort()));
2759 if (whereToSendOutput
!= DestRemote
)
2760 return; /* can't actually do anything... */
2762 if (portal
->tupDesc
)
2763 SendRowDescriptionMessage(&row_description_buf
,
2765 FetchPortalTargetList(portal
),
2768 pq_putemptymessage(PqMsg_NoData
);
2773 * Convenience routines for starting/committing a single command.
2776 start_xact_command(void)
2780 StartTransactionCommand();
2782 xact_started
= true;
2786 * Start statement timeout if necessary. Note that this'll intentionally
2787 * not reset the clock on an already started timeout, to avoid the timing
2788 * overhead when start_xact_command() is invoked repeatedly, without an
2789 * interceding finish_xact_command() (e.g. parse/bind/execute). If that's
2790 * not desired, the timeout has to be disabled explicitly.
2792 enable_statement_timeout();
2794 /* Start timeout for checking if the client has gone away if necessary. */
2795 if (client_connection_check_interval
> 0 &&
2796 IsUnderPostmaster
&&
2798 !get_timeout_active(CLIENT_CONNECTION_CHECK_TIMEOUT
))
2799 enable_timeout_after(CLIENT_CONNECTION_CHECK_TIMEOUT
,
2800 client_connection_check_interval
);
2804 finish_xact_command(void)
2806 /* cancel active statement timeout after each command */
2807 disable_statement_timeout();
2811 CommitTransactionCommand();
2813 #ifdef MEMORY_CONTEXT_CHECKING
2814 /* Check all memory contexts that weren't freed during commit */
2815 /* (those that were, were checked before being deleted) */
2816 MemoryContextCheck(TopMemoryContext
);
2819 #ifdef SHOW_MEMORY_STATS
2820 /* Print mem stats after each commit for leak tracking */
2821 MemoryContextStats(TopMemoryContext
);
2824 xact_started
= false;
2830 * Convenience routines for checking whether a statement is one of the
2831 * ones that we allow in transaction-aborted state.
2834 /* Test a bare parsetree */
2836 IsTransactionExitStmt(Node
*parsetree
)
2838 if (parsetree
&& IsA(parsetree
, TransactionStmt
))
2840 TransactionStmt
*stmt
= (TransactionStmt
*) parsetree
;
2842 if (stmt
->kind
== TRANS_STMT_COMMIT
||
2843 stmt
->kind
== TRANS_STMT_PREPARE
||
2844 stmt
->kind
== TRANS_STMT_ROLLBACK
||
2845 stmt
->kind
== TRANS_STMT_ROLLBACK_TO
)
2851 /* Test a list that contains PlannedStmt nodes */
2853 IsTransactionExitStmtList(List
*pstmts
)
2855 if (list_length(pstmts
) == 1)
2857 PlannedStmt
*pstmt
= linitial_node(PlannedStmt
, pstmts
);
2859 if (pstmt
->commandType
== CMD_UTILITY
&&
2860 IsTransactionExitStmt(pstmt
->utilityStmt
))
2866 /* Test a list that contains PlannedStmt nodes */
2868 IsTransactionStmtList(List
*pstmts
)
2870 if (list_length(pstmts
) == 1)
2872 PlannedStmt
*pstmt
= linitial_node(PlannedStmt
, pstmts
);
2874 if (pstmt
->commandType
== CMD_UTILITY
&&
2875 IsA(pstmt
->utilityStmt
, TransactionStmt
))
2881 /* Release any existing unnamed prepared statement */
2883 drop_unnamed_stmt(void)
2885 /* paranoia to avoid a dangling pointer in case of error */
2886 if (unnamed_stmt_psrc
)
2888 CachedPlanSource
*psrc
= unnamed_stmt_psrc
;
2890 unnamed_stmt_psrc
= NULL
;
2891 DropCachedPlan(psrc
);
2896 /* --------------------------------
2897 * signal handler routines used in PostgresMain()
2898 * --------------------------------
2902 * quickdie() occurs when signaled SIGQUIT by the postmaster.
2904 * Either some backend has bought the farm, or we've been told to shut down
2905 * "immediately"; so we need to stop what we're doing and exit.
2908 quickdie(SIGNAL_ARGS
)
2910 sigaddset(&BlockSig
, SIGQUIT
); /* prevent nested calls */
2911 sigprocmask(SIG_SETMASK
, &BlockSig
, NULL
);
2914 * Prevent interrupts while exiting; though we just blocked signals that
2915 * would queue new interrupts, one may have been pending. We don't want a
2916 * quickdie() downgraded to a mere query cancel.
2921 * If we're aborting out of client auth, don't risk trying to send
2922 * anything to the client; we will likely violate the protocol, not to
2923 * mention that we may have interrupted the guts of OpenSSL or some
2924 * authentication library.
2926 if (ClientAuthInProgress
&& whereToSendOutput
== DestRemote
)
2927 whereToSendOutput
= DestNone
;
2930 * Notify the client before exiting, to give a clue on what happened.
2932 * It's dubious to call ereport() from a signal handler. It is certainly
2933 * not async-signal safe. But it seems better to try, than to disconnect
2934 * abruptly and leave the client wondering what happened. It's remotely
2935 * possible that we crash or hang while trying to send the message, but
2936 * receiving a SIGQUIT is a sign that something has already gone badly
2937 * wrong, so there's not much to lose. Assuming the postmaster is still
2938 * running, it will SIGKILL us soon if we get stuck for some reason.
2940 * One thing we can do to make this a tad safer is to clear the error
2941 * context stack, so that context callbacks are not called. That's a lot
2942 * less code that could be reached here, and the context info is unlikely
2943 * to be very relevant to a SIGQUIT report anyway.
2945 error_context_stack
= NULL
;
2948 * When responding to a postmaster-issued signal, we send the message only
2949 * to the client; sending to the server log just creates log spam, plus
2950 * it's more code that we need to hope will work in a signal handler.
2952 * Ideally these should be ereport(FATAL), but then we'd not get control
2953 * back to force the correct type of process exit.
2955 switch (GetQuitSignalReason())
2957 case PMQUIT_NOT_SENT
:
2958 /* Hmm, SIGQUIT arrived out of the blue */
2960 (errcode(ERRCODE_ADMIN_SHUTDOWN
),
2961 errmsg("terminating connection because of unexpected SIGQUIT signal")));
2963 case PMQUIT_FOR_CRASH
:
2964 /* A crash-and-restart cycle is in progress */
2965 ereport(WARNING_CLIENT_ONLY
,
2966 (errcode(ERRCODE_CRASH_SHUTDOWN
),
2967 errmsg("terminating connection because of crash of another server process"),
2968 errdetail("The postmaster has commanded this server process to roll back"
2969 " the current transaction and exit, because another"
2970 " server process exited abnormally and possibly corrupted"
2972 errhint("In a moment you should be able to reconnect to the"
2973 " database and repeat your command.")));
2975 case PMQUIT_FOR_STOP
:
2976 /* Immediate-mode stop */
2977 ereport(WARNING_CLIENT_ONLY
,
2978 (errcode(ERRCODE_ADMIN_SHUTDOWN
),
2979 errmsg("terminating connection due to immediate shutdown command")));
2984 * We DO NOT want to run proc_exit() or atexit() callbacks -- we're here
2985 * because shared memory may be corrupted, so we don't want to try to
2986 * clean up our transaction. Just nail the windows shut and get out of
2987 * town. The callbacks wouldn't be safe to run from a signal handler,
2990 * Note we do _exit(2) not _exit(0). This is to force the postmaster into
2991 * a system reset cycle if someone sends a manual SIGQUIT to a random
2992 * backend. This is necessary precisely because we don't clean up our
2993 * shared memory state. (The "dead man switch" mechanism in pmsignal.c
2994 * should ensure the postmaster sees this as a crash, too, but no harm in
2995 * being doubly sure.)
3001 * Shutdown signal from postmaster: abort transaction and exit
3002 * at soonest convenient time
3007 /* Don't joggle the elbow of proc_exit */
3008 if (!proc_exit_inprogress
)
3010 InterruptPending
= true;
3011 ProcDiePending
= true;
3014 /* for the cumulative stats system */
3015 pgStatSessionEndCause
= DISCONNECT_KILLED
;
3017 /* If we're still here, waken anything waiting on the process latch */
3021 * If we're in single user mode, we want to quit immediately - we can't
3022 * rely on latches as they wouldn't work when stdin/stdout is a file.
3023 * Rather ugly, but it's unlikely to be worthwhile to invest much more
3024 * effort just for the benefit of single user mode.
3026 if (DoingCommandRead
&& whereToSendOutput
!= DestRemote
)
3027 ProcessInterrupts();
3031 * Query-cancel signal from postmaster: abort current transaction
3032 * at soonest convenient time
3035 StatementCancelHandler(SIGNAL_ARGS
)
3038 * Don't joggle the elbow of proc_exit
3040 if (!proc_exit_inprogress
)
3042 InterruptPending
= true;
3043 QueryCancelPending
= true;
3046 /* If we're still here, waken anything waiting on the process latch */
3050 /* signal handler for floating point exception */
3052 FloatExceptionHandler(SIGNAL_ARGS
)
3054 /* We're not returning, so no need to save errno */
3056 (errcode(ERRCODE_FLOATING_POINT_EXCEPTION
),
3057 errmsg("floating-point exception"),
3058 errdetail("An invalid floating-point operation was signaled. "
3059 "This probably means an out-of-range result or an "
3060 "invalid operation, such as division by zero.")));
3064 * Tell the next CHECK_FOR_INTERRUPTS() to check for a particular type of
3065 * recovery conflict. Runs in a SIGUSR1 handler.
3068 HandleRecoveryConflictInterrupt(ProcSignalReason reason
)
3070 RecoveryConflictPendingReasons
[reason
] = true;
3071 RecoveryConflictPending
= true;
3072 InterruptPending
= true;
3073 /* latch will be set by procsignal_sigusr1_handler */
3077 * Check one individual conflict reason.
3080 ProcessRecoveryConflictInterrupt(ProcSignalReason reason
)
3084 case PROCSIG_RECOVERY_CONFLICT_STARTUP_DEADLOCK
:
3087 * If we aren't waiting for a lock we can never deadlock.
3089 if (!IsWaitingForLock())
3092 /* Intentional fall through to check wait for pin */
3095 case PROCSIG_RECOVERY_CONFLICT_BUFFERPIN
:
3098 * If PROCSIG_RECOVERY_CONFLICT_BUFFERPIN is requested but we
3099 * aren't blocking the Startup process there is nothing more to
3102 * When PROCSIG_RECOVERY_CONFLICT_STARTUP_DEADLOCK is requested,
3103 * if we're waiting for locks and the startup process is not
3104 * waiting for buffer pin (i.e., also waiting for locks), we set
3105 * the flag so that ProcSleep() will check for deadlocks.
3107 if (!HoldingBufferPinThatDelaysRecovery())
3109 if (reason
== PROCSIG_RECOVERY_CONFLICT_STARTUP_DEADLOCK
&&
3110 GetStartupBufferPinWaitBufId() < 0)
3111 CheckDeadLockAlert();
3115 MyProc
->recoveryConflictPending
= true;
3117 /* Intentional fall through to error handling */
3120 case PROCSIG_RECOVERY_CONFLICT_LOCK
:
3121 case PROCSIG_RECOVERY_CONFLICT_TABLESPACE
:
3122 case PROCSIG_RECOVERY_CONFLICT_SNAPSHOT
:
3125 * If we aren't in a transaction any longer then ignore.
3127 if (!IsTransactionOrTransactionBlock())
3132 case PROCSIG_RECOVERY_CONFLICT_LOGICALSLOT
:
3135 * If we're not in a subtransaction then we are OK to throw an
3136 * ERROR to resolve the conflict. Otherwise drop through to the
3139 * PROCSIG_RECOVERY_CONFLICT_LOGICALSLOT is a special case that
3140 * always throws an ERROR (ie never promotes to FATAL), though it
3141 * still has to respect QueryCancelHoldoffCount, so it shares this
3142 * code path. Logical decoding slots are only acquired while
3143 * performing logical decoding. During logical decoding no user
3144 * controlled code is run. During [sub]transaction abort, the
3145 * slot is released. Therefore user controlled code cannot
3146 * intercept an error before the replication slot is released.
3148 * XXX other times that we can throw just an ERROR *may* be
3149 * PROCSIG_RECOVERY_CONFLICT_LOCK if no locks are held in parent
3152 * PROCSIG_RECOVERY_CONFLICT_SNAPSHOT if no snapshots are held by
3153 * parent transactions and the transaction is not
3154 * transaction-snapshot mode
3156 * PROCSIG_RECOVERY_CONFLICT_TABLESPACE if no temp files or
3157 * cursors open in parent transactions
3159 if (reason
== PROCSIG_RECOVERY_CONFLICT_LOGICALSLOT
||
3160 !IsSubTransaction())
3163 * If we already aborted then we no longer need to cancel. We
3164 * do this here since we do not wish to ignore aborted
3165 * subtransactions, which must cause FATAL, currently.
3167 if (IsAbortedTransactionBlockState())
3171 * If a recovery conflict happens while we are waiting for
3172 * input from the client, the client is presumably just
3173 * sitting idle in a transaction, preventing recovery from
3174 * making progress. We'll drop through to the FATAL case
3175 * below to dislodge it, in that case.
3177 if (!DoingCommandRead
)
3179 /* Avoid losing sync in the FE/BE protocol. */
3180 if (QueryCancelHoldoffCount
!= 0)
3183 * Re-arm and defer this interrupt until later. See
3184 * similar code in ProcessInterrupts().
3186 RecoveryConflictPendingReasons
[reason
] = true;
3187 RecoveryConflictPending
= true;
3188 InterruptPending
= true;
3193 * We are cleared to throw an ERROR. Either it's the
3194 * logical slot case, or we have a top-level transaction
3195 * that we can abort and a conflict that isn't inherently
3199 pgstat_report_recovery_conflict(reason
);
3201 (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE
),
3202 errmsg("canceling statement due to conflict with recovery"),
3203 errdetail_recovery_conflict(reason
)));
3208 /* Intentional fall through to session cancel */
3211 case PROCSIG_RECOVERY_CONFLICT_DATABASE
:
3214 * Retrying is not possible because the database is dropped, or we
3215 * decided above that we couldn't resolve the conflict with an
3216 * ERROR and fell through. Terminate the session.
3218 pgstat_report_recovery_conflict(reason
);
3220 (errcode(reason
== PROCSIG_RECOVERY_CONFLICT_DATABASE
?
3221 ERRCODE_DATABASE_DROPPED
:
3222 ERRCODE_T_R_SERIALIZATION_FAILURE
),
3223 errmsg("terminating connection due to conflict with recovery"),
3224 errdetail_recovery_conflict(reason
),
3225 errhint("In a moment you should be able to reconnect to the"
3226 " database and repeat your command.")));
3230 elog(FATAL
, "unrecognized conflict mode: %d", (int) reason
);
3235 * Check each possible recovery conflict reason.
3238 ProcessRecoveryConflictInterrupts(void)
3241 * We don't need to worry about joggling the elbow of proc_exit, because
3242 * proc_exit_prepare() holds interrupts, so ProcessInterrupts() won't call
3245 Assert(!proc_exit_inprogress
);
3246 Assert(InterruptHoldoffCount
== 0);
3247 Assert(RecoveryConflictPending
);
3249 RecoveryConflictPending
= false;
3251 for (ProcSignalReason reason
= PROCSIG_RECOVERY_CONFLICT_FIRST
;
3252 reason
<= PROCSIG_RECOVERY_CONFLICT_LAST
;
3255 if (RecoveryConflictPendingReasons
[reason
])
3257 RecoveryConflictPendingReasons
[reason
] = false;
3258 ProcessRecoveryConflictInterrupt(reason
);
3264 * ProcessInterrupts: out-of-line portion of CHECK_FOR_INTERRUPTS() macro
3266 * If an interrupt condition is pending, and it's safe to service it,
3267 * then clear the flag and accept the interrupt. Called only when
3268 * InterruptPending is true.
3270 * Note: if INTERRUPTS_CAN_BE_PROCESSED() is true, then ProcessInterrupts
3271 * is guaranteed to clear the InterruptPending flag before returning.
3272 * (This is not the same as guaranteeing that it's still clear when we
3273 * return; another interrupt could have arrived. But we promise that
3274 * any pre-existing one will have been serviced.)
3277 ProcessInterrupts(void)
3279 /* OK to accept any interrupts now? */
3280 if (InterruptHoldoffCount
!= 0 || CritSectionCount
!= 0)
3282 InterruptPending
= false;
3286 ProcDiePending
= false;
3287 QueryCancelPending
= false; /* ProcDie trumps QueryCancel */
3289 /* As in quickdie, don't risk sending to client during auth */
3290 if (ClientAuthInProgress
&& whereToSendOutput
== DestRemote
)
3291 whereToSendOutput
= DestNone
;
3292 if (ClientAuthInProgress
)
3294 (errcode(ERRCODE_QUERY_CANCELED
),
3295 errmsg("canceling authentication due to timeout")));
3296 else if (AmAutoVacuumWorkerProcess())
3298 (errcode(ERRCODE_ADMIN_SHUTDOWN
),
3299 errmsg("terminating autovacuum process due to administrator command")));
3300 else if (IsLogicalWorker())
3302 (errcode(ERRCODE_ADMIN_SHUTDOWN
),
3303 errmsg("terminating logical replication worker due to administrator command")));
3304 else if (IsLogicalLauncher())
3307 (errmsg_internal("logical replication launcher shutting down")));
3310 * The logical replication launcher can be stopped at any time.
3311 * Use exit status 1 so the background worker is restarted.
3315 else if (AmBackgroundWorkerProcess())
3317 (errcode(ERRCODE_ADMIN_SHUTDOWN
),
3318 errmsg("terminating background worker \"%s\" due to administrator command",
3319 MyBgworkerEntry
->bgw_type
)));
3322 (errcode(ERRCODE_ADMIN_SHUTDOWN
),
3323 errmsg("terminating connection due to administrator command")));
3326 if (CheckClientConnectionPending
)
3328 CheckClientConnectionPending
= false;
3331 * Check for lost connection and re-arm, if still configured, but not
3332 * if we've arrived back at DoingCommandRead state. We don't want to
3333 * wake up idle sessions, and they already know how to detect lost
3336 if (!DoingCommandRead
&& client_connection_check_interval
> 0)
3338 if (!pq_check_connection())
3339 ClientConnectionLost
= true;
3341 enable_timeout_after(CLIENT_CONNECTION_CHECK_TIMEOUT
,
3342 client_connection_check_interval
);
3346 if (ClientConnectionLost
)
3348 QueryCancelPending
= false; /* lost connection trumps QueryCancel */
3350 /* don't send to client, we already know the connection to be dead. */
3351 whereToSendOutput
= DestNone
;
3353 (errcode(ERRCODE_CONNECTION_FAILURE
),
3354 errmsg("connection to client lost")));
3358 * Don't allow query cancel interrupts while reading input from the
3359 * client, because we might lose sync in the FE/BE protocol. (Die
3360 * interrupts are OK, because we won't read any further messages from the
3361 * client in that case.)
3363 * See similar logic in ProcessRecoveryConflictInterrupts().
3365 if (QueryCancelPending
&& QueryCancelHoldoffCount
!= 0)
3368 * Re-arm InterruptPending so that we process the cancel request as
3369 * soon as we're done reading the message. (XXX this is seriously
3370 * ugly: it complicates INTERRUPTS_CAN_BE_PROCESSED(), and it means we
3371 * can't use that macro directly as the initial test in this function,
3372 * meaning that this code also creates opportunities for other bugs to
3375 InterruptPending
= true;
3377 else if (QueryCancelPending
)
3379 bool lock_timeout_occurred
;
3380 bool stmt_timeout_occurred
;
3382 QueryCancelPending
= false;
3385 * If LOCK_TIMEOUT and STATEMENT_TIMEOUT indicators are both set, we
3386 * need to clear both, so always fetch both.
3388 lock_timeout_occurred
= get_timeout_indicator(LOCK_TIMEOUT
, true);
3389 stmt_timeout_occurred
= get_timeout_indicator(STATEMENT_TIMEOUT
, true);
3392 * If both were set, we want to report whichever timeout completed
3393 * earlier; this ensures consistent behavior if the machine is slow
3394 * enough that the second timeout triggers before we get here. A tie
3395 * is arbitrarily broken in favor of reporting a lock timeout.
3397 if (lock_timeout_occurred
&& stmt_timeout_occurred
&&
3398 get_timeout_finish_time(STATEMENT_TIMEOUT
) < get_timeout_finish_time(LOCK_TIMEOUT
))
3399 lock_timeout_occurred
= false; /* report stmt timeout */
3401 if (lock_timeout_occurred
)
3405 (errcode(ERRCODE_LOCK_NOT_AVAILABLE
),
3406 errmsg("canceling statement due to lock timeout")));
3408 if (stmt_timeout_occurred
)
3412 (errcode(ERRCODE_QUERY_CANCELED
),
3413 errmsg("canceling statement due to statement timeout")));
3415 if (AmAutoVacuumWorkerProcess())
3419 (errcode(ERRCODE_QUERY_CANCELED
),
3420 errmsg("canceling autovacuum task")));
3424 * If we are reading a command from the client, just ignore the cancel
3425 * request --- sending an extra error message won't accomplish
3426 * anything. Otherwise, go ahead and throw the error.
3428 if (!DoingCommandRead
)
3432 (errcode(ERRCODE_QUERY_CANCELED
),
3433 errmsg("canceling statement due to user request")));
3437 if (RecoveryConflictPending
)
3438 ProcessRecoveryConflictInterrupts();
3440 if (IdleInTransactionSessionTimeoutPending
)
3443 * If the GUC has been reset to zero, ignore the signal. This is
3444 * important because the GUC update itself won't disable any pending
3445 * interrupt. We need to unset the flag before the injection point,
3446 * otherwise we could loop in interrupts checking.
3448 IdleInTransactionSessionTimeoutPending
= false;
3449 if (IdleInTransactionSessionTimeout
> 0)
3451 INJECTION_POINT("idle-in-transaction-session-timeout");
3453 (errcode(ERRCODE_IDLE_IN_TRANSACTION_SESSION_TIMEOUT
),
3454 errmsg("terminating connection due to idle-in-transaction timeout")));
3458 if (TransactionTimeoutPending
)
3460 /* As above, ignore the signal if the GUC has been reset to zero. */
3461 TransactionTimeoutPending
= false;
3462 if (TransactionTimeout
> 0)
3464 INJECTION_POINT("transaction-timeout");
3466 (errcode(ERRCODE_TRANSACTION_TIMEOUT
),
3467 errmsg("terminating connection due to transaction timeout")));
3471 if (IdleSessionTimeoutPending
)
3473 /* As above, ignore the signal if the GUC has been reset to zero. */
3474 IdleSessionTimeoutPending
= false;
3475 if (IdleSessionTimeout
> 0)
3477 INJECTION_POINT("idle-session-timeout");
3479 (errcode(ERRCODE_IDLE_SESSION_TIMEOUT
),
3480 errmsg("terminating connection due to idle-session timeout")));
3485 * If there are pending stats updates and we currently are truly idle
3486 * (matching the conditions in PostgresMain(), report stats now.
3488 if (IdleStatsUpdateTimeoutPending
&&
3489 DoingCommandRead
&& !IsTransactionOrTransactionBlock())
3491 IdleStatsUpdateTimeoutPending
= false;
3492 pgstat_report_stat(true);
3495 if (ProcSignalBarrierPending
)
3496 ProcessProcSignalBarrier();
3498 if (ParallelMessagePending
)
3499 HandleParallelMessages();
3501 if (LogMemoryContextPending
)
3502 ProcessLogMemoryContextInterrupt();
3504 if (ParallelApplyMessagePending
)
3505 HandleParallelApplyMessages();
3509 * set_stack_base: set up reference point for stack depth checking
3511 * Returns the old reference point, if any.
3514 set_stack_base(void)
3516 #ifndef HAVE__BUILTIN_FRAME_ADDRESS
3519 pg_stack_base_t old
;
3521 old
= stack_base_ptr
;
3524 * Set up reference point for stack depth checking. On recent gcc we use
3525 * __builtin_frame_address() to avoid a warning about storing a local
3526 * variable's address in a long-lived variable.
3528 #ifdef HAVE__BUILTIN_FRAME_ADDRESS
3529 stack_base_ptr
= __builtin_frame_address(0);
3531 stack_base_ptr
= &stack_base
;
3538 * restore_stack_base: restore reference point for stack depth checking
3540 * This can be used after set_stack_base() to restore the old value. This
3541 * is currently only used in PL/Java. When PL/Java calls a backend function
3542 * from different thread, the thread's stack is at a different location than
3543 * the main thread's stack, so it sets the base pointer before the call, and
3544 * restores it afterwards.
3547 restore_stack_base(pg_stack_base_t base
)
3549 stack_base_ptr
= base
;
3553 * check_stack_depth/stack_is_too_deep: check for excessively deep recursion
3555 * This should be called someplace in any recursive routine that might possibly
3556 * recurse deep enough to overflow the stack. Most Unixen treat stack
3557 * overflow as an unrecoverable SIGSEGV, so we want to error out ourselves
3558 * before hitting the hardware limit.
3560 * check_stack_depth() just throws an error summarily. stack_is_too_deep()
3561 * can be used by code that wants to handle the error condition itself.
3564 check_stack_depth(void)
3566 if (stack_is_too_deep())
3569 (errcode(ERRCODE_STATEMENT_TOO_COMPLEX
),
3570 errmsg("stack depth limit exceeded"),
3571 errhint("Increase the configuration parameter \"max_stack_depth\" (currently %dkB), "
3572 "after ensuring the platform's stack depth limit is adequate.",
3578 stack_is_too_deep(void)
3584 * Compute distance from reference point to my local variables
3586 stack_depth
= (long) (stack_base_ptr
- &stack_top_loc
);
3589 * Take abs value, since stacks grow up on some machines, down on others
3591 if (stack_depth
< 0)
3592 stack_depth
= -stack_depth
;
3597 * The test on stack_base_ptr prevents us from erroring out if called
3598 * during process setup or in a non-backend process. Logically it should
3599 * be done first, but putting it here avoids wasting cycles during normal
3602 if (stack_depth
> max_stack_depth_bytes
&&
3603 stack_base_ptr
!= NULL
)
3609 /* GUC check hook for max_stack_depth */
3611 check_max_stack_depth(int *newval
, void **extra
, GucSource source
)
3613 long newval_bytes
= *newval
* 1024L;
3614 long stack_rlimit
= get_stack_depth_rlimit();
3616 if (stack_rlimit
> 0 && newval_bytes
> stack_rlimit
- STACK_DEPTH_SLOP
)
3618 GUC_check_errdetail("\"max_stack_depth\" must not exceed %ldkB.",
3619 (stack_rlimit
- STACK_DEPTH_SLOP
) / 1024L);
3620 GUC_check_errhint("Increase the platform's stack depth limit via \"ulimit -s\" or local equivalent.");
3626 /* GUC assign hook for max_stack_depth */
3628 assign_max_stack_depth(int newval
, void *extra
)
3630 long newval_bytes
= newval
* 1024L;
3632 max_stack_depth_bytes
= newval_bytes
;
3636 * GUC check_hook for client_connection_check_interval
3639 check_client_connection_check_interval(int *newval
, void **extra
, GucSource source
)
3641 if (!WaitEventSetCanReportClosed() && *newval
!= 0)
3643 GUC_check_errdetail("\"client_connection_check_interval\" must be set to 0 on this platform.");
3650 * GUC check_hook for log_parser_stats, log_planner_stats, log_executor_stats
3652 * This function and check_log_stats interact to prevent their variables from
3653 * being set in a disallowed combination. This is a hack that doesn't really
3654 * work right; for example it might fail while applying pg_db_role_setting
3655 * values even though the final state would have been acceptable. However,
3656 * since these variables are legacy settings with little production usage,
3660 check_stage_log_stats(bool *newval
, void **extra
, GucSource source
)
3662 if (*newval
&& log_statement_stats
)
3664 GUC_check_errdetail("Cannot enable parameter when \"log_statement_stats\" is true.");
3671 * GUC check_hook for log_statement_stats
3674 check_log_stats(bool *newval
, void **extra
, GucSource source
)
3677 (log_parser_stats
|| log_planner_stats
|| log_executor_stats
))
3679 GUC_check_errdetail("Cannot enable \"log_statement_stats\" when "
3680 "\"log_parser_stats\", \"log_planner_stats\", "
3681 "or \"log_executor_stats\" is true.");
3687 /* GUC assign hook for transaction_timeout */
3689 assign_transaction_timeout(int newval
, void *extra
)
3691 if (IsTransactionState())
3694 * If transaction_timeout GUC has changed within the transaction block
3695 * enable or disable the timer correspondingly.
3697 if (newval
> 0 && !get_timeout_active(TRANSACTION_TIMEOUT
))
3698 enable_timeout_after(TRANSACTION_TIMEOUT
, newval
);
3699 else if (newval
<= 0 && get_timeout_active(TRANSACTION_TIMEOUT
))
3700 disable_timeout(TRANSACTION_TIMEOUT
, false);
3705 * GUC check_hook for restrict_nonsystem_relation_kind
3708 check_restrict_nonsystem_relation_kind(char **newval
, void **extra
, GucSource source
)
3715 /* Need a modifiable copy of string */
3716 rawstring
= pstrdup(*newval
);
3718 if (!SplitIdentifierString(rawstring
, ',', &elemlist
))
3720 /* syntax error in list */
3721 GUC_check_errdetail("List syntax is invalid.");
3723 list_free(elemlist
);
3727 foreach(l
, elemlist
)
3729 char *tok
= (char *) lfirst(l
);
3731 if (pg_strcasecmp(tok
, "view") == 0)
3732 flags
|= RESTRICT_RELKIND_VIEW
;
3733 else if (pg_strcasecmp(tok
, "foreign-table") == 0)
3734 flags
|= RESTRICT_RELKIND_FOREIGN_TABLE
;
3737 GUC_check_errdetail("Unrecognized key word: \"%s\".", tok
);
3739 list_free(elemlist
);
3745 list_free(elemlist
);
3747 /* Save the flags in *extra, for use by the assign function */
3748 *extra
= guc_malloc(ERROR
, sizeof(int));
3749 *((int *) *extra
) = flags
;
3755 * GUC assign_hook for restrict_nonsystem_relation_kind
3758 assign_restrict_nonsystem_relation_kind(const char *newval
, void *extra
)
3760 int *flags
= (int *) extra
;
3762 restrict_nonsystem_relation_kind
= *flags
;
3766 * set_debug_options --- apply "-d N" command line option
3768 * -d is not quite the same as setting log_min_messages because it enables
3769 * other output options.
3772 set_debug_options(int debug_flag
, GucContext context
, GucSource source
)
3778 sprintf(debugstr
, "debug%d", debug_flag
);
3779 SetConfigOption("log_min_messages", debugstr
, context
, source
);
3782 SetConfigOption("log_min_messages", "notice", context
, source
);
3784 if (debug_flag
>= 1 && context
== PGC_POSTMASTER
)
3786 SetConfigOption("log_connections", "true", context
, source
);
3787 SetConfigOption("log_disconnections", "true", context
, source
);
3789 if (debug_flag
>= 2)
3790 SetConfigOption("log_statement", "all", context
, source
);
3791 if (debug_flag
>= 3)
3792 SetConfigOption("debug_print_parse", "true", context
, source
);
3793 if (debug_flag
>= 4)
3794 SetConfigOption("debug_print_plan", "true", context
, source
);
3795 if (debug_flag
>= 5)
3796 SetConfigOption("debug_print_rewritten", "true", context
, source
);
3801 set_plan_disabling_options(const char *arg
, GucContext context
, GucSource source
)
3803 const char *tmp
= NULL
;
3807 case 's': /* seqscan */
3808 tmp
= "enable_seqscan";
3810 case 'i': /* indexscan */
3811 tmp
= "enable_indexscan";
3813 case 'o': /* indexonlyscan */
3814 tmp
= "enable_indexonlyscan";
3816 case 'b': /* bitmapscan */
3817 tmp
= "enable_bitmapscan";
3819 case 't': /* tidscan */
3820 tmp
= "enable_tidscan";
3822 case 'n': /* nestloop */
3823 tmp
= "enable_nestloop";
3825 case 'm': /* mergejoin */
3826 tmp
= "enable_mergejoin";
3828 case 'h': /* hashjoin */
3829 tmp
= "enable_hashjoin";
3834 SetConfigOption(tmp
, "false", context
, source
);
3843 get_stats_option_name(const char *arg
)
3848 if (optarg
[1] == 'a') /* "parser" */
3849 return "log_parser_stats";
3850 else if (optarg
[1] == 'l') /* "planner" */
3851 return "log_planner_stats";
3854 case 'e': /* "executor" */
3855 return "log_executor_stats";
3863 /* ----------------------------------------------------------------
3864 * process_postgres_switches
3865 * Parse command line arguments for backends
3867 * This is called twice, once for the "secure" options coming from the
3868 * postmaster or command line, and once for the "insecure" options coming
3869 * from the client's startup packet. The latter have the same syntax but
3870 * may be restricted in what they can do.
3872 * argv[0] is ignored in either case (it's assumed to be the program name).
3874 * ctx is PGC_POSTMASTER for secure options, PGC_BACKEND for insecure options
3875 * coming from the client, or PGC_SU_BACKEND for insecure options coming from
3876 * a superuser client.
3878 * If a database name is present in the command line arguments, it's
3879 * returned into *dbname (this is allowed only if *dbname is initially NULL).
3880 * ----------------------------------------------------------------
3883 process_postgres_switches(int argc
, char *argv
[], GucContext ctx
,
3884 const char **dbname
)
3886 bool secure
= (ctx
== PGC_POSTMASTER
);
3888 GucSource gucsource
;
3893 gucsource
= PGC_S_ARGV
; /* switches came from command line */
3895 /* Ignore the initial --single argument, if present */
3896 if (argc
> 1 && strcmp(argv
[1], "--single") == 0)
3904 gucsource
= PGC_S_CLIENT
; /* switches came from client */
3907 #ifdef HAVE_INT_OPTERR
3910 * Turn this off because it's either printed to stderr and not the log
3911 * where we'd want it, or argv[0] is now "--single", which would make for
3912 * a weird error message. We print our own error message below.
3918 * Parse command-line options. CAUTION: keep this in sync with
3919 * postmaster/postmaster.c (the option sets should not conflict) and with
3920 * the common help() function in main/main.c.
3922 while ((flag
= getopt(argc
, argv
, "B:bC:c:D:d:EeFf:h:ijk:lN:nOPp:r:S:sTt:v:W:-:")) != -1)
3927 SetConfigOption("shared_buffers", optarg
, ctx
, gucsource
);
3931 /* Undocumented flag used for binary upgrades */
3933 IsBinaryUpgrade
= true;
3937 /* ignored for consistency with the postmaster */
3946 ParseLongOption(optarg
, &name
, &value
);
3951 (errcode(ERRCODE_SYNTAX_ERROR
),
3952 errmsg("--%s requires a value",
3956 (errcode(ERRCODE_SYNTAX_ERROR
),
3957 errmsg("-c %s requires a value",
3960 SetConfigOption(name
, value
, ctx
, gucsource
);
3968 userDoption
= strdup(optarg
);
3972 set_debug_options(atoi(optarg
), ctx
, gucsource
);
3981 SetConfigOption("datestyle", "euro", ctx
, gucsource
);
3985 SetConfigOption("fsync", "false", ctx
, gucsource
);
3989 if (!set_plan_disabling_options(optarg
, ctx
, gucsource
))
3994 SetConfigOption("listen_addresses", optarg
, ctx
, gucsource
);
3998 SetConfigOption("listen_addresses", "*", ctx
, gucsource
);
4003 UseSemiNewlineNewline
= true;
4007 SetConfigOption("unix_socket_directories", optarg
, ctx
, gucsource
);
4011 SetConfigOption("ssl", "true", ctx
, gucsource
);
4015 SetConfigOption("max_connections", optarg
, ctx
, gucsource
);
4019 /* ignored for consistency with postmaster */
4023 SetConfigOption("allow_system_table_mods", "true", ctx
, gucsource
);
4027 SetConfigOption("ignore_system_indexes", "true", ctx
, gucsource
);
4031 SetConfigOption("port", optarg
, ctx
, gucsource
);
4035 /* send output (stdout and stderr) to the given file */
4037 strlcpy(OutputFileName
, optarg
, MAXPGPATH
);
4041 SetConfigOption("work_mem", optarg
, ctx
, gucsource
);
4045 SetConfigOption("log_statement_stats", "true", ctx
, gucsource
);
4049 /* ignored for consistency with the postmaster */
4054 const char *tmp
= get_stats_option_name(optarg
);
4057 SetConfigOption(tmp
, "true", ctx
, gucsource
);
4066 * -v is no longer used in normal operation, since
4067 * FrontendProtocol is already set before we get here. We keep
4068 * the switch only for possible use in standalone operation,
4069 * in case we ever support using normal FE/BE protocol with a
4070 * standalone backend.
4073 FrontendProtocol
= (ProtocolVersion
) atoi(optarg
);
4077 SetConfigOption("post_auth_delay", optarg
, ctx
, gucsource
);
4090 * Optional database name should be there only if *dbname is NULL.
4092 if (!errs
&& dbname
&& *dbname
== NULL
&& argc
- optind
>= 1)
4093 *dbname
= strdup(argv
[optind
++]);
4095 if (errs
|| argc
!= optind
)
4098 optind
--; /* complain about the previous argument */
4100 /* spell the error message a bit differently depending on context */
4101 if (IsUnderPostmaster
)
4103 errcode(ERRCODE_SYNTAX_ERROR
),
4104 errmsg("invalid command-line argument for server process: %s", argv
[optind
]),
4105 errhint("Try \"%s --help\" for more information.", progname
));
4108 errcode(ERRCODE_SYNTAX_ERROR
),
4109 errmsg("%s: invalid command-line argument: %s",
4110 progname
, argv
[optind
]),
4111 errhint("Try \"%s --help\" for more information.", progname
));
4115 * Reset getopt(3) library so that it will work correctly in subprocesses
4116 * or when this function is called a second time with another array.
4119 #ifdef HAVE_INT_OPTRESET
4120 optreset
= 1; /* some systems need this too */
4126 * PostgresSingleUserMain
4127 * Entry point for single user mode. argc/argv are the command line
4128 * arguments to be used.
4130 * Performs single user specific setup then calls PostgresMain() to actually
4131 * process queries. Single user mode specific setup should go here, rather
4132 * than PostgresMain() or InitPostgres() when reasonably possible.
4135 PostgresSingleUserMain(int argc
, char *argv
[],
4136 const char *username
)
4138 const char *dbname
= NULL
;
4140 Assert(!IsUnderPostmaster
);
4142 /* Initialize startup process environment. */
4143 InitStandaloneProcess(argv
[0]);
4146 * Set default values for command-line options.
4148 InitializeGUCOptions();
4151 * Parse command-line options.
4153 process_postgres_switches(argc
, argv
, PGC_POSTMASTER
, &dbname
);
4155 /* Must have gotten a database name, or have a default (the username) */
4161 (errcode(ERRCODE_INVALID_PARAMETER_VALUE
),
4162 errmsg("%s: no database nor user name specified",
4166 /* Acquire configuration parameters */
4167 if (!SelectConfigFiles(userDoption
, progname
))
4171 * Validate we have been given a reasonable-looking DataDir and change
4178 * Create lockfile for data directory.
4180 CreateDataDirLockFile(false);
4182 /* read control file (error checking and contains config ) */
4183 LocalProcessControlFile(false);
4186 * process any libraries that should be preloaded at postmaster start
4188 process_shared_preload_libraries();
4190 /* Initialize MaxBackends */
4191 InitializeMaxBackends();
4193 /* Initialize size of fast-path lock cache. */
4194 InitializeFastPathLocks();
4197 * Give preloaded libraries a chance to request additional shared memory.
4199 process_shmem_requests();
4202 * Now that loadable modules have had their chance to request additional
4203 * shared memory, determine the value of any runtime-computed GUCs that
4204 * depend on the amount of shared memory required.
4206 InitializeShmemGUCs();
4209 * Now that modules have been loaded, we can process any custom resource
4210 * managers specified in the wal_consistency_checking GUC.
4212 InitializeWalConsistencyChecking();
4214 CreateSharedMemoryAndSemaphores();
4217 * Remember stand-alone backend startup time,roughly at the same point
4218 * during startup that postmaster does so.
4220 PgStartTime
= GetCurrentTimestamp();
4223 * Create a per-backend PGPROC struct in shared memory. We must do this
4224 * before we can use LWLocks.
4229 * Now that sufficient infrastructure has been initialized, PostgresMain()
4232 PostgresMain(dbname
, username
);
4236 /* ----------------------------------------------------------------
4238 * postgres main loop -- all backends, interactive or otherwise loop here
4240 * dbname is the name of the database to connect to, username is the
4241 * PostgreSQL user name to be used for the session.
4243 * NB: Single user mode specific setup should go to PostgresSingleUserMain()
4244 * if reasonably possible.
4245 * ----------------------------------------------------------------
4248 PostgresMain(const char *dbname
, const char *username
)
4250 sigjmp_buf local_sigjmp_buf
;
4252 /* these must be volatile to ensure state is preserved across longjmp: */
4253 volatile bool send_ready_for_query
= true;
4254 volatile bool idle_in_transaction_timeout_enabled
= false;
4255 volatile bool idle_session_timeout_enabled
= false;
4257 Assert(dbname
!= NULL
);
4258 Assert(username
!= NULL
);
4260 Assert(GetProcessingMode() == InitProcessing
);
4263 * Set up signal handlers. (InitPostmasterChild or InitStandaloneProcess
4264 * has already set up BlockSig and made that the active signal mask.)
4266 * Note that postmaster blocked all signals before forking child process,
4267 * so there is no race condition whereby we might receive a signal before
4268 * we have set up the handler.
4270 * Also note: it's best not to use any signals that are SIG_IGNored in the
4271 * postmaster. If such a signal arrives before we are able to change the
4272 * handler to non-SIG_IGN, it'll get dropped. Instead, make a dummy
4273 * handler in the postmaster to reserve the signal. (Of course, this isn't
4274 * an issue for signals that are locally generated, such as SIGALRM and
4281 pqsignal(SIGHUP
, SignalHandlerForConfigReload
);
4282 pqsignal(SIGINT
, StatementCancelHandler
); /* cancel current query */
4283 pqsignal(SIGTERM
, die
); /* cancel current query and exit */
4286 * In a postmaster child backend, replace SignalHandlerForCrashExit
4287 * with quickdie, so we can tell the client we're dying.
4289 * In a standalone backend, SIGQUIT can be generated from the keyboard
4290 * easily, while SIGTERM cannot, so we make both signals do die()
4291 * rather than quickdie().
4293 if (IsUnderPostmaster
)
4294 pqsignal(SIGQUIT
, quickdie
); /* hard crash time */
4296 pqsignal(SIGQUIT
, die
); /* cancel current query and exit */
4297 InitializeTimeouts(); /* establishes SIGALRM handler */
4300 * Ignore failure to write to frontend. Note: if frontend closes
4301 * connection, we will notice it and exit cleanly when control next
4302 * returns to outer loop. This seems safer than forcing exit in the
4303 * midst of output during who-knows-what operation...
4305 pqsignal(SIGPIPE
, SIG_IGN
);
4306 pqsignal(SIGUSR1
, procsignal_sigusr1_handler
);
4307 pqsignal(SIGUSR2
, SIG_IGN
);
4308 pqsignal(SIGFPE
, FloatExceptionHandler
);
4311 * Reset some signals that are accepted by postmaster but not by
4314 pqsignal(SIGCHLD
, SIG_DFL
); /* system() requires this on some
4318 /* Early initialization */
4321 /* We need to allow SIGINT, etc during the initial transaction */
4322 sigprocmask(SIG_SETMASK
, &UnBlockSig
, NULL
);
4325 * Generate a random cancel key, if this is a backend serving a
4326 * connection. InitPostgres() will advertise it in shared memory.
4328 Assert(!MyCancelKeyValid
);
4329 if (whereToSendOutput
== DestRemote
)
4331 if (!pg_strong_random(&MyCancelKey
, sizeof(int32
)))
4334 (errcode(ERRCODE_INTERNAL_ERROR
),
4335 errmsg("could not generate random cancel key")));
4337 MyCancelKeyValid
= true;
4341 * General initialization.
4343 * NOTE: if you are tempted to add code in this vicinity, consider putting
4344 * it inside InitPostgres() instead. In particular, anything that
4345 * involves database access should be there, not here.
4347 * Honor session_preload_libraries if not dealing with a WAL sender.
4349 InitPostgres(dbname
, InvalidOid
, /* database to connect to */
4350 username
, InvalidOid
, /* role to connect as */
4351 (!am_walsender
) ? INIT_PG_LOAD_SESSION_LIBS
: 0,
4352 NULL
); /* no out_dbname */
4355 * If the PostmasterContext is still around, recycle the space; we don't
4356 * need it anymore after InitPostgres completes.
4358 if (PostmasterContext
)
4360 MemoryContextDelete(PostmasterContext
);
4361 PostmasterContext
= NULL
;
4364 SetProcessingMode(NormalProcessing
);
4367 * Now all GUC states are fully set up. Report them to client if
4370 BeginReportingGUCOptions();
4373 * Also set up handler to log session end; we have to wait till now to be
4374 * sure Log_disconnections has its final value.
4376 if (IsUnderPostmaster
&& Log_disconnections
)
4377 on_proc_exit(log_disconnections
, 0);
4379 pgstat_report_connect(MyDatabaseId
);
4381 /* Perform initialization specific to a WAL sender process. */
4386 * Send this backend's cancellation info to the frontend.
4388 if (whereToSendOutput
== DestRemote
)
4392 Assert(MyCancelKeyValid
);
4393 pq_beginmessage(&buf
, PqMsg_BackendKeyData
);
4394 pq_sendint32(&buf
, (int32
) MyProcPid
);
4395 pq_sendint32(&buf
, (int32
) MyCancelKey
);
4396 pq_endmessage(&buf
);
4397 /* Need not flush since ReadyForQuery will do it. */
4400 /* Welcome banner for standalone case */
4401 if (whereToSendOutput
== DestDebug
)
4402 printf("\nPostgreSQL stand-alone backend %s\n", PG_VERSION
);
4405 * Create the memory context we will use in the main loop.
4407 * MessageContext is reset once per iteration of the main loop, ie, upon
4408 * completion of processing of each command message from the client.
4410 MessageContext
= AllocSetContextCreate(TopMemoryContext
,
4412 ALLOCSET_DEFAULT_SIZES
);
4415 * Create memory context and buffer used for RowDescription messages. As
4416 * SendRowDescriptionMessage(), via exec_describe_statement_message(), is
4417 * frequently executed for ever single statement, we don't want to
4418 * allocate a separate buffer every time.
4420 row_description_context
= AllocSetContextCreate(TopMemoryContext
,
4421 "RowDescriptionContext",
4422 ALLOCSET_DEFAULT_SIZES
);
4423 MemoryContextSwitchTo(row_description_context
);
4424 initStringInfo(&row_description_buf
);
4425 MemoryContextSwitchTo(TopMemoryContext
);
4427 /* Fire any defined login event triggers, if appropriate */
4428 EventTriggerOnLogin();
4431 * POSTGRES main processing loop begins here
4433 * If an exception is encountered, processing resumes here so we abort the
4434 * current transaction and start a new one.
4436 * You might wonder why this isn't coded as an infinite loop around a
4437 * PG_TRY construct. The reason is that this is the bottom of the
4438 * exception stack, and so with PG_TRY there would be no exception handler
4439 * in force at all during the CATCH part. By leaving the outermost setjmp
4440 * always active, we have at least some chance of recovering from an error
4441 * during error recovery. (If we get into an infinite loop thereby, it
4442 * will soon be stopped by overflow of elog.c's internal state stack.)
4444 * Note that we use sigsetjmp(..., 1), so that this function's signal mask
4445 * (to wit, UnBlockSig) will be restored when longjmp'ing to here. This
4446 * is essential in case we longjmp'd out of a signal handler on a platform
4447 * where that leaves the signal blocked. It's not redundant with the
4448 * unblock in AbortTransaction() because the latter is only called if we
4449 * were inside a transaction.
4452 if (sigsetjmp(local_sigjmp_buf
, 1) != 0)
4455 * NOTE: if you are tempted to add more code in this if-block,
4456 * consider the high probability that it should be in
4457 * AbortTransaction() instead. The only stuff done directly here
4458 * should be stuff that is guaranteed to apply *only* for outer-level
4459 * error recovery, such as adjusting the FE/BE protocol status.
4462 /* Since not using PG_TRY, must reset error stack by hand */
4463 error_context_stack
= NULL
;
4465 /* Prevent interrupts while cleaning up */
4469 * Forget any pending QueryCancel request, since we're returning to
4470 * the idle loop anyway, and cancel any active timeout requests. (In
4471 * future we might want to allow some timeout requests to survive, but
4472 * at minimum it'd be necessary to do reschedule_timeouts(), in case
4473 * we got here because of a query cancel interrupting the SIGALRM
4474 * interrupt handler.) Note in particular that we must clear the
4475 * statement and lock timeout indicators, to prevent any future plain
4476 * query cancels from being misreported as timeouts in case we're
4477 * forgetting a timeout cancel.
4479 disable_all_timeouts(false); /* do first to avoid race condition */
4480 QueryCancelPending
= false;
4481 idle_in_transaction_timeout_enabled
= false;
4482 idle_session_timeout_enabled
= false;
4484 /* Not reading from the client anymore. */
4485 DoingCommandRead
= false;
4487 /* Make sure libpq is in a good state */
4490 /* Report the error to the client and/or server log */
4494 * If Valgrind noticed something during the erroneous query, print the
4495 * query string, assuming we have one.
4497 valgrind_report_error_query(debug_query_string
);
4500 * Make sure debug_query_string gets reset before we possibly clobber
4501 * the storage it points at.
4503 debug_query_string
= NULL
;
4506 * Abort the current transaction in order to recover.
4508 AbortCurrentTransaction();
4511 WalSndErrorCleanup();
4513 PortalErrorCleanup();
4516 * We can't release replication slots inside AbortTransaction() as we
4517 * need to be able to start and abort transactions while having a slot
4518 * acquired. But we never need to hold them across top level errors,
4519 * so releasing here is fine. There also is a before_shmem_exit()
4520 * callback ensuring correct cleanup on FATAL errors.
4522 if (MyReplicationSlot
!= NULL
)
4523 ReplicationSlotRelease();
4525 /* We also want to cleanup temporary slots on error. */
4526 ReplicationSlotCleanup(false);
4528 jit_reset_after_error();
4531 * Now return to normal top-level context and clear ErrorContext for
4534 MemoryContextSwitchTo(MessageContext
);
4538 * If we were handling an extended-query-protocol message, initiate
4539 * skip till next Sync. This also causes us not to issue
4540 * ReadyForQuery (until we get Sync).
4542 if (doing_extended_query_message
)
4543 ignore_till_sync
= true;
4545 /* We don't have a transaction command open anymore */
4546 xact_started
= false;
4549 * If an error occurred while we were reading a message from the
4550 * client, we have potentially lost track of where the previous
4551 * message ends and the next one begins. Even though we have
4552 * otherwise recovered from the error, we cannot safely read any more
4553 * messages from the client, so there isn't much we can do with the
4554 * connection anymore.
4556 if (pq_is_reading_msg())
4558 (errcode(ERRCODE_PROTOCOL_VIOLATION
),
4559 errmsg("terminating connection because protocol synchronization was lost")));
4561 /* Now we can allow interrupts again */
4562 RESUME_INTERRUPTS();
4565 /* We can now handle ereport(ERROR) */
4566 PG_exception_stack
= &local_sigjmp_buf
;
4568 if (!ignore_till_sync
)
4569 send_ready_for_query
= true; /* initially, or after error */
4572 * Non-error queries loop here.
4578 StringInfoData input_message
;
4581 * At top of loop, reset extended-query-message flag, so that any
4582 * errors encountered in "idle" state don't provoke skip.
4584 doing_extended_query_message
= false;
4587 * For valgrind reporting purposes, the "current query" begins here.
4590 old_valgrind_error_count
= VALGRIND_COUNT_ERRORS
;
4594 * Release storage left over from prior query cycle, and create a new
4595 * query input buffer in the cleared MessageContext.
4597 MemoryContextSwitchTo(MessageContext
);
4598 MemoryContextReset(MessageContext
);
4600 initStringInfo(&input_message
);
4603 * Also consider releasing our catalog snapshot if any, so that it's
4604 * not preventing advance of global xmin while we wait for the client.
4606 InvalidateCatalogSnapshotConditionally();
4609 * (1) If we've reached idle state, tell the frontend we're ready for
4612 * Note: this includes fflush()'ing the last of the prior output.
4614 * This is also a good time to flush out collected statistics to the
4615 * cumulative stats system, and to update the PS stats display. We
4616 * avoid doing those every time through the message loop because it'd
4617 * slow down processing of batched messages, and because we don't want
4618 * to report uncommitted updates (that confuses autovacuum). The
4619 * notification processor wants a call too, if we are not in a
4620 * transaction block.
4622 * Also, if an idle timeout is enabled, start the timer for that.
4624 if (send_ready_for_query
)
4626 if (IsAbortedTransactionBlockState())
4628 set_ps_display("idle in transaction (aborted)");
4629 pgstat_report_activity(STATE_IDLEINTRANSACTION_ABORTED
, NULL
);
4631 /* Start the idle-in-transaction timer */
4632 if (IdleInTransactionSessionTimeout
> 0
4633 && (IdleInTransactionSessionTimeout
< TransactionTimeout
|| TransactionTimeout
== 0))
4635 idle_in_transaction_timeout_enabled
= true;
4636 enable_timeout_after(IDLE_IN_TRANSACTION_SESSION_TIMEOUT
,
4637 IdleInTransactionSessionTimeout
);
4640 else if (IsTransactionOrTransactionBlock())
4642 set_ps_display("idle in transaction");
4643 pgstat_report_activity(STATE_IDLEINTRANSACTION
, NULL
);
4645 /* Start the idle-in-transaction timer */
4646 if (IdleInTransactionSessionTimeout
> 0
4647 && (IdleInTransactionSessionTimeout
< TransactionTimeout
|| TransactionTimeout
== 0))
4649 idle_in_transaction_timeout_enabled
= true;
4650 enable_timeout_after(IDLE_IN_TRANSACTION_SESSION_TIMEOUT
,
4651 IdleInTransactionSessionTimeout
);
4659 * Process incoming notifies (including self-notifies), if
4660 * any, and send relevant messages to the client. Doing it
4661 * here helps ensure stable behavior in tests: if any notifies
4662 * were received during the just-finished transaction, they'll
4663 * be seen by the client before ReadyForQuery is.
4665 if (notifyInterruptPending
)
4666 ProcessNotifyInterrupt(false);
4669 * Check if we need to report stats. If pgstat_report_stat()
4670 * decides it's too soon to flush out pending stats / lock
4671 * contention prevented reporting, it'll tell us when we
4672 * should try to report stats again (so that stats updates
4673 * aren't unduly delayed if the connection goes idle for a
4674 * long time). We only enable the timeout if we don't already
4675 * have a timeout in progress, because we don't disable the
4676 * timeout below. enable_timeout_after() needs to determine
4677 * the current timestamp, which can have a negative
4678 * performance impact. That's OK because pgstat_report_stat()
4679 * won't have us wake up sooner than a prior call.
4681 stats_timeout
= pgstat_report_stat(false);
4682 if (stats_timeout
> 0)
4684 if (!get_timeout_active(IDLE_STATS_UPDATE_TIMEOUT
))
4685 enable_timeout_after(IDLE_STATS_UPDATE_TIMEOUT
,
4690 /* all stats flushed, no need for the timeout */
4691 if (get_timeout_active(IDLE_STATS_UPDATE_TIMEOUT
))
4692 disable_timeout(IDLE_STATS_UPDATE_TIMEOUT
, false);
4695 set_ps_display("idle");
4696 pgstat_report_activity(STATE_IDLE
, NULL
);
4698 /* Start the idle-session timer */
4699 if (IdleSessionTimeout
> 0)
4701 idle_session_timeout_enabled
= true;
4702 enable_timeout_after(IDLE_SESSION_TIMEOUT
,
4703 IdleSessionTimeout
);
4707 /* Report any recently-changed GUC options */
4708 ReportChangedGUCOptions();
4710 ReadyForQuery(whereToSendOutput
);
4711 send_ready_for_query
= false;
4715 * (2) Allow asynchronous signals to be executed immediately if they
4716 * come in while we are waiting for client input. (This must be
4717 * conditional since we don't want, say, reads on behalf of COPY FROM
4718 * STDIN doing the same thing.)
4720 DoingCommandRead
= true;
4723 * (3) read a command (loop blocks here)
4725 firstchar
= ReadCommand(&input_message
);
4728 * (4) turn off the idle-in-transaction and idle-session timeouts if
4729 * active. We do this before step (5) so that any last-moment timeout
4730 * is certain to be detected in step (5).
4732 * At most one of these timeouts will be active, so there's no need to
4733 * worry about combining the timeout.c calls into one.
4735 if (idle_in_transaction_timeout_enabled
)
4737 disable_timeout(IDLE_IN_TRANSACTION_SESSION_TIMEOUT
, false);
4738 idle_in_transaction_timeout_enabled
= false;
4740 if (idle_session_timeout_enabled
)
4742 disable_timeout(IDLE_SESSION_TIMEOUT
, false);
4743 idle_session_timeout_enabled
= false;
4747 * (5) disable async signal conditions again.
4749 * Query cancel is supposed to be a no-op when there is no query in
4750 * progress, so if a query cancel arrived while we were idle, just
4751 * reset QueryCancelPending. ProcessInterrupts() has that effect when
4752 * it's called when DoingCommandRead is set, so check for interrupts
4753 * before resetting DoingCommandRead.
4755 CHECK_FOR_INTERRUPTS();
4756 DoingCommandRead
= false;
4759 * (6) check for any other interesting events that happened while we
4762 if (ConfigReloadPending
)
4764 ConfigReloadPending
= false;
4765 ProcessConfigFile(PGC_SIGHUP
);
4769 * (7) process the command. But ignore it if we're skipping till
4772 if (ignore_till_sync
&& firstchar
!= EOF
)
4779 const char *query_string
;
4781 /* Set statement_timestamp() */
4782 SetCurrentStatementStartTimestamp();
4784 query_string
= pq_getmsgstring(&input_message
);
4785 pq_getmsgend(&input_message
);
4789 if (!exec_replication_command(query_string
))
4790 exec_simple_query(query_string
);
4793 exec_simple_query(query_string
);
4795 valgrind_report_error_query(query_string
);
4797 send_ready_for_query
= true;
4803 const char *stmt_name
;
4804 const char *query_string
;
4806 Oid
*paramTypes
= NULL
;
4808 forbidden_in_wal_sender(firstchar
);
4810 /* Set statement_timestamp() */
4811 SetCurrentStatementStartTimestamp();
4813 stmt_name
= pq_getmsgstring(&input_message
);
4814 query_string
= pq_getmsgstring(&input_message
);
4815 numParams
= pq_getmsgint(&input_message
, 2);
4818 paramTypes
= palloc_array(Oid
, numParams
);
4819 for (int i
= 0; i
< numParams
; i
++)
4820 paramTypes
[i
] = pq_getmsgint(&input_message
, 4);
4822 pq_getmsgend(&input_message
);
4824 exec_parse_message(query_string
, stmt_name
,
4825 paramTypes
, numParams
);
4827 valgrind_report_error_query(query_string
);
4832 forbidden_in_wal_sender(firstchar
);
4834 /* Set statement_timestamp() */
4835 SetCurrentStatementStartTimestamp();
4838 * this message is complex enough that it seems best to put
4839 * the field extraction out-of-line
4841 exec_bind_message(&input_message
);
4843 /* exec_bind_message does valgrind_report_error_query */
4848 const char *portal_name
;
4851 forbidden_in_wal_sender(firstchar
);
4853 /* Set statement_timestamp() */
4854 SetCurrentStatementStartTimestamp();
4856 portal_name
= pq_getmsgstring(&input_message
);
4857 max_rows
= pq_getmsgint(&input_message
, 4);
4858 pq_getmsgend(&input_message
);
4860 exec_execute_message(portal_name
, max_rows
);
4862 /* exec_execute_message does valgrind_report_error_query */
4866 case PqMsg_FunctionCall
:
4867 forbidden_in_wal_sender(firstchar
);
4869 /* Set statement_timestamp() */
4870 SetCurrentStatementStartTimestamp();
4872 /* Report query to various monitoring facilities. */
4873 pgstat_report_activity(STATE_FASTPATH
, NULL
);
4874 set_ps_display("<FASTPATH>");
4876 /* start an xact for this function invocation */
4877 start_xact_command();
4880 * Note: we may at this point be inside an aborted
4881 * transaction. We can't throw error for that until we've
4882 * finished reading the function-call message, so
4883 * HandleFunctionRequest() must check for it after doing so.
4884 * Be careful not to do anything that assumes we're inside a
4885 * valid transaction here.
4888 /* switch back to message context */
4889 MemoryContextSwitchTo(MessageContext
);
4891 HandleFunctionRequest(&input_message
);
4893 /* commit the function-invocation transaction */
4894 finish_xact_command();
4896 valgrind_report_error_query("fastpath function call");
4898 send_ready_for_query
= true;
4904 const char *close_target
;
4906 forbidden_in_wal_sender(firstchar
);
4908 close_type
= pq_getmsgbyte(&input_message
);
4909 close_target
= pq_getmsgstring(&input_message
);
4910 pq_getmsgend(&input_message
);
4915 if (close_target
[0] != '\0')
4916 DropPreparedStatement(close_target
, false);
4919 /* special-case the unnamed statement */
4920 drop_unnamed_stmt();
4927 portal
= GetPortalByName(close_target
);
4928 if (PortalIsValid(portal
))
4929 PortalDrop(portal
, false);
4934 (errcode(ERRCODE_PROTOCOL_VIOLATION
),
4935 errmsg("invalid CLOSE message subtype %d",
4940 if (whereToSendOutput
== DestRemote
)
4941 pq_putemptymessage(PqMsg_CloseComplete
);
4943 valgrind_report_error_query("CLOSE message");
4947 case PqMsg_Describe
:
4950 const char *describe_target
;
4952 forbidden_in_wal_sender(firstchar
);
4954 /* Set statement_timestamp() (needed for xact) */
4955 SetCurrentStatementStartTimestamp();
4957 describe_type
= pq_getmsgbyte(&input_message
);
4958 describe_target
= pq_getmsgstring(&input_message
);
4959 pq_getmsgend(&input_message
);
4961 switch (describe_type
)
4964 exec_describe_statement_message(describe_target
);
4967 exec_describe_portal_message(describe_target
);
4971 (errcode(ERRCODE_PROTOCOL_VIOLATION
),
4972 errmsg("invalid DESCRIBE message subtype %d",
4977 valgrind_report_error_query("DESCRIBE message");
4982 pq_getmsgend(&input_message
);
4983 if (whereToSendOutput
== DestRemote
)
4988 pq_getmsgend(&input_message
);
4989 finish_xact_command();
4990 valgrind_report_error_query("SYNC message");
4991 send_ready_for_query
= true;
4995 * 'X' means that the frontend is closing down the socket. EOF
4996 * means unexpected loss of frontend connection. Either way,
4997 * perform normal shutdown.
5001 /* for the cumulative statistics system */
5002 pgStatSessionEndCause
= DISCONNECT_CLIENT_EOF
;
5006 case PqMsg_Terminate
:
5009 * Reset whereToSendOutput to prevent ereport from attempting
5010 * to send any more messages to client.
5012 if (whereToSendOutput
== DestRemote
)
5013 whereToSendOutput
= DestNone
;
5016 * NOTE: if you are tempted to add more code here, DON'T!
5017 * Whatever you had in mind to do should be set up as an
5018 * on_proc_exit or on_shmem_exit callback, instead. Otherwise
5019 * it will fail to be called during other backend-shutdown
5024 case PqMsg_CopyData
:
5025 case PqMsg_CopyDone
:
5026 case PqMsg_CopyFail
:
5029 * Accept but ignore these messages, per protocol spec; we
5030 * probably got here because a COPY failed, and the frontend
5031 * is still sending data.
5037 (errcode(ERRCODE_PROTOCOL_VIOLATION
),
5038 errmsg("invalid frontend message type %d",
5041 } /* end of input-reading loop */
5045 * Throw an error if we're a WAL sender process.
5047 * This is used to forbid anything else than simple query protocol messages
5048 * in a WAL sender process. 'firstchar' specifies what kind of a forbidden
5049 * message was received, and is used to construct the error message.
5052 forbidden_in_wal_sender(char firstchar
)
5056 if (firstchar
== PqMsg_FunctionCall
)
5058 (errcode(ERRCODE_PROTOCOL_VIOLATION
),
5059 errmsg("fastpath function calls not supported in a replication connection")));
5062 (errcode(ERRCODE_PROTOCOL_VIOLATION
),
5063 errmsg("extended query protocol not supported in a replication connection")));
5069 * Obtain platform stack depth limit (in bytes)
5071 * Return -1 if unknown
5074 get_stack_depth_rlimit(void)
5076 #if defined(HAVE_GETRLIMIT)
5077 static long val
= 0;
5079 /* This won't change after process launch, so check just once */
5084 if (getrlimit(RLIMIT_STACK
, &rlim
) < 0)
5086 else if (rlim
.rlim_cur
== RLIM_INFINITY
)
5088 /* rlim_cur is probably of an unsigned type, so check for overflow */
5089 else if (rlim
.rlim_cur
>= LONG_MAX
)
5092 val
= rlim
.rlim_cur
;
5096 /* On Windows we set the backend stack size in src/backend/Makefile */
5097 return WIN32_STACK_RLIMIT
;
5102 static struct rusage Save_r
;
5103 static struct timeval Save_t
;
5108 getrusage(RUSAGE_SELF
, &Save_r
);
5109 gettimeofday(&Save_t
, NULL
);
5113 ShowUsage(const char *title
)
5116 struct timeval user
,
5118 struct timeval elapse_t
;
5121 getrusage(RUSAGE_SELF
, &r
);
5122 gettimeofday(&elapse_t
, NULL
);
5123 memcpy((char *) &user
, (char *) &r
.ru_utime
, sizeof(user
));
5124 memcpy((char *) &sys
, (char *) &r
.ru_stime
, sizeof(sys
));
5125 if (elapse_t
.tv_usec
< Save_t
.tv_usec
)
5128 elapse_t
.tv_usec
+= 1000000;
5130 if (r
.ru_utime
.tv_usec
< Save_r
.ru_utime
.tv_usec
)
5132 r
.ru_utime
.tv_sec
--;
5133 r
.ru_utime
.tv_usec
+= 1000000;
5135 if (r
.ru_stime
.tv_usec
< Save_r
.ru_stime
.tv_usec
)
5137 r
.ru_stime
.tv_sec
--;
5138 r
.ru_stime
.tv_usec
+= 1000000;
5142 * The only stats we don't show here are ixrss, idrss, isrss. It takes
5143 * some work to interpret them, and most platforms don't fill them in.
5145 initStringInfo(&str
);
5147 appendStringInfoString(&str
, "! system usage stats:\n");
5148 appendStringInfo(&str
,
5149 "!\t%ld.%06ld s user, %ld.%06ld s system, %ld.%06ld s elapsed\n",
5150 (long) (r
.ru_utime
.tv_sec
- Save_r
.ru_utime
.tv_sec
),
5151 (long) (r
.ru_utime
.tv_usec
- Save_r
.ru_utime
.tv_usec
),
5152 (long) (r
.ru_stime
.tv_sec
- Save_r
.ru_stime
.tv_sec
),
5153 (long) (r
.ru_stime
.tv_usec
- Save_r
.ru_stime
.tv_usec
),
5154 (long) (elapse_t
.tv_sec
- Save_t
.tv_sec
),
5155 (long) (elapse_t
.tv_usec
- Save_t
.tv_usec
));
5156 appendStringInfo(&str
,
5157 "!\t[%ld.%06ld s user, %ld.%06ld s system total]\n",
5159 (long) user
.tv_usec
,
5161 (long) sys
.tv_usec
);
5165 * The following rusage fields are not defined by POSIX, but they're
5166 * present on all current Unix-like systems so we use them without any
5167 * special checks. Some of these could be provided in our Windows
5168 * emulation in src/port/win32getrusage.c with more work.
5170 appendStringInfo(&str
,
5171 "!\t%ld kB max resident size\n",
5172 #if defined(__darwin__)
5173 /* in bytes on macOS */
5176 /* in kilobytes on most other platforms */
5180 appendStringInfo(&str
,
5181 "!\t%ld/%ld [%ld/%ld] filesystem blocks in/out\n",
5182 r
.ru_inblock
- Save_r
.ru_inblock
,
5183 /* they only drink coffee at dec */
5184 r
.ru_oublock
- Save_r
.ru_oublock
,
5185 r
.ru_inblock
, r
.ru_oublock
);
5186 appendStringInfo(&str
,
5187 "!\t%ld/%ld [%ld/%ld] page faults/reclaims, %ld [%ld] swaps\n",
5188 r
.ru_majflt
- Save_r
.ru_majflt
,
5189 r
.ru_minflt
- Save_r
.ru_minflt
,
5190 r
.ru_majflt
, r
.ru_minflt
,
5191 r
.ru_nswap
- Save_r
.ru_nswap
,
5193 appendStringInfo(&str
,
5194 "!\t%ld [%ld] signals rcvd, %ld/%ld [%ld/%ld] messages rcvd/sent\n",
5195 r
.ru_nsignals
- Save_r
.ru_nsignals
,
5197 r
.ru_msgrcv
- Save_r
.ru_msgrcv
,
5198 r
.ru_msgsnd
- Save_r
.ru_msgsnd
,
5199 r
.ru_msgrcv
, r
.ru_msgsnd
);
5200 appendStringInfo(&str
,
5201 "!\t%ld/%ld [%ld/%ld] voluntary/involuntary context switches\n",
5202 r
.ru_nvcsw
- Save_r
.ru_nvcsw
,
5203 r
.ru_nivcsw
- Save_r
.ru_nivcsw
,
5204 r
.ru_nvcsw
, r
.ru_nivcsw
);
5207 /* remove trailing newline */
5208 if (str
.data
[str
.len
- 1] == '\n')
5209 str
.data
[--str
.len
] = '\0';
5212 (errmsg_internal("%s", title
),
5213 errdetail_internal("%s", str
.data
)));
5219 * on_proc_exit handler to log end of session
5222 log_disconnections(int code
, Datum arg
)
5224 Port
*port
= MyProcPort
;
5232 TimestampDifference(MyStartTimestamp
,
5233 GetCurrentTimestamp(),
5235 msecs
= usecs
/ 1000;
5237 hours
= secs
/ SECS_PER_HOUR
;
5238 secs
%= SECS_PER_HOUR
;
5239 minutes
= secs
/ SECS_PER_MINUTE
;
5240 seconds
= secs
% SECS_PER_MINUTE
;
5243 (errmsg("disconnection: session time: %d:%02d:%02d.%03d "
5244 "user=%s database=%s host=%s%s%s",
5245 hours
, minutes
, seconds
, msecs
,
5246 port
->user_name
, port
->database_name
, port
->remote_host
,
5247 port
->remote_port
[0] ? " port=" : "", port
->remote_port
)));
5251 * Start statement timeout timer, if enabled.
5253 * If there's already a timeout running, don't restart the timer. That
5254 * enables compromises between accuracy of timeouts and cost of starting a
5258 enable_statement_timeout(void)
5260 /* must be within an xact */
5261 Assert(xact_started
);
5263 if (StatementTimeout
> 0
5264 && (StatementTimeout
< TransactionTimeout
|| TransactionTimeout
== 0))
5266 if (!get_timeout_active(STATEMENT_TIMEOUT
))
5267 enable_timeout_after(STATEMENT_TIMEOUT
, StatementTimeout
);
5271 if (get_timeout_active(STATEMENT_TIMEOUT
))
5272 disable_timeout(STATEMENT_TIMEOUT
, false);
5277 * Disable statement timeout, if active.
5280 disable_statement_timeout(void)
5282 if (get_timeout_active(STATEMENT_TIMEOUT
))
5283 disable_timeout(STATEMENT_TIMEOUT
, false);