doc Makefile: issue warning about chars that cannot be output
[pgsql.git] / src / backend / tcop / postgres.c
blob4b985bd0561513c74719d1da03fe5759ac41f9e0
1 /*-------------------------------------------------------------------------
3 * postgres.c
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
10 * IDENTIFICATION
11 * src/backend/tcop/postgres.c
13 * NOTES
14 * this is the "main" module of the postgres backend and
15 * hence the main module of the "traffic cop".
17 *-------------------------------------------------------------------------
20 #include "postgres.h"
22 #include <fcntl.h>
23 #include <limits.h>
24 #include <signal.h>
25 #include <unistd.h>
26 #include <sys/resource.h>
27 #include <sys/socket.h>
28 #include <sys/time.h>
30 #ifdef USE_VALGRIND
31 #include <valgrind/valgrind.h>
32 #endif
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"
42 #include "jit/jit.h"
43 #include "libpq/libpq.h"
44 #include "libpq/pqformat.h"
45 #include "libpq/pqsignal.h"
46 #include "mb/pg_wchar.h"
47 #include "mb/stringinfo_mb.h"
48 #include "miscadmin.h"
49 #include "nodes/print.h"
50 #include "optimizer/optimizer.h"
51 #include "parser/analyze.h"
52 #include "parser/parser.h"
53 #include "pg_getopt.h"
54 #include "pg_trace.h"
55 #include "pgstat.h"
56 #include "postmaster/interrupt.h"
57 #include "postmaster/postmaster.h"
58 #include "replication/logicallauncher.h"
59 #include "replication/logicalworker.h"
60 #include "replication/slot.h"
61 #include "replication/walsender.h"
62 #include "rewrite/rewriteHandler.h"
63 #include "storage/bufmgr.h"
64 #include "storage/ipc.h"
65 #include "storage/pmsignal.h"
66 #include "storage/proc.h"
67 #include "storage/procsignal.h"
68 #include "storage/sinval.h"
69 #include "tcop/fastpath.h"
70 #include "tcop/pquery.h"
71 #include "tcop/tcopprot.h"
72 #include "tcop/utility.h"
73 #include "utils/guc_hooks.h"
74 #include "utils/injection_point.h"
75 #include "utils/lsyscache.h"
76 #include "utils/memutils.h"
77 #include "utils/ps_status.h"
78 #include "utils/snapmgr.h"
79 #include "utils/timeout.h"
80 #include "utils/timestamp.h"
81 #include "utils/varlena.h"
83 /* ----------------
84 * global variables
85 * ----------------
87 const char *debug_query_string; /* client-supplied query string */
89 /* Note: whereToSendOutput is initialized for the bootstrap/standalone case */
90 CommandDest whereToSendOutput = DestDebug;
92 /* flag for logging end of session */
93 bool Log_disconnections = false;
95 int log_statement = LOGSTMT_NONE;
97 /* GUC variable for maximum stack depth (measured in kilobytes) */
98 int max_stack_depth = 100;
100 /* wait N seconds to allow attach from a debugger */
101 int PostAuthDelay = 0;
103 /* Time between checks that the client is still connected. */
104 int client_connection_check_interval = 0;
106 /* flags for non-system relation kinds to restrict use */
107 int restrict_nonsystem_relation_kind;
109 /* ----------------
110 * private typedefs etc
111 * ----------------
114 /* type of argument for bind_param_error_callback */
115 typedef struct BindParamCbData
117 const char *portalName;
118 int paramno; /* zero-based param number, or -1 initially */
119 const char *paramval; /* textual input string, if available */
120 } BindParamCbData;
122 /* ----------------
123 * private variables
124 * ----------------
127 /* max_stack_depth converted to bytes for speed of checking */
128 static long max_stack_depth_bytes = 100 * 1024L;
131 * Stack base pointer -- initialized by PostmasterMain and inherited by
132 * subprocesses (but see also InitPostmasterChild).
134 static char *stack_base_ptr = NULL;
137 * Flag to keep track of whether we have started a transaction.
138 * For extended query protocol this has to be remembered across messages.
140 static bool xact_started = false;
143 * Flag to indicate that we are doing the outer loop's read-from-client,
144 * as opposed to any random read from client that might happen within
145 * commands like COPY FROM STDIN.
147 static bool DoingCommandRead = false;
150 * Flags to implement skip-till-Sync-after-error behavior for messages of
151 * the extended query protocol.
153 static bool doing_extended_query_message = false;
154 static bool ignore_till_sync = false;
157 * If an unnamed prepared statement exists, it's stored here.
158 * We keep it separate from the hashtable kept by commands/prepare.c
159 * in order to reduce overhead for short-lived queries.
161 static CachedPlanSource *unnamed_stmt_psrc = NULL;
163 /* assorted command-line switches */
164 static const char *userDoption = NULL; /* -D switch */
165 static bool EchoQuery = false; /* -E switch */
166 static bool UseSemiNewlineNewline = false; /* -j switch */
168 /* whether or not, and why, we were canceled by conflict with recovery */
169 static volatile sig_atomic_t RecoveryConflictPending = false;
170 static volatile sig_atomic_t RecoveryConflictPendingReasons[NUM_PROCSIGNALS];
172 /* reused buffer to pass to SendRowDescriptionMessage() */
173 static MemoryContext row_description_context = NULL;
174 static StringInfoData row_description_buf;
176 /* ----------------------------------------------------------------
177 * decls for routines only used in this file
178 * ----------------------------------------------------------------
180 static int InteractiveBackend(StringInfo inBuf);
181 static int interactive_getc(void);
182 static int SocketBackend(StringInfo inBuf);
183 static int ReadCommand(StringInfo inBuf);
184 static void forbidden_in_wal_sender(char firstchar);
185 static bool check_log_statement(List *stmt_list);
186 static int errdetail_execute(List *raw_parsetree_list);
187 static int errdetail_params(ParamListInfo params);
188 static int errdetail_abort(void);
189 static void bind_param_error_callback(void *arg);
190 static void start_xact_command(void);
191 static void finish_xact_command(void);
192 static bool IsTransactionExitStmt(Node *parsetree);
193 static bool IsTransactionExitStmtList(List *pstmts);
194 static bool IsTransactionStmtList(List *pstmts);
195 static void drop_unnamed_stmt(void);
196 static void log_disconnections(int code, Datum arg);
197 static void enable_statement_timeout(void);
198 static void disable_statement_timeout(void);
201 /* ----------------------------------------------------------------
202 * infrastructure for valgrind debugging
203 * ----------------------------------------------------------------
205 #ifdef USE_VALGRIND
206 /* This variable should be set at the top of the main loop. */
207 static unsigned int old_valgrind_error_count;
210 * If Valgrind detected any errors since old_valgrind_error_count was updated,
211 * report the current query as the cause. This should be called at the end
212 * of message processing.
214 static void
215 valgrind_report_error_query(const char *query)
217 unsigned int valgrind_error_count = VALGRIND_COUNT_ERRORS;
219 if (unlikely(valgrind_error_count != old_valgrind_error_count) &&
220 query != NULL)
221 VALGRIND_PRINTF("Valgrind detected %u error(s) during execution of \"%s\"\n",
222 valgrind_error_count - old_valgrind_error_count,
223 query);
226 #else /* !USE_VALGRIND */
227 #define valgrind_report_error_query(query) ((void) 0)
228 #endif /* USE_VALGRIND */
231 /* ----------------------------------------------------------------
232 * routines to obtain user input
233 * ----------------------------------------------------------------
236 /* ----------------
237 * InteractiveBackend() is called for user interactive connections
239 * the string entered by the user is placed in its parameter inBuf,
240 * and we act like a Q message was received.
242 * EOF is returned if end-of-file input is seen; time to shut down.
243 * ----------------
246 static int
247 InteractiveBackend(StringInfo inBuf)
249 int c; /* character read from getc() */
252 * display a prompt and obtain input from the user
254 printf("backend> ");
255 fflush(stdout);
257 resetStringInfo(inBuf);
260 * Read characters until EOF or the appropriate delimiter is seen.
262 while ((c = interactive_getc()) != EOF)
264 if (c == '\n')
266 if (UseSemiNewlineNewline)
269 * In -j mode, semicolon followed by two newlines ends the
270 * command; otherwise treat newline as regular character.
272 if (inBuf->len > 1 &&
273 inBuf->data[inBuf->len - 1] == '\n' &&
274 inBuf->data[inBuf->len - 2] == ';')
276 /* might as well drop the second newline */
277 break;
280 else
283 * In plain mode, newline ends the command unless preceded by
284 * backslash.
286 if (inBuf->len > 0 &&
287 inBuf->data[inBuf->len - 1] == '\\')
289 /* discard backslash from inBuf */
290 inBuf->data[--inBuf->len] = '\0';
291 /* discard newline too */
292 continue;
294 else
296 /* keep the newline character, but end the command */
297 appendStringInfoChar(inBuf, '\n');
298 break;
303 /* Not newline, or newline treated as regular character */
304 appendStringInfoChar(inBuf, (char) c);
307 /* No input before EOF signal means time to quit. */
308 if (c == EOF && inBuf->len == 0)
309 return EOF;
312 * otherwise we have a user query so process it.
315 /* Add '\0' to make it look the same as message case. */
316 appendStringInfoChar(inBuf, (char) '\0');
319 * if the query echo flag was given, print the query..
321 if (EchoQuery)
322 printf("statement: %s\n", inBuf->data);
323 fflush(stdout);
325 return 'Q';
329 * interactive_getc -- collect one character from stdin
331 * Even though we are not reading from a "client" process, we still want to
332 * respond to signals, particularly SIGTERM/SIGQUIT.
334 static int
335 interactive_getc(void)
337 int c;
340 * This will not process catchup interrupts or notifications while
341 * reading. But those can't really be relevant for a standalone backend
342 * anyway. To properly handle SIGTERM there's a hack in die() that
343 * directly processes interrupts at this stage...
345 CHECK_FOR_INTERRUPTS();
347 c = getc(stdin);
349 ProcessClientReadInterrupt(false);
351 return c;
354 /* ----------------
355 * SocketBackend() Is called for frontend-backend connections
357 * Returns the message type code, and loads message body data into inBuf.
359 * EOF is returned if the connection is lost.
360 * ----------------
362 static int
363 SocketBackend(StringInfo inBuf)
365 int qtype;
366 int maxmsglen;
369 * Get message type code from the frontend.
371 HOLD_CANCEL_INTERRUPTS();
372 pq_startmsgread();
373 qtype = pq_getbyte();
375 if (qtype == EOF) /* frontend disconnected */
377 if (IsTransactionState())
378 ereport(COMMERROR,
379 (errcode(ERRCODE_CONNECTION_FAILURE),
380 errmsg("unexpected EOF on client connection with an open transaction")));
381 else
384 * Can't send DEBUG log messages to client at this point. Since
385 * we're disconnecting right away, we don't need to restore
386 * whereToSendOutput.
388 whereToSendOutput = DestNone;
389 ereport(DEBUG1,
390 (errcode(ERRCODE_CONNECTION_DOES_NOT_EXIST),
391 errmsg_internal("unexpected EOF on client connection")));
393 return qtype;
397 * Validate message type code before trying to read body; if we have lost
398 * sync, better to say "command unknown" than to run out of memory because
399 * we used garbage as a length word. We can also select a type-dependent
400 * limit on what a sane length word could be. (The limit could be chosen
401 * more granularly, but it's not clear it's worth fussing over.)
403 * This also gives us a place to set the doing_extended_query_message flag
404 * as soon as possible.
406 switch (qtype)
408 case PqMsg_Query:
409 maxmsglen = PQ_LARGE_MESSAGE_LIMIT;
410 doing_extended_query_message = false;
411 break;
413 case PqMsg_FunctionCall:
414 maxmsglen = PQ_LARGE_MESSAGE_LIMIT;
415 doing_extended_query_message = false;
416 break;
418 case PqMsg_Terminate:
419 maxmsglen = PQ_SMALL_MESSAGE_LIMIT;
420 doing_extended_query_message = false;
421 ignore_till_sync = false;
422 break;
424 case PqMsg_Bind:
425 case PqMsg_Parse:
426 maxmsglen = PQ_LARGE_MESSAGE_LIMIT;
427 doing_extended_query_message = true;
428 break;
430 case PqMsg_Close:
431 case PqMsg_Describe:
432 case PqMsg_Execute:
433 case PqMsg_Flush:
434 maxmsglen = PQ_SMALL_MESSAGE_LIMIT;
435 doing_extended_query_message = true;
436 break;
438 case PqMsg_Sync:
439 maxmsglen = PQ_SMALL_MESSAGE_LIMIT;
440 /* stop any active skip-till-Sync */
441 ignore_till_sync = false;
442 /* mark not-extended, so that a new error doesn't begin skip */
443 doing_extended_query_message = false;
444 break;
446 case PqMsg_CopyData:
447 maxmsglen = PQ_LARGE_MESSAGE_LIMIT;
448 doing_extended_query_message = false;
449 break;
451 case PqMsg_CopyDone:
452 case PqMsg_CopyFail:
453 maxmsglen = PQ_SMALL_MESSAGE_LIMIT;
454 doing_extended_query_message = false;
455 break;
457 default:
460 * Otherwise we got garbage from the frontend. We treat this as
461 * fatal because we have probably lost message boundary sync, and
462 * there's no good way to recover.
464 ereport(FATAL,
465 (errcode(ERRCODE_PROTOCOL_VIOLATION),
466 errmsg("invalid frontend message type %d", qtype)));
467 maxmsglen = 0; /* keep compiler quiet */
468 break;
472 * In protocol version 3, all frontend messages have a length word next
473 * after the type code; we can read the message contents independently of
474 * the type.
476 if (pq_getmessage(inBuf, maxmsglen))
477 return EOF; /* suitable message already logged */
478 RESUME_CANCEL_INTERRUPTS();
480 return qtype;
483 /* ----------------
484 * ReadCommand reads a command from either the frontend or
485 * standard input, places it in inBuf, and returns the
486 * message type code (first byte of the message).
487 * EOF is returned if end of file.
488 * ----------------
490 static int
491 ReadCommand(StringInfo inBuf)
493 int result;
495 if (whereToSendOutput == DestRemote)
496 result = SocketBackend(inBuf);
497 else
498 result = InteractiveBackend(inBuf);
499 return result;
503 * ProcessClientReadInterrupt() - Process interrupts specific to client reads
505 * This is called just before and after low-level reads.
506 * 'blocked' is true if no data was available to read and we plan to retry,
507 * false if about to read or done reading.
509 * Must preserve errno!
511 void
512 ProcessClientReadInterrupt(bool blocked)
514 int save_errno = errno;
516 if (DoingCommandRead)
518 /* Check for general interrupts that arrived before/while reading */
519 CHECK_FOR_INTERRUPTS();
521 /* Process sinval catchup interrupts, if any */
522 if (catchupInterruptPending)
523 ProcessCatchupInterrupt();
525 /* Process notify interrupts, if any */
526 if (notifyInterruptPending)
527 ProcessNotifyInterrupt(true);
529 else if (ProcDiePending)
532 * We're dying. If there is no data available to read, then it's safe
533 * (and sane) to handle that now. If we haven't tried to read yet,
534 * make sure the process latch is set, so that if there is no data
535 * then we'll come back here and die. If we're done reading, also
536 * make sure the process latch is set, as we might've undesirably
537 * cleared it while reading.
539 if (blocked)
540 CHECK_FOR_INTERRUPTS();
541 else
542 SetLatch(MyLatch);
545 errno = save_errno;
549 * ProcessClientWriteInterrupt() - Process interrupts specific to client writes
551 * This is called just before and after low-level writes.
552 * 'blocked' is true if no data could be written and we plan to retry,
553 * false if about to write or done writing.
555 * Must preserve errno!
557 void
558 ProcessClientWriteInterrupt(bool blocked)
560 int save_errno = errno;
562 if (ProcDiePending)
565 * We're dying. If it's not possible to write, then we should handle
566 * that immediately, else a stuck client could indefinitely delay our
567 * response to the signal. If we haven't tried to write yet, make
568 * sure the process latch is set, so that if the write would block
569 * then we'll come back here and die. If we're done writing, also
570 * make sure the process latch is set, as we might've undesirably
571 * cleared it while writing.
573 if (blocked)
576 * Don't mess with whereToSendOutput if ProcessInterrupts wouldn't
577 * service ProcDiePending.
579 if (InterruptHoldoffCount == 0 && CritSectionCount == 0)
582 * We don't want to send the client the error message, as a)
583 * that would possibly block again, and b) it would likely
584 * lead to loss of protocol sync because we may have already
585 * sent a partial protocol message.
587 if (whereToSendOutput == DestRemote)
588 whereToSendOutput = DestNone;
590 CHECK_FOR_INTERRUPTS();
593 else
594 SetLatch(MyLatch);
597 errno = save_errno;
601 * Do raw parsing (only).
603 * A list of parsetrees (RawStmt nodes) is returned, since there might be
604 * multiple commands in the given string.
606 * NOTE: for interactive queries, it is important to keep this routine
607 * separate from the analysis & rewrite stages. Analysis and rewriting
608 * cannot be done in an aborted transaction, since they require access to
609 * database tables. So, we rely on the raw parser to determine whether
610 * we've seen a COMMIT or ABORT command; when we are in abort state, other
611 * commands are not processed any further than the raw parse stage.
613 List *
614 pg_parse_query(const char *query_string)
616 List *raw_parsetree_list;
618 TRACE_POSTGRESQL_QUERY_PARSE_START(query_string);
620 if (log_parser_stats)
621 ResetUsage();
623 raw_parsetree_list = raw_parser(query_string, RAW_PARSE_DEFAULT);
625 if (log_parser_stats)
626 ShowUsage("PARSER STATISTICS");
628 #ifdef DEBUG_NODE_TESTS_ENABLED
630 /* Optional debugging check: pass raw parsetrees through copyObject() */
631 if (Debug_copy_parse_plan_trees)
633 List *new_list = copyObject(raw_parsetree_list);
635 /* This checks both copyObject() and the equal() routines... */
636 if (!equal(new_list, raw_parsetree_list))
637 elog(WARNING, "copyObject() failed to produce an equal raw parse tree");
638 else
639 raw_parsetree_list = new_list;
643 * Optional debugging check: pass raw parsetrees through
644 * outfuncs/readfuncs
646 if (Debug_write_read_parse_plan_trees)
648 char *str = nodeToStringWithLocations(raw_parsetree_list);
649 List *new_list = stringToNodeWithLocations(str);
651 pfree(str);
652 /* This checks both outfuncs/readfuncs and the equal() routines... */
653 if (!equal(new_list, raw_parsetree_list))
654 elog(WARNING, "outfuncs/readfuncs failed to produce an equal raw parse tree");
655 else
656 raw_parsetree_list = new_list;
659 #endif /* DEBUG_NODE_TESTS_ENABLED */
661 TRACE_POSTGRESQL_QUERY_PARSE_DONE(query_string);
663 return raw_parsetree_list;
667 * Given a raw parsetree (gram.y output), and optionally information about
668 * types of parameter symbols ($n), perform parse analysis and rule rewriting.
670 * A list of Query nodes is returned, since either the analyzer or the
671 * rewriter might expand one query to several.
673 * NOTE: for reasons mentioned above, this must be separate from raw parsing.
675 List *
676 pg_analyze_and_rewrite_fixedparams(RawStmt *parsetree,
677 const char *query_string,
678 const Oid *paramTypes,
679 int numParams,
680 QueryEnvironment *queryEnv)
682 Query *query;
683 List *querytree_list;
685 TRACE_POSTGRESQL_QUERY_REWRITE_START(query_string);
688 * (1) Perform parse analysis.
690 if (log_parser_stats)
691 ResetUsage();
693 query = parse_analyze_fixedparams(parsetree, query_string, paramTypes, numParams,
694 queryEnv);
696 if (log_parser_stats)
697 ShowUsage("PARSE ANALYSIS STATISTICS");
700 * (2) Rewrite the queries, as necessary
702 querytree_list = pg_rewrite_query(query);
704 TRACE_POSTGRESQL_QUERY_REWRITE_DONE(query_string);
706 return querytree_list;
710 * Do parse analysis and rewriting. This is the same as
711 * pg_analyze_and_rewrite_fixedparams except that it's okay to deduce
712 * information about $n symbol datatypes from context.
714 List *
715 pg_analyze_and_rewrite_varparams(RawStmt *parsetree,
716 const char *query_string,
717 Oid **paramTypes,
718 int *numParams,
719 QueryEnvironment *queryEnv)
721 Query *query;
722 List *querytree_list;
724 TRACE_POSTGRESQL_QUERY_REWRITE_START(query_string);
727 * (1) Perform parse analysis.
729 if (log_parser_stats)
730 ResetUsage();
732 query = parse_analyze_varparams(parsetree, query_string, paramTypes, numParams,
733 queryEnv);
736 * Check all parameter types got determined.
738 for (int i = 0; i < *numParams; i++)
740 Oid ptype = (*paramTypes)[i];
742 if (ptype == InvalidOid || ptype == UNKNOWNOID)
743 ereport(ERROR,
744 (errcode(ERRCODE_INDETERMINATE_DATATYPE),
745 errmsg("could not determine data type of parameter $%d",
746 i + 1)));
749 if (log_parser_stats)
750 ShowUsage("PARSE ANALYSIS STATISTICS");
753 * (2) Rewrite the queries, as necessary
755 querytree_list = pg_rewrite_query(query);
757 TRACE_POSTGRESQL_QUERY_REWRITE_DONE(query_string);
759 return querytree_list;
763 * Do parse analysis and rewriting. This is the same as
764 * pg_analyze_and_rewrite_fixedparams except that, instead of a fixed list of
765 * parameter datatypes, a parser callback is supplied that can do
766 * external-parameter resolution and possibly other things.
768 List *
769 pg_analyze_and_rewrite_withcb(RawStmt *parsetree,
770 const char *query_string,
771 ParserSetupHook parserSetup,
772 void *parserSetupArg,
773 QueryEnvironment *queryEnv)
775 Query *query;
776 List *querytree_list;
778 TRACE_POSTGRESQL_QUERY_REWRITE_START(query_string);
781 * (1) Perform parse analysis.
783 if (log_parser_stats)
784 ResetUsage();
786 query = parse_analyze_withcb(parsetree, query_string, parserSetup, parserSetupArg,
787 queryEnv);
789 if (log_parser_stats)
790 ShowUsage("PARSE ANALYSIS STATISTICS");
793 * (2) Rewrite the queries, as necessary
795 querytree_list = pg_rewrite_query(query);
797 TRACE_POSTGRESQL_QUERY_REWRITE_DONE(query_string);
799 return querytree_list;
803 * Perform rewriting of a query produced by parse analysis.
805 * Note: query must just have come from the parser, because we do not do
806 * AcquireRewriteLocks() on it.
808 List *
809 pg_rewrite_query(Query *query)
811 List *querytree_list;
813 if (Debug_print_parse)
814 elog_node_display(LOG, "parse tree", query,
815 Debug_pretty_print);
817 if (log_parser_stats)
818 ResetUsage();
820 if (query->commandType == CMD_UTILITY)
822 /* don't rewrite utilities, just dump 'em into result list */
823 querytree_list = list_make1(query);
825 else
827 /* rewrite regular queries */
828 querytree_list = QueryRewrite(query);
831 if (log_parser_stats)
832 ShowUsage("REWRITER STATISTICS");
834 #ifdef DEBUG_NODE_TESTS_ENABLED
836 /* Optional debugging check: pass querytree through copyObject() */
837 if (Debug_copy_parse_plan_trees)
839 List *new_list;
841 new_list = copyObject(querytree_list);
842 /* This checks both copyObject() and the equal() routines... */
843 if (!equal(new_list, querytree_list))
844 elog(WARNING, "copyObject() failed to produce an equal rewritten parse tree");
845 else
846 querytree_list = new_list;
849 /* Optional debugging check: pass querytree through outfuncs/readfuncs */
850 if (Debug_write_read_parse_plan_trees)
852 List *new_list = NIL;
853 ListCell *lc;
855 foreach(lc, querytree_list)
857 Query *curr_query = lfirst_node(Query, lc);
858 char *str = nodeToStringWithLocations(curr_query);
859 Query *new_query = stringToNodeWithLocations(str);
862 * queryId is not saved in stored rules, but we must preserve it
863 * here to avoid breaking pg_stat_statements.
865 new_query->queryId = curr_query->queryId;
867 new_list = lappend(new_list, new_query);
868 pfree(str);
871 /* This checks both outfuncs/readfuncs and the equal() routines... */
872 if (!equal(new_list, querytree_list))
873 elog(WARNING, "outfuncs/readfuncs failed to produce an equal rewritten parse tree");
874 else
875 querytree_list = new_list;
878 #endif /* DEBUG_NODE_TESTS_ENABLED */
880 if (Debug_print_rewritten)
881 elog_node_display(LOG, "rewritten parse tree", querytree_list,
882 Debug_pretty_print);
884 return querytree_list;
889 * Generate a plan for a single already-rewritten query.
890 * This is a thin wrapper around planner() and takes the same parameters.
892 PlannedStmt *
893 pg_plan_query(Query *querytree, const char *query_string, int cursorOptions,
894 ParamListInfo boundParams)
896 PlannedStmt *plan;
898 /* Utility commands have no plans. */
899 if (querytree->commandType == CMD_UTILITY)
900 return NULL;
902 /* Planner must have a snapshot in case it calls user-defined functions. */
903 Assert(ActiveSnapshotSet());
905 TRACE_POSTGRESQL_QUERY_PLAN_START();
907 if (log_planner_stats)
908 ResetUsage();
910 /* call the optimizer */
911 plan = planner(querytree, query_string, cursorOptions, boundParams);
913 if (log_planner_stats)
914 ShowUsage("PLANNER STATISTICS");
916 #ifdef DEBUG_NODE_TESTS_ENABLED
918 /* Optional debugging check: pass plan tree through copyObject() */
919 if (Debug_copy_parse_plan_trees)
921 PlannedStmt *new_plan = copyObject(plan);
924 * equal() currently does not have routines to compare Plan nodes, so
925 * don't try to test equality here. Perhaps fix someday?
927 #ifdef NOT_USED
928 /* This checks both copyObject() and the equal() routines... */
929 if (!equal(new_plan, plan))
930 elog(WARNING, "copyObject() failed to produce an equal plan tree");
931 else
932 #endif
933 plan = new_plan;
936 /* Optional debugging check: pass plan tree through outfuncs/readfuncs */
937 if (Debug_write_read_parse_plan_trees)
939 char *str;
940 PlannedStmt *new_plan;
942 str = nodeToStringWithLocations(plan);
943 new_plan = stringToNodeWithLocations(str);
944 pfree(str);
947 * equal() currently does not have routines to compare Plan nodes, so
948 * don't try to test equality here. Perhaps fix someday?
950 #ifdef NOT_USED
951 /* This checks both outfuncs/readfuncs and the equal() routines... */
952 if (!equal(new_plan, plan))
953 elog(WARNING, "outfuncs/readfuncs failed to produce an equal plan tree");
954 else
955 #endif
956 plan = new_plan;
959 #endif /* DEBUG_NODE_TESTS_ENABLED */
962 * Print plan if debugging.
964 if (Debug_print_plan)
965 elog_node_display(LOG, "plan", plan, Debug_pretty_print);
967 TRACE_POSTGRESQL_QUERY_PLAN_DONE();
969 return plan;
973 * Generate plans for a list of already-rewritten queries.
975 * For normal optimizable statements, invoke the planner. For utility
976 * statements, just make a wrapper PlannedStmt node.
978 * The result is a list of PlannedStmt nodes.
980 List *
981 pg_plan_queries(List *querytrees, const char *query_string, int cursorOptions,
982 ParamListInfo boundParams)
984 List *stmt_list = NIL;
985 ListCell *query_list;
987 foreach(query_list, querytrees)
989 Query *query = lfirst_node(Query, query_list);
990 PlannedStmt *stmt;
992 if (query->commandType == CMD_UTILITY)
994 /* Utility commands require no planning. */
995 stmt = makeNode(PlannedStmt);
996 stmt->commandType = CMD_UTILITY;
997 stmt->canSetTag = query->canSetTag;
998 stmt->utilityStmt = query->utilityStmt;
999 stmt->stmt_location = query->stmt_location;
1000 stmt->stmt_len = query->stmt_len;
1001 stmt->queryId = query->queryId;
1003 else
1005 stmt = pg_plan_query(query, query_string, cursorOptions,
1006 boundParams);
1009 stmt_list = lappend(stmt_list, stmt);
1012 return stmt_list;
1017 * exec_simple_query
1019 * Execute a "simple Query" protocol message.
1021 static void
1022 exec_simple_query(const char *query_string)
1024 CommandDest dest = whereToSendOutput;
1025 MemoryContext oldcontext;
1026 List *parsetree_list;
1027 ListCell *parsetree_item;
1028 bool save_log_statement_stats = log_statement_stats;
1029 bool was_logged = false;
1030 bool use_implicit_block;
1031 char msec_str[32];
1034 * Report query to various monitoring facilities.
1036 debug_query_string = query_string;
1038 pgstat_report_activity(STATE_RUNNING, query_string);
1040 TRACE_POSTGRESQL_QUERY_START(query_string);
1043 * We use save_log_statement_stats so ShowUsage doesn't report incorrect
1044 * results because ResetUsage wasn't called.
1046 if (save_log_statement_stats)
1047 ResetUsage();
1050 * Start up a transaction command. All queries generated by the
1051 * query_string will be in this same command block, *unless* we find a
1052 * BEGIN/COMMIT/ABORT statement; we have to force a new xact command after
1053 * one of those, else bad things will happen in xact.c. (Note that this
1054 * will normally change current memory context.)
1056 start_xact_command();
1059 * Zap any pre-existing unnamed statement. (While not strictly necessary,
1060 * it seems best to define simple-Query mode as if it used the unnamed
1061 * statement and portal; this ensures we recover any storage used by prior
1062 * unnamed operations.)
1064 drop_unnamed_stmt();
1067 * Switch to appropriate context for constructing parsetrees.
1069 oldcontext = MemoryContextSwitchTo(MessageContext);
1072 * Do basic parsing of the query or queries (this should be safe even if
1073 * we are in aborted transaction state!)
1075 parsetree_list = pg_parse_query(query_string);
1077 /* Log immediately if dictated by log_statement */
1078 if (check_log_statement(parsetree_list))
1080 ereport(LOG,
1081 (errmsg("statement: %s", query_string),
1082 errhidestmt(true),
1083 errdetail_execute(parsetree_list)));
1084 was_logged = true;
1088 * Switch back to transaction context to enter the loop.
1090 MemoryContextSwitchTo(oldcontext);
1093 * For historical reasons, if multiple SQL statements are given in a
1094 * single "simple Query" message, we execute them as a single transaction,
1095 * unless explicit transaction control commands are included to make
1096 * portions of the list be separate transactions. To represent this
1097 * behavior properly in the transaction machinery, we use an "implicit"
1098 * transaction block.
1100 use_implicit_block = (list_length(parsetree_list) > 1);
1103 * Run through the raw parsetree(s) and process each one.
1105 foreach(parsetree_item, parsetree_list)
1107 RawStmt *parsetree = lfirst_node(RawStmt, parsetree_item);
1108 bool snapshot_set = false;
1109 CommandTag commandTag;
1110 QueryCompletion qc;
1111 MemoryContext per_parsetree_context = NULL;
1112 List *querytree_list,
1113 *plantree_list;
1114 Portal portal;
1115 DestReceiver *receiver;
1116 int16 format;
1117 const char *cmdtagname;
1118 size_t cmdtaglen;
1120 pgstat_report_query_id(0, true);
1123 * Get the command name for use in status display (it also becomes the
1124 * default completion tag, down inside PortalRun). Set ps_status and
1125 * do any special start-of-SQL-command processing needed by the
1126 * destination.
1128 commandTag = CreateCommandTag(parsetree->stmt);
1129 cmdtagname = GetCommandTagNameAndLen(commandTag, &cmdtaglen);
1131 set_ps_display_with_len(cmdtagname, cmdtaglen);
1133 BeginCommand(commandTag, dest);
1136 * If we are in an aborted transaction, reject all commands except
1137 * COMMIT/ABORT. It is important that this test occur before we try
1138 * to do parse analysis, rewrite, or planning, since all those phases
1139 * try to do database accesses, which may fail in abort state. (It
1140 * might be safe to allow some additional utility commands in this
1141 * state, but not many...)
1143 if (IsAbortedTransactionBlockState() &&
1144 !IsTransactionExitStmt(parsetree->stmt))
1145 ereport(ERROR,
1146 (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
1147 errmsg("current transaction is aborted, "
1148 "commands ignored until end of transaction block"),
1149 errdetail_abort()));
1151 /* Make sure we are in a transaction command */
1152 start_xact_command();
1155 * If using an implicit transaction block, and we're not already in a
1156 * transaction block, start an implicit block to force this statement
1157 * to be grouped together with any following ones. (We must do this
1158 * each time through the loop; otherwise, a COMMIT/ROLLBACK in the
1159 * list would cause later statements to not be grouped.)
1161 if (use_implicit_block)
1162 BeginImplicitTransactionBlock();
1164 /* If we got a cancel signal in parsing or prior command, quit */
1165 CHECK_FOR_INTERRUPTS();
1168 * Set up a snapshot if parse analysis/planning will need one.
1170 if (analyze_requires_snapshot(parsetree))
1172 PushActiveSnapshot(GetTransactionSnapshot());
1173 snapshot_set = true;
1177 * OK to analyze, rewrite, and plan this query.
1179 * Switch to appropriate context for constructing query and plan trees
1180 * (these can't be in the transaction context, as that will get reset
1181 * when the command is COMMIT/ROLLBACK). If we have multiple
1182 * parsetrees, we use a separate context for each one, so that we can
1183 * free that memory before moving on to the next one. But for the
1184 * last (or only) parsetree, just use MessageContext, which will be
1185 * reset shortly after completion anyway. In event of an error, the
1186 * per_parsetree_context will be deleted when MessageContext is reset.
1188 if (lnext(parsetree_list, parsetree_item) != NULL)
1190 per_parsetree_context =
1191 AllocSetContextCreate(MessageContext,
1192 "per-parsetree message context",
1193 ALLOCSET_DEFAULT_SIZES);
1194 oldcontext = MemoryContextSwitchTo(per_parsetree_context);
1196 else
1197 oldcontext = MemoryContextSwitchTo(MessageContext);
1199 querytree_list = pg_analyze_and_rewrite_fixedparams(parsetree, query_string,
1200 NULL, 0, NULL);
1202 plantree_list = pg_plan_queries(querytree_list, query_string,
1203 CURSOR_OPT_PARALLEL_OK, NULL);
1206 * Done with the snapshot used for parsing/planning.
1208 * While it looks promising to reuse the same snapshot for query
1209 * execution (at least for simple protocol), unfortunately it causes
1210 * execution to use a snapshot that has been acquired before locking
1211 * any of the tables mentioned in the query. This creates user-
1212 * visible anomalies, so refrain. Refer to
1213 * https://postgr.es/m/flat/5075D8DF.6050500@fuzzy.cz for details.
1215 if (snapshot_set)
1216 PopActiveSnapshot();
1218 /* If we got a cancel signal in analysis or planning, quit */
1219 CHECK_FOR_INTERRUPTS();
1222 * Create unnamed portal to run the query or queries in. If there
1223 * already is one, silently drop it.
1225 portal = CreatePortal("", true, true);
1226 /* Don't display the portal in pg_cursors */
1227 portal->visible = false;
1230 * We don't have to copy anything into the portal, because everything
1231 * we are passing here is in MessageContext or the
1232 * per_parsetree_context, and so will outlive the portal anyway.
1234 PortalDefineQuery(portal,
1235 NULL,
1236 query_string,
1237 commandTag,
1238 plantree_list,
1239 NULL);
1242 * Start the portal. No parameters here.
1244 PortalStart(portal, NULL, 0, InvalidSnapshot);
1247 * Select the appropriate output format: text unless we are doing a
1248 * FETCH from a binary cursor. (Pretty grotty to have to do this here
1249 * --- but it avoids grottiness in other places. Ah, the joys of
1250 * backward compatibility...)
1252 format = 0; /* TEXT is default */
1253 if (IsA(parsetree->stmt, FetchStmt))
1255 FetchStmt *stmt = (FetchStmt *) parsetree->stmt;
1257 if (!stmt->ismove)
1259 Portal fportal = GetPortalByName(stmt->portalname);
1261 if (PortalIsValid(fportal) &&
1262 (fportal->cursorOptions & CURSOR_OPT_BINARY))
1263 format = 1; /* BINARY */
1266 PortalSetResultFormat(portal, 1, &format);
1269 * Now we can create the destination receiver object.
1271 receiver = CreateDestReceiver(dest);
1272 if (dest == DestRemote)
1273 SetRemoteDestReceiverParams(receiver, portal);
1276 * Switch back to transaction context for execution.
1278 MemoryContextSwitchTo(oldcontext);
1281 * Run the portal to completion, and then drop it (and the receiver).
1283 (void) PortalRun(portal,
1284 FETCH_ALL,
1285 true, /* always top level */
1286 true,
1287 receiver,
1288 receiver,
1289 &qc);
1291 receiver->rDestroy(receiver);
1293 PortalDrop(portal, false);
1295 if (lnext(parsetree_list, parsetree_item) == NULL)
1298 * If this is the last parsetree of the query string, close down
1299 * transaction statement before reporting command-complete. This
1300 * is so that any end-of-transaction errors are reported before
1301 * the command-complete message is issued, to avoid confusing
1302 * clients who will expect either a command-complete message or an
1303 * error, not one and then the other. Also, if we're using an
1304 * implicit transaction block, we must close that out first.
1306 if (use_implicit_block)
1307 EndImplicitTransactionBlock();
1308 finish_xact_command();
1310 else if (IsA(parsetree->stmt, TransactionStmt))
1313 * If this was a transaction control statement, commit it. We will
1314 * start a new xact command for the next command.
1316 finish_xact_command();
1318 else
1321 * We had better not see XACT_FLAGS_NEEDIMMEDIATECOMMIT set if
1322 * we're not calling finish_xact_command(). (The implicit
1323 * transaction block should have prevented it from getting set.)
1325 Assert(!(MyXactFlags & XACT_FLAGS_NEEDIMMEDIATECOMMIT));
1328 * We need a CommandCounterIncrement after every query, except
1329 * those that start or end a transaction block.
1331 CommandCounterIncrement();
1334 * Disable statement timeout between queries of a multi-query
1335 * string, so that the timeout applies separately to each query.
1336 * (Our next loop iteration will start a fresh timeout.)
1338 disable_statement_timeout();
1342 * Tell client that we're done with this query. Note we emit exactly
1343 * one EndCommand report for each raw parsetree, thus one for each SQL
1344 * command the client sent, regardless of rewriting. (But a command
1345 * aborted by error will not send an EndCommand report at all.)
1347 EndCommand(&qc, dest, false);
1349 /* Now we may drop the per-parsetree context, if one was created. */
1350 if (per_parsetree_context)
1351 MemoryContextDelete(per_parsetree_context);
1352 } /* end loop over parsetrees */
1355 * Close down transaction statement, if one is open. (This will only do
1356 * something if the parsetree list was empty; otherwise the last loop
1357 * iteration already did it.)
1359 finish_xact_command();
1362 * If there were no parsetrees, return EmptyQueryResponse message.
1364 if (!parsetree_list)
1365 NullCommand(dest);
1368 * Emit duration logging if appropriate.
1370 switch (check_log_duration(msec_str, was_logged))
1372 case 1:
1373 ereport(LOG,
1374 (errmsg("duration: %s ms", msec_str),
1375 errhidestmt(true)));
1376 break;
1377 case 2:
1378 ereport(LOG,
1379 (errmsg("duration: %s ms statement: %s",
1380 msec_str, query_string),
1381 errhidestmt(true),
1382 errdetail_execute(parsetree_list)));
1383 break;
1386 if (save_log_statement_stats)
1387 ShowUsage("QUERY STATISTICS");
1389 TRACE_POSTGRESQL_QUERY_DONE(query_string);
1391 debug_query_string = NULL;
1395 * exec_parse_message
1397 * Execute a "Parse" protocol message.
1399 static void
1400 exec_parse_message(const char *query_string, /* string to execute */
1401 const char *stmt_name, /* name for prepared stmt */
1402 Oid *paramTypes, /* parameter types */
1403 int numParams) /* number of parameters */
1405 MemoryContext unnamed_stmt_context = NULL;
1406 MemoryContext oldcontext;
1407 List *parsetree_list;
1408 RawStmt *raw_parse_tree;
1409 List *querytree_list;
1410 CachedPlanSource *psrc;
1411 bool is_named;
1412 bool save_log_statement_stats = log_statement_stats;
1413 char msec_str[32];
1416 * Report query to various monitoring facilities.
1418 debug_query_string = query_string;
1420 pgstat_report_activity(STATE_RUNNING, query_string);
1422 set_ps_display("PARSE");
1424 if (save_log_statement_stats)
1425 ResetUsage();
1427 ereport(DEBUG2,
1428 (errmsg_internal("parse %s: %s",
1429 *stmt_name ? stmt_name : "<unnamed>",
1430 query_string)));
1433 * Start up a transaction command so we can run parse analysis etc. (Note
1434 * that this will normally change current memory context.) Nothing happens
1435 * if we are already in one. This also arms the statement timeout if
1436 * necessary.
1438 start_xact_command();
1441 * Switch to appropriate context for constructing parsetrees.
1443 * We have two strategies depending on whether the prepared statement is
1444 * named or not. For a named prepared statement, we do parsing in
1445 * MessageContext and copy the finished trees into the prepared
1446 * statement's plancache entry; then the reset of MessageContext releases
1447 * temporary space used by parsing and rewriting. For an unnamed prepared
1448 * statement, we assume the statement isn't going to hang around long, so
1449 * getting rid of temp space quickly is probably not worth the costs of
1450 * copying parse trees. So in this case, we create the plancache entry's
1451 * query_context here, and do all the parsing work therein.
1453 is_named = (stmt_name[0] != '\0');
1454 if (is_named)
1456 /* Named prepared statement --- parse in MessageContext */
1457 oldcontext = MemoryContextSwitchTo(MessageContext);
1459 else
1461 /* Unnamed prepared statement --- release any prior unnamed stmt */
1462 drop_unnamed_stmt();
1463 /* Create context for parsing */
1464 unnamed_stmt_context =
1465 AllocSetContextCreate(MessageContext,
1466 "unnamed prepared statement",
1467 ALLOCSET_DEFAULT_SIZES);
1468 oldcontext = MemoryContextSwitchTo(unnamed_stmt_context);
1472 * Do basic parsing of the query or queries (this should be safe even if
1473 * we are in aborted transaction state!)
1475 parsetree_list = pg_parse_query(query_string);
1478 * We only allow a single user statement in a prepared statement. This is
1479 * mainly to keep the protocol simple --- otherwise we'd need to worry
1480 * about multiple result tupdescs and things like that.
1482 if (list_length(parsetree_list) > 1)
1483 ereport(ERROR,
1484 (errcode(ERRCODE_SYNTAX_ERROR),
1485 errmsg("cannot insert multiple commands into a prepared statement")));
1487 if (parsetree_list != NIL)
1489 bool snapshot_set = false;
1491 raw_parse_tree = linitial_node(RawStmt, parsetree_list);
1494 * If we are in an aborted transaction, reject all commands except
1495 * COMMIT/ROLLBACK. It is important that this test occur before we
1496 * try to do parse analysis, rewrite, or planning, since all those
1497 * phases try to do database accesses, which may fail in abort state.
1498 * (It might be safe to allow some additional utility commands in this
1499 * state, but not many...)
1501 if (IsAbortedTransactionBlockState() &&
1502 !IsTransactionExitStmt(raw_parse_tree->stmt))
1503 ereport(ERROR,
1504 (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
1505 errmsg("current transaction is aborted, "
1506 "commands ignored until end of transaction block"),
1507 errdetail_abort()));
1510 * Create the CachedPlanSource before we do parse analysis, since it
1511 * needs to see the unmodified raw parse tree.
1513 psrc = CreateCachedPlan(raw_parse_tree, query_string,
1514 CreateCommandTag(raw_parse_tree->stmt));
1517 * Set up a snapshot if parse analysis will need one.
1519 if (analyze_requires_snapshot(raw_parse_tree))
1521 PushActiveSnapshot(GetTransactionSnapshot());
1522 snapshot_set = true;
1526 * Analyze and rewrite the query. Note that the originally specified
1527 * parameter set is not required to be complete, so we have to use
1528 * pg_analyze_and_rewrite_varparams().
1530 querytree_list = pg_analyze_and_rewrite_varparams(raw_parse_tree,
1531 query_string,
1532 &paramTypes,
1533 &numParams,
1534 NULL);
1536 /* Done with the snapshot used for parsing */
1537 if (snapshot_set)
1538 PopActiveSnapshot();
1540 else
1542 /* Empty input string. This is legal. */
1543 raw_parse_tree = NULL;
1544 psrc = CreateCachedPlan(raw_parse_tree, query_string,
1545 CMDTAG_UNKNOWN);
1546 querytree_list = NIL;
1550 * CachedPlanSource must be a direct child of MessageContext before we
1551 * reparent unnamed_stmt_context under it, else we have a disconnected
1552 * circular subgraph. Klugy, but less so than flipping contexts even more
1553 * above.
1555 if (unnamed_stmt_context)
1556 MemoryContextSetParent(psrc->context, MessageContext);
1558 /* Finish filling in the CachedPlanSource */
1559 CompleteCachedPlan(psrc,
1560 querytree_list,
1561 unnamed_stmt_context,
1562 paramTypes,
1563 numParams,
1564 NULL,
1565 NULL,
1566 CURSOR_OPT_PARALLEL_OK, /* allow parallel mode */
1567 true); /* fixed result */
1569 /* If we got a cancel signal during analysis, quit */
1570 CHECK_FOR_INTERRUPTS();
1572 if (is_named)
1575 * Store the query as a prepared statement.
1577 StorePreparedStatement(stmt_name, psrc, false);
1579 else
1582 * We just save the CachedPlanSource into unnamed_stmt_psrc.
1584 SaveCachedPlan(psrc);
1585 unnamed_stmt_psrc = psrc;
1588 MemoryContextSwitchTo(oldcontext);
1591 * We do NOT close the open transaction command here; that only happens
1592 * when the client sends Sync. Instead, do CommandCounterIncrement just
1593 * in case something happened during parse/plan.
1595 CommandCounterIncrement();
1598 * Send ParseComplete.
1600 if (whereToSendOutput == DestRemote)
1601 pq_putemptymessage(PqMsg_ParseComplete);
1604 * Emit duration logging if appropriate.
1606 switch (check_log_duration(msec_str, false))
1608 case 1:
1609 ereport(LOG,
1610 (errmsg("duration: %s ms", msec_str),
1611 errhidestmt(true)));
1612 break;
1613 case 2:
1614 ereport(LOG,
1615 (errmsg("duration: %s ms parse %s: %s",
1616 msec_str,
1617 *stmt_name ? stmt_name : "<unnamed>",
1618 query_string),
1619 errhidestmt(true)));
1620 break;
1623 if (save_log_statement_stats)
1624 ShowUsage("PARSE MESSAGE STATISTICS");
1626 debug_query_string = NULL;
1630 * exec_bind_message
1632 * Process a "Bind" message to create a portal from a prepared statement
1634 static void
1635 exec_bind_message(StringInfo input_message)
1637 const char *portal_name;
1638 const char *stmt_name;
1639 int numPFormats;
1640 int16 *pformats = NULL;
1641 int numParams;
1642 int numRFormats;
1643 int16 *rformats = NULL;
1644 CachedPlanSource *psrc;
1645 CachedPlan *cplan;
1646 Portal portal;
1647 char *query_string;
1648 char *saved_stmt_name;
1649 ParamListInfo params;
1650 MemoryContext oldContext;
1651 bool save_log_statement_stats = log_statement_stats;
1652 bool snapshot_set = false;
1653 char msec_str[32];
1654 ParamsErrorCbData params_data;
1655 ErrorContextCallback params_errcxt;
1656 ListCell *lc;
1658 /* Get the fixed part of the message */
1659 portal_name = pq_getmsgstring(input_message);
1660 stmt_name = pq_getmsgstring(input_message);
1662 ereport(DEBUG2,
1663 (errmsg_internal("bind %s to %s",
1664 *portal_name ? portal_name : "<unnamed>",
1665 *stmt_name ? stmt_name : "<unnamed>")));
1667 /* Find prepared statement */
1668 if (stmt_name[0] != '\0')
1670 PreparedStatement *pstmt;
1672 pstmt = FetchPreparedStatement(stmt_name, true);
1673 psrc = pstmt->plansource;
1675 else
1677 /* special-case the unnamed statement */
1678 psrc = unnamed_stmt_psrc;
1679 if (!psrc)
1680 ereport(ERROR,
1681 (errcode(ERRCODE_UNDEFINED_PSTATEMENT),
1682 errmsg("unnamed prepared statement does not exist")));
1686 * Report query to various monitoring facilities.
1688 debug_query_string = psrc->query_string;
1690 pgstat_report_activity(STATE_RUNNING, psrc->query_string);
1692 foreach(lc, psrc->query_list)
1694 Query *query = lfirst_node(Query, lc);
1696 if (query->queryId != UINT64CONST(0))
1698 pgstat_report_query_id(query->queryId, false);
1699 break;
1703 set_ps_display("BIND");
1705 if (save_log_statement_stats)
1706 ResetUsage();
1709 * Start up a transaction command so we can call functions etc. (Note that
1710 * this will normally change current memory context.) Nothing happens if
1711 * we are already in one. This also arms the statement timeout if
1712 * necessary.
1714 start_xact_command();
1716 /* Switch back to message context */
1717 MemoryContextSwitchTo(MessageContext);
1719 /* Get the parameter format codes */
1720 numPFormats = pq_getmsgint(input_message, 2);
1721 if (numPFormats > 0)
1723 pformats = palloc_array(int16, numPFormats);
1724 for (int i = 0; i < numPFormats; i++)
1725 pformats[i] = pq_getmsgint(input_message, 2);
1728 /* Get the parameter value count */
1729 numParams = pq_getmsgint(input_message, 2);
1731 if (numPFormats > 1 && numPFormats != numParams)
1732 ereport(ERROR,
1733 (errcode(ERRCODE_PROTOCOL_VIOLATION),
1734 errmsg("bind message has %d parameter formats but %d parameters",
1735 numPFormats, numParams)));
1737 if (numParams != psrc->num_params)
1738 ereport(ERROR,
1739 (errcode(ERRCODE_PROTOCOL_VIOLATION),
1740 errmsg("bind message supplies %d parameters, but prepared statement \"%s\" requires %d",
1741 numParams, stmt_name, psrc->num_params)));
1744 * If we are in aborted transaction state, the only portals we can
1745 * actually run are those containing COMMIT or ROLLBACK commands. We
1746 * disallow binding anything else to avoid problems with infrastructure
1747 * that expects to run inside a valid transaction. We also disallow
1748 * binding any parameters, since we can't risk calling user-defined I/O
1749 * functions.
1751 if (IsAbortedTransactionBlockState() &&
1752 (!(psrc->raw_parse_tree &&
1753 IsTransactionExitStmt(psrc->raw_parse_tree->stmt)) ||
1754 numParams != 0))
1755 ereport(ERROR,
1756 (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
1757 errmsg("current transaction is aborted, "
1758 "commands ignored until end of transaction block"),
1759 errdetail_abort()));
1762 * Create the portal. Allow silent replacement of an existing portal only
1763 * if the unnamed portal is specified.
1765 if (portal_name[0] == '\0')
1766 portal = CreatePortal(portal_name, true, true);
1767 else
1768 portal = CreatePortal(portal_name, false, false);
1771 * Prepare to copy stuff into the portal's memory context. We do all this
1772 * copying first, because it could possibly fail (out-of-memory) and we
1773 * don't want a failure to occur between GetCachedPlan and
1774 * PortalDefineQuery; that would result in leaking our plancache refcount.
1776 oldContext = MemoryContextSwitchTo(portal->portalContext);
1778 /* Copy the plan's query string into the portal */
1779 query_string = pstrdup(psrc->query_string);
1781 /* Likewise make a copy of the statement name, unless it's unnamed */
1782 if (stmt_name[0])
1783 saved_stmt_name = pstrdup(stmt_name);
1784 else
1785 saved_stmt_name = NULL;
1788 * Set a snapshot if we have parameters to fetch (since the input
1789 * functions might need it) or the query isn't a utility command (and
1790 * hence could require redoing parse analysis and planning). We keep the
1791 * snapshot active till we're done, so that plancache.c doesn't have to
1792 * take new ones.
1794 if (numParams > 0 ||
1795 (psrc->raw_parse_tree &&
1796 analyze_requires_snapshot(psrc->raw_parse_tree)))
1798 PushActiveSnapshot(GetTransactionSnapshot());
1799 snapshot_set = true;
1803 * Fetch parameters, if any, and store in the portal's memory context.
1805 if (numParams > 0)
1807 char **knownTextValues = NULL; /* allocate on first use */
1808 BindParamCbData one_param_data;
1811 * Set up an error callback so that if there's an error in this phase,
1812 * we can report the specific parameter causing the problem.
1814 one_param_data.portalName = portal->name;
1815 one_param_data.paramno = -1;
1816 one_param_data.paramval = NULL;
1817 params_errcxt.previous = error_context_stack;
1818 params_errcxt.callback = bind_param_error_callback;
1819 params_errcxt.arg = &one_param_data;
1820 error_context_stack = &params_errcxt;
1822 params = makeParamList(numParams);
1824 for (int paramno = 0; paramno < numParams; paramno++)
1826 Oid ptype = psrc->param_types[paramno];
1827 int32 plength;
1828 Datum pval;
1829 bool isNull;
1830 StringInfoData pbuf;
1831 char csave;
1832 int16 pformat;
1834 one_param_data.paramno = paramno;
1835 one_param_data.paramval = NULL;
1837 plength = pq_getmsgint(input_message, 4);
1838 isNull = (plength == -1);
1840 if (!isNull)
1842 char *pvalue;
1845 * Rather than copying data around, we just initialize a
1846 * StringInfo pointing to the correct portion of the message
1847 * buffer. We assume we can scribble on the message buffer to
1848 * add a trailing NUL which is required for the input function
1849 * call.
1851 pvalue = unconstify(char *, pq_getmsgbytes(input_message, plength));
1852 csave = pvalue[plength];
1853 pvalue[plength] = '\0';
1854 initReadOnlyStringInfo(&pbuf, pvalue, plength);
1856 else
1858 pbuf.data = NULL; /* keep compiler quiet */
1859 csave = 0;
1862 if (numPFormats > 1)
1863 pformat = pformats[paramno];
1864 else if (numPFormats > 0)
1865 pformat = pformats[0];
1866 else
1867 pformat = 0; /* default = text */
1869 if (pformat == 0) /* text mode */
1871 Oid typinput;
1872 Oid typioparam;
1873 char *pstring;
1875 getTypeInputInfo(ptype, &typinput, &typioparam);
1878 * We have to do encoding conversion before calling the
1879 * typinput routine.
1881 if (isNull)
1882 pstring = NULL;
1883 else
1884 pstring = pg_client_to_server(pbuf.data, plength);
1886 /* Now we can log the input string in case of error */
1887 one_param_data.paramval = pstring;
1889 pval = OidInputFunctionCall(typinput, pstring, typioparam, -1);
1891 one_param_data.paramval = NULL;
1894 * If we might need to log parameters later, save a copy of
1895 * the converted string in MessageContext; then free the
1896 * result of encoding conversion, if any was done.
1898 if (pstring)
1900 if (log_parameter_max_length_on_error != 0)
1902 MemoryContext oldcxt;
1904 oldcxt = MemoryContextSwitchTo(MessageContext);
1906 if (knownTextValues == NULL)
1907 knownTextValues = palloc0_array(char *, numParams);
1909 if (log_parameter_max_length_on_error < 0)
1910 knownTextValues[paramno] = pstrdup(pstring);
1911 else
1914 * We can trim the saved string, knowing that we
1915 * won't print all of it. But we must copy at
1916 * least two more full characters than
1917 * BuildParamLogString wants to use; otherwise it
1918 * might fail to include the trailing ellipsis.
1920 knownTextValues[paramno] =
1921 pnstrdup(pstring,
1922 log_parameter_max_length_on_error
1923 + 2 * MAX_MULTIBYTE_CHAR_LEN);
1926 MemoryContextSwitchTo(oldcxt);
1928 if (pstring != pbuf.data)
1929 pfree(pstring);
1932 else if (pformat == 1) /* binary mode */
1934 Oid typreceive;
1935 Oid typioparam;
1936 StringInfo bufptr;
1939 * Call the parameter type's binary input converter
1941 getTypeBinaryInputInfo(ptype, &typreceive, &typioparam);
1943 if (isNull)
1944 bufptr = NULL;
1945 else
1946 bufptr = &pbuf;
1948 pval = OidReceiveFunctionCall(typreceive, bufptr, typioparam, -1);
1950 /* Trouble if it didn't eat the whole buffer */
1951 if (!isNull && pbuf.cursor != pbuf.len)
1952 ereport(ERROR,
1953 (errcode(ERRCODE_INVALID_BINARY_REPRESENTATION),
1954 errmsg("incorrect binary data format in bind parameter %d",
1955 paramno + 1)));
1957 else
1959 ereport(ERROR,
1960 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1961 errmsg("unsupported format code: %d",
1962 pformat)));
1963 pval = 0; /* keep compiler quiet */
1966 /* Restore message buffer contents */
1967 if (!isNull)
1968 pbuf.data[plength] = csave;
1970 params->params[paramno].value = pval;
1971 params->params[paramno].isnull = isNull;
1974 * We mark the params as CONST. This ensures that any custom plan
1975 * makes full use of the parameter values.
1977 params->params[paramno].pflags = PARAM_FLAG_CONST;
1978 params->params[paramno].ptype = ptype;
1981 /* Pop the per-parameter error callback */
1982 error_context_stack = error_context_stack->previous;
1985 * Once all parameters have been received, prepare for printing them
1986 * in future errors, if configured to do so. (This is saved in the
1987 * portal, so that they'll appear when the query is executed later.)
1989 if (log_parameter_max_length_on_error != 0)
1990 params->paramValuesStr =
1991 BuildParamLogString(params,
1992 knownTextValues,
1993 log_parameter_max_length_on_error);
1995 else
1996 params = NULL;
1998 /* Done storing stuff in portal's context */
1999 MemoryContextSwitchTo(oldContext);
2002 * Set up another error callback so that all the parameters are logged if
2003 * we get an error during the rest of the BIND processing.
2005 params_data.portalName = portal->name;
2006 params_data.params = params;
2007 params_errcxt.previous = error_context_stack;
2008 params_errcxt.callback = ParamsErrorCallback;
2009 params_errcxt.arg = &params_data;
2010 error_context_stack = &params_errcxt;
2012 /* Get the result format codes */
2013 numRFormats = pq_getmsgint(input_message, 2);
2014 if (numRFormats > 0)
2016 rformats = palloc_array(int16, numRFormats);
2017 for (int i = 0; i < numRFormats; i++)
2018 rformats[i] = pq_getmsgint(input_message, 2);
2021 pq_getmsgend(input_message);
2024 * Obtain a plan from the CachedPlanSource. Any cruft from (re)planning
2025 * will be generated in MessageContext. The plan refcount will be
2026 * assigned to the Portal, so it will be released at portal destruction.
2028 cplan = GetCachedPlan(psrc, params, NULL, NULL);
2031 * Now we can define the portal.
2033 * DO NOT put any code that could possibly throw an error between the
2034 * above GetCachedPlan call and here.
2036 PortalDefineQuery(portal,
2037 saved_stmt_name,
2038 query_string,
2039 psrc->commandTag,
2040 cplan->stmt_list,
2041 cplan);
2043 /* Done with the snapshot used for parameter I/O and parsing/planning */
2044 if (snapshot_set)
2045 PopActiveSnapshot();
2048 * And we're ready to start portal execution.
2050 PortalStart(portal, params, 0, InvalidSnapshot);
2053 * Apply the result format requests to the portal.
2055 PortalSetResultFormat(portal, numRFormats, rformats);
2058 * Done binding; remove the parameters error callback. Entries emitted
2059 * later determine independently whether to log the parameters or not.
2061 error_context_stack = error_context_stack->previous;
2064 * Send BindComplete.
2066 if (whereToSendOutput == DestRemote)
2067 pq_putemptymessage(PqMsg_BindComplete);
2070 * Emit duration logging if appropriate.
2072 switch (check_log_duration(msec_str, false))
2074 case 1:
2075 ereport(LOG,
2076 (errmsg("duration: %s ms", msec_str),
2077 errhidestmt(true)));
2078 break;
2079 case 2:
2080 ereport(LOG,
2081 (errmsg("duration: %s ms bind %s%s%s: %s",
2082 msec_str,
2083 *stmt_name ? stmt_name : "<unnamed>",
2084 *portal_name ? "/" : "",
2085 *portal_name ? portal_name : "",
2086 psrc->query_string),
2087 errhidestmt(true),
2088 errdetail_params(params)));
2089 break;
2092 if (save_log_statement_stats)
2093 ShowUsage("BIND MESSAGE STATISTICS");
2095 valgrind_report_error_query(debug_query_string);
2097 debug_query_string = NULL;
2101 * exec_execute_message
2103 * Process an "Execute" message for a portal
2105 static void
2106 exec_execute_message(const char *portal_name, long max_rows)
2108 CommandDest dest;
2109 DestReceiver *receiver;
2110 Portal portal;
2111 bool completed;
2112 QueryCompletion qc;
2113 const char *sourceText;
2114 const char *prepStmtName;
2115 ParamListInfo portalParams;
2116 bool save_log_statement_stats = log_statement_stats;
2117 bool is_xact_command;
2118 bool execute_is_fetch;
2119 bool was_logged = false;
2120 char msec_str[32];
2121 ParamsErrorCbData params_data;
2122 ErrorContextCallback params_errcxt;
2123 const char *cmdtagname;
2124 size_t cmdtaglen;
2125 ListCell *lc;
2127 /* Adjust destination to tell printtup.c what to do */
2128 dest = whereToSendOutput;
2129 if (dest == DestRemote)
2130 dest = DestRemoteExecute;
2132 portal = GetPortalByName(portal_name);
2133 if (!PortalIsValid(portal))
2134 ereport(ERROR,
2135 (errcode(ERRCODE_UNDEFINED_CURSOR),
2136 errmsg("portal \"%s\" does not exist", portal_name)));
2139 * If the original query was a null string, just return
2140 * EmptyQueryResponse.
2142 if (portal->commandTag == CMDTAG_UNKNOWN)
2144 Assert(portal->stmts == NIL);
2145 NullCommand(dest);
2146 return;
2149 /* Does the portal contain a transaction command? */
2150 is_xact_command = IsTransactionStmtList(portal->stmts);
2153 * We must copy the sourceText and prepStmtName into MessageContext in
2154 * case the portal is destroyed during finish_xact_command. We do not
2155 * make a copy of the portalParams though, preferring to just not print
2156 * them in that case.
2158 sourceText = pstrdup(portal->sourceText);
2159 if (portal->prepStmtName)
2160 prepStmtName = pstrdup(portal->prepStmtName);
2161 else
2162 prepStmtName = "<unnamed>";
2163 portalParams = portal->portalParams;
2166 * Report query to various monitoring facilities.
2168 debug_query_string = sourceText;
2170 pgstat_report_activity(STATE_RUNNING, sourceText);
2172 foreach(lc, portal->stmts)
2174 PlannedStmt *stmt = lfirst_node(PlannedStmt, lc);
2176 if (stmt->queryId != UINT64CONST(0))
2178 pgstat_report_query_id(stmt->queryId, false);
2179 break;
2183 cmdtagname = GetCommandTagNameAndLen(portal->commandTag, &cmdtaglen);
2185 set_ps_display_with_len(cmdtagname, cmdtaglen);
2187 if (save_log_statement_stats)
2188 ResetUsage();
2190 BeginCommand(portal->commandTag, dest);
2193 * Create dest receiver in MessageContext (we don't want it in transaction
2194 * context, because that may get deleted if portal contains VACUUM).
2196 receiver = CreateDestReceiver(dest);
2197 if (dest == DestRemoteExecute)
2198 SetRemoteDestReceiverParams(receiver, portal);
2201 * Ensure we are in a transaction command (this should normally be the
2202 * case already due to prior BIND).
2204 start_xact_command();
2207 * If we re-issue an Execute protocol request against an existing portal,
2208 * then we are only fetching more rows rather than completely re-executing
2209 * the query from the start. atStart is never reset for a v3 portal, so we
2210 * are safe to use this check.
2212 execute_is_fetch = !portal->atStart;
2214 /* Log immediately if dictated by log_statement */
2215 if (check_log_statement(portal->stmts))
2217 ereport(LOG,
2218 (errmsg("%s %s%s%s: %s",
2219 execute_is_fetch ?
2220 _("execute fetch from") :
2221 _("execute"),
2222 prepStmtName,
2223 *portal_name ? "/" : "",
2224 *portal_name ? portal_name : "",
2225 sourceText),
2226 errhidestmt(true),
2227 errdetail_params(portalParams)));
2228 was_logged = true;
2232 * If we are in aborted transaction state, the only portals we can
2233 * actually run are those containing COMMIT or ROLLBACK commands.
2235 if (IsAbortedTransactionBlockState() &&
2236 !IsTransactionExitStmtList(portal->stmts))
2237 ereport(ERROR,
2238 (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
2239 errmsg("current transaction is aborted, "
2240 "commands ignored until end of transaction block"),
2241 errdetail_abort()));
2243 /* Check for cancel signal before we start execution */
2244 CHECK_FOR_INTERRUPTS();
2247 * Okay to run the portal. Set the error callback so that parameters are
2248 * logged. The parameters must have been saved during the bind phase.
2250 params_data.portalName = portal->name;
2251 params_data.params = portalParams;
2252 params_errcxt.previous = error_context_stack;
2253 params_errcxt.callback = ParamsErrorCallback;
2254 params_errcxt.arg = &params_data;
2255 error_context_stack = &params_errcxt;
2257 if (max_rows <= 0)
2258 max_rows = FETCH_ALL;
2260 completed = PortalRun(portal,
2261 max_rows,
2262 true, /* always top level */
2263 !execute_is_fetch && max_rows == FETCH_ALL,
2264 receiver,
2265 receiver,
2266 &qc);
2268 receiver->rDestroy(receiver);
2270 /* Done executing; remove the params error callback */
2271 error_context_stack = error_context_stack->previous;
2273 if (completed)
2275 if (is_xact_command || (MyXactFlags & XACT_FLAGS_NEEDIMMEDIATECOMMIT))
2278 * If this was a transaction control statement, commit it. We
2279 * will start a new xact command for the next command (if any).
2280 * Likewise if the statement required immediate commit. Without
2281 * this provision, we wouldn't force commit until Sync is
2282 * received, which creates a hazard if the client tries to
2283 * pipeline immediate-commit statements.
2285 finish_xact_command();
2288 * These commands typically don't have any parameters, and even if
2289 * one did we couldn't print them now because the storage went
2290 * away during finish_xact_command. So pretend there were none.
2292 portalParams = NULL;
2294 else
2297 * We need a CommandCounterIncrement after every query, except
2298 * those that start or end a transaction block.
2300 CommandCounterIncrement();
2303 * Set XACT_FLAGS_PIPELINING whenever we complete an Execute
2304 * message without immediately committing the transaction.
2306 MyXactFlags |= XACT_FLAGS_PIPELINING;
2309 * Disable statement timeout whenever we complete an Execute
2310 * message. The next protocol message will start a fresh timeout.
2312 disable_statement_timeout();
2315 /* Send appropriate CommandComplete to client */
2316 EndCommand(&qc, dest, false);
2318 else
2320 /* Portal run not complete, so send PortalSuspended */
2321 if (whereToSendOutput == DestRemote)
2322 pq_putemptymessage(PqMsg_PortalSuspended);
2325 * Set XACT_FLAGS_PIPELINING whenever we suspend an Execute message,
2326 * too.
2328 MyXactFlags |= XACT_FLAGS_PIPELINING;
2332 * Emit duration logging if appropriate.
2334 switch (check_log_duration(msec_str, was_logged))
2336 case 1:
2337 ereport(LOG,
2338 (errmsg("duration: %s ms", msec_str),
2339 errhidestmt(true)));
2340 break;
2341 case 2:
2342 ereport(LOG,
2343 (errmsg("duration: %s ms %s %s%s%s: %s",
2344 msec_str,
2345 execute_is_fetch ?
2346 _("execute fetch from") :
2347 _("execute"),
2348 prepStmtName,
2349 *portal_name ? "/" : "",
2350 *portal_name ? portal_name : "",
2351 sourceText),
2352 errhidestmt(true),
2353 errdetail_params(portalParams)));
2354 break;
2357 if (save_log_statement_stats)
2358 ShowUsage("EXECUTE MESSAGE STATISTICS");
2360 valgrind_report_error_query(debug_query_string);
2362 debug_query_string = NULL;
2366 * check_log_statement
2367 * Determine whether command should be logged because of log_statement
2369 * stmt_list can be either raw grammar output or a list of planned
2370 * statements
2372 static bool
2373 check_log_statement(List *stmt_list)
2375 ListCell *stmt_item;
2377 if (log_statement == LOGSTMT_NONE)
2378 return false;
2379 if (log_statement == LOGSTMT_ALL)
2380 return true;
2382 /* Else we have to inspect the statement(s) to see whether to log */
2383 foreach(stmt_item, stmt_list)
2385 Node *stmt = (Node *) lfirst(stmt_item);
2387 if (GetCommandLogLevel(stmt) <= log_statement)
2388 return true;
2391 return false;
2395 * check_log_duration
2396 * Determine whether current command's duration should be logged
2397 * We also check if this statement in this transaction must be logged
2398 * (regardless of its duration).
2400 * Returns:
2401 * 0 if no logging is needed
2402 * 1 if just the duration should be logged
2403 * 2 if duration and query details should be logged
2405 * If logging is needed, the duration in msec is formatted into msec_str[],
2406 * which must be a 32-byte buffer.
2408 * was_logged should be true if caller already logged query details (this
2409 * essentially prevents 2 from being returned).
2412 check_log_duration(char *msec_str, bool was_logged)
2414 if (log_duration || log_min_duration_sample >= 0 ||
2415 log_min_duration_statement >= 0 || xact_is_sampled)
2417 long secs;
2418 int usecs;
2419 int msecs;
2420 bool exceeded_duration;
2421 bool exceeded_sample_duration;
2422 bool in_sample = false;
2424 TimestampDifference(GetCurrentStatementStartTimestamp(),
2425 GetCurrentTimestamp(),
2426 &secs, &usecs);
2427 msecs = usecs / 1000;
2430 * This odd-looking test for log_min_duration_* being exceeded is
2431 * designed to avoid integer overflow with very long durations: don't
2432 * compute secs * 1000 until we've verified it will fit in int.
2434 exceeded_duration = (log_min_duration_statement == 0 ||
2435 (log_min_duration_statement > 0 &&
2436 (secs > log_min_duration_statement / 1000 ||
2437 secs * 1000 + msecs >= log_min_duration_statement)));
2439 exceeded_sample_duration = (log_min_duration_sample == 0 ||
2440 (log_min_duration_sample > 0 &&
2441 (secs > log_min_duration_sample / 1000 ||
2442 secs * 1000 + msecs >= log_min_duration_sample)));
2445 * Do not log if log_statement_sample_rate = 0. Log a sample if
2446 * log_statement_sample_rate <= 1 and avoid unnecessary PRNG call if
2447 * log_statement_sample_rate = 1.
2449 if (exceeded_sample_duration)
2450 in_sample = log_statement_sample_rate != 0 &&
2451 (log_statement_sample_rate == 1 ||
2452 pg_prng_double(&pg_global_prng_state) <= log_statement_sample_rate);
2454 if (exceeded_duration || in_sample || log_duration || xact_is_sampled)
2456 snprintf(msec_str, 32, "%ld.%03d",
2457 secs * 1000 + msecs, usecs % 1000);
2458 if ((exceeded_duration || in_sample || xact_is_sampled) && !was_logged)
2459 return 2;
2460 else
2461 return 1;
2465 return 0;
2469 * errdetail_execute
2471 * Add an errdetail() line showing the query referenced by an EXECUTE, if any.
2472 * The argument is the raw parsetree list.
2474 static int
2475 errdetail_execute(List *raw_parsetree_list)
2477 ListCell *parsetree_item;
2479 foreach(parsetree_item, raw_parsetree_list)
2481 RawStmt *parsetree = lfirst_node(RawStmt, parsetree_item);
2483 if (IsA(parsetree->stmt, ExecuteStmt))
2485 ExecuteStmt *stmt = (ExecuteStmt *) parsetree->stmt;
2486 PreparedStatement *pstmt;
2488 pstmt = FetchPreparedStatement(stmt->name, false);
2489 if (pstmt)
2491 errdetail("prepare: %s", pstmt->plansource->query_string);
2492 return 0;
2497 return 0;
2501 * errdetail_params
2503 * Add an errdetail() line showing bind-parameter data, if available.
2504 * Note that this is only used for statement logging, so it is controlled
2505 * by log_parameter_max_length not log_parameter_max_length_on_error.
2507 static int
2508 errdetail_params(ParamListInfo params)
2510 if (params && params->numParams > 0 && log_parameter_max_length != 0)
2512 char *str;
2514 str = BuildParamLogString(params, NULL, log_parameter_max_length);
2515 if (str && str[0] != '\0')
2516 errdetail("Parameters: %s", str);
2519 return 0;
2523 * errdetail_abort
2525 * Add an errdetail() line showing abort reason, if any.
2527 static int
2528 errdetail_abort(void)
2530 if (MyProc->recoveryConflictPending)
2531 errdetail("Abort reason: recovery conflict");
2533 return 0;
2537 * errdetail_recovery_conflict
2539 * Add an errdetail() line showing conflict source.
2541 static int
2542 errdetail_recovery_conflict(ProcSignalReason reason)
2544 switch (reason)
2546 case PROCSIG_RECOVERY_CONFLICT_BUFFERPIN:
2547 errdetail("User was holding shared buffer pin for too long.");
2548 break;
2549 case PROCSIG_RECOVERY_CONFLICT_LOCK:
2550 errdetail("User was holding a relation lock for too long.");
2551 break;
2552 case PROCSIG_RECOVERY_CONFLICT_TABLESPACE:
2553 errdetail("User was or might have been using tablespace that must be dropped.");
2554 break;
2555 case PROCSIG_RECOVERY_CONFLICT_SNAPSHOT:
2556 errdetail("User query might have needed to see row versions that must be removed.");
2557 break;
2558 case PROCSIG_RECOVERY_CONFLICT_LOGICALSLOT:
2559 errdetail("User was using a logical replication slot that must be invalidated.");
2560 break;
2561 case PROCSIG_RECOVERY_CONFLICT_STARTUP_DEADLOCK:
2562 errdetail("User transaction caused buffer deadlock with recovery.");
2563 break;
2564 case PROCSIG_RECOVERY_CONFLICT_DATABASE:
2565 errdetail("User was connected to a database that must be dropped.");
2566 break;
2567 default:
2568 break;
2569 /* no errdetail */
2572 return 0;
2576 * bind_param_error_callback
2578 * Error context callback used while parsing parameters in a Bind message
2580 static void
2581 bind_param_error_callback(void *arg)
2583 BindParamCbData *data = (BindParamCbData *) arg;
2584 StringInfoData buf;
2585 char *quotedval;
2587 if (data->paramno < 0)
2588 return;
2590 /* If we have a textual value, quote it, and trim if necessary */
2591 if (data->paramval)
2593 initStringInfo(&buf);
2594 appendStringInfoStringQuoted(&buf, data->paramval,
2595 log_parameter_max_length_on_error);
2596 quotedval = buf.data;
2598 else
2599 quotedval = NULL;
2601 if (data->portalName && data->portalName[0] != '\0')
2603 if (quotedval)
2604 errcontext("portal \"%s\" parameter $%d = %s",
2605 data->portalName, data->paramno + 1, quotedval);
2606 else
2607 errcontext("portal \"%s\" parameter $%d",
2608 data->portalName, data->paramno + 1);
2610 else
2612 if (quotedval)
2613 errcontext("unnamed portal parameter $%d = %s",
2614 data->paramno + 1, quotedval);
2615 else
2616 errcontext("unnamed portal parameter $%d",
2617 data->paramno + 1);
2620 if (quotedval)
2621 pfree(quotedval);
2625 * exec_describe_statement_message
2627 * Process a "Describe" message for a prepared statement
2629 static void
2630 exec_describe_statement_message(const char *stmt_name)
2632 CachedPlanSource *psrc;
2635 * Start up a transaction command. (Note that this will normally change
2636 * current memory context.) Nothing happens if we are already in one.
2638 start_xact_command();
2640 /* Switch back to message context */
2641 MemoryContextSwitchTo(MessageContext);
2643 /* Find prepared statement */
2644 if (stmt_name[0] != '\0')
2646 PreparedStatement *pstmt;
2648 pstmt = FetchPreparedStatement(stmt_name, true);
2649 psrc = pstmt->plansource;
2651 else
2653 /* special-case the unnamed statement */
2654 psrc = unnamed_stmt_psrc;
2655 if (!psrc)
2656 ereport(ERROR,
2657 (errcode(ERRCODE_UNDEFINED_PSTATEMENT),
2658 errmsg("unnamed prepared statement does not exist")));
2661 /* Prepared statements shouldn't have changeable result descs */
2662 Assert(psrc->fixed_result);
2665 * If we are in aborted transaction state, we can't run
2666 * SendRowDescriptionMessage(), because that needs catalog accesses.
2667 * Hence, refuse to Describe statements that return data. (We shouldn't
2668 * just refuse all Describes, since that might break the ability of some
2669 * clients to issue COMMIT or ROLLBACK commands, if they use code that
2670 * blindly Describes whatever it does.) We can Describe parameters
2671 * without doing anything dangerous, so we don't restrict that.
2673 if (IsAbortedTransactionBlockState() &&
2674 psrc->resultDesc)
2675 ereport(ERROR,
2676 (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
2677 errmsg("current transaction is aborted, "
2678 "commands ignored until end of transaction block"),
2679 errdetail_abort()));
2681 if (whereToSendOutput != DestRemote)
2682 return; /* can't actually do anything... */
2685 * First describe the parameters...
2687 pq_beginmessage_reuse(&row_description_buf, PqMsg_ParameterDescription);
2688 pq_sendint16(&row_description_buf, psrc->num_params);
2690 for (int i = 0; i < psrc->num_params; i++)
2692 Oid ptype = psrc->param_types[i];
2694 pq_sendint32(&row_description_buf, (int) ptype);
2696 pq_endmessage_reuse(&row_description_buf);
2699 * Next send RowDescription or NoData to describe the result...
2701 if (psrc->resultDesc)
2703 List *tlist;
2705 /* Get the plan's primary targetlist */
2706 tlist = CachedPlanGetTargetList(psrc, NULL);
2708 SendRowDescriptionMessage(&row_description_buf,
2709 psrc->resultDesc,
2710 tlist,
2711 NULL);
2713 else
2714 pq_putemptymessage(PqMsg_NoData);
2718 * exec_describe_portal_message
2720 * Process a "Describe" message for a portal
2722 static void
2723 exec_describe_portal_message(const char *portal_name)
2725 Portal portal;
2728 * Start up a transaction command. (Note that this will normally change
2729 * current memory context.) Nothing happens if we are already in one.
2731 start_xact_command();
2733 /* Switch back to message context */
2734 MemoryContextSwitchTo(MessageContext);
2736 portal = GetPortalByName(portal_name);
2737 if (!PortalIsValid(portal))
2738 ereport(ERROR,
2739 (errcode(ERRCODE_UNDEFINED_CURSOR),
2740 errmsg("portal \"%s\" does not exist", portal_name)));
2743 * If we are in aborted transaction state, we can't run
2744 * SendRowDescriptionMessage(), because that needs catalog accesses.
2745 * Hence, refuse to Describe portals that return data. (We shouldn't just
2746 * refuse all Describes, since that might break the ability of some
2747 * clients to issue COMMIT or ROLLBACK commands, if they use code that
2748 * blindly Describes whatever it does.)
2750 if (IsAbortedTransactionBlockState() &&
2751 portal->tupDesc)
2752 ereport(ERROR,
2753 (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
2754 errmsg("current transaction is aborted, "
2755 "commands ignored until end of transaction block"),
2756 errdetail_abort()));
2758 if (whereToSendOutput != DestRemote)
2759 return; /* can't actually do anything... */
2761 if (portal->tupDesc)
2762 SendRowDescriptionMessage(&row_description_buf,
2763 portal->tupDesc,
2764 FetchPortalTargetList(portal),
2765 portal->formats);
2766 else
2767 pq_putemptymessage(PqMsg_NoData);
2772 * Convenience routines for starting/committing a single command.
2774 static void
2775 start_xact_command(void)
2777 if (!xact_started)
2779 StartTransactionCommand();
2781 xact_started = true;
2783 else if (MyXactFlags & XACT_FLAGS_PIPELINING)
2786 * When the first Execute message is completed, following commands
2787 * will be done in an implicit transaction block created via
2788 * pipelining. The transaction state needs to be updated to an
2789 * implicit block if we're not already in a transaction block (like
2790 * one started by an explicit BEGIN).
2792 BeginImplicitTransactionBlock();
2796 * Start statement timeout if necessary. Note that this'll intentionally
2797 * not reset the clock on an already started timeout, to avoid the timing
2798 * overhead when start_xact_command() is invoked repeatedly, without an
2799 * interceding finish_xact_command() (e.g. parse/bind/execute). If that's
2800 * not desired, the timeout has to be disabled explicitly.
2802 enable_statement_timeout();
2804 /* Start timeout for checking if the client has gone away if necessary. */
2805 if (client_connection_check_interval > 0 &&
2806 IsUnderPostmaster &&
2807 MyProcPort &&
2808 !get_timeout_active(CLIENT_CONNECTION_CHECK_TIMEOUT))
2809 enable_timeout_after(CLIENT_CONNECTION_CHECK_TIMEOUT,
2810 client_connection_check_interval);
2813 static void
2814 finish_xact_command(void)
2816 /* cancel active statement timeout after each command */
2817 disable_statement_timeout();
2819 if (xact_started)
2821 CommitTransactionCommand();
2823 #ifdef MEMORY_CONTEXT_CHECKING
2824 /* Check all memory contexts that weren't freed during commit */
2825 /* (those that were, were checked before being deleted) */
2826 MemoryContextCheck(TopMemoryContext);
2827 #endif
2829 #ifdef SHOW_MEMORY_STATS
2830 /* Print mem stats after each commit for leak tracking */
2831 MemoryContextStats(TopMemoryContext);
2832 #endif
2834 xact_started = false;
2840 * Convenience routines for checking whether a statement is one of the
2841 * ones that we allow in transaction-aborted state.
2844 /* Test a bare parsetree */
2845 static bool
2846 IsTransactionExitStmt(Node *parsetree)
2848 if (parsetree && IsA(parsetree, TransactionStmt))
2850 TransactionStmt *stmt = (TransactionStmt *) parsetree;
2852 if (stmt->kind == TRANS_STMT_COMMIT ||
2853 stmt->kind == TRANS_STMT_PREPARE ||
2854 stmt->kind == TRANS_STMT_ROLLBACK ||
2855 stmt->kind == TRANS_STMT_ROLLBACK_TO)
2856 return true;
2858 return false;
2861 /* Test a list that contains PlannedStmt nodes */
2862 static bool
2863 IsTransactionExitStmtList(List *pstmts)
2865 if (list_length(pstmts) == 1)
2867 PlannedStmt *pstmt = linitial_node(PlannedStmt, pstmts);
2869 if (pstmt->commandType == CMD_UTILITY &&
2870 IsTransactionExitStmt(pstmt->utilityStmt))
2871 return true;
2873 return false;
2876 /* Test a list that contains PlannedStmt nodes */
2877 static bool
2878 IsTransactionStmtList(List *pstmts)
2880 if (list_length(pstmts) == 1)
2882 PlannedStmt *pstmt = linitial_node(PlannedStmt, pstmts);
2884 if (pstmt->commandType == CMD_UTILITY &&
2885 IsA(pstmt->utilityStmt, TransactionStmt))
2886 return true;
2888 return false;
2891 /* Release any existing unnamed prepared statement */
2892 static void
2893 drop_unnamed_stmt(void)
2895 /* paranoia to avoid a dangling pointer in case of error */
2896 if (unnamed_stmt_psrc)
2898 CachedPlanSource *psrc = unnamed_stmt_psrc;
2900 unnamed_stmt_psrc = NULL;
2901 DropCachedPlan(psrc);
2906 /* --------------------------------
2907 * signal handler routines used in PostgresMain()
2908 * --------------------------------
2912 * quickdie() occurs when signaled SIGQUIT by the postmaster.
2914 * Either some backend has bought the farm, or we've been told to shut down
2915 * "immediately"; so we need to stop what we're doing and exit.
2917 void
2918 quickdie(SIGNAL_ARGS)
2920 sigaddset(&BlockSig, SIGQUIT); /* prevent nested calls */
2921 sigprocmask(SIG_SETMASK, &BlockSig, NULL);
2924 * Prevent interrupts while exiting; though we just blocked signals that
2925 * would queue new interrupts, one may have been pending. We don't want a
2926 * quickdie() downgraded to a mere query cancel.
2928 HOLD_INTERRUPTS();
2931 * If we're aborting out of client auth, don't risk trying to send
2932 * anything to the client; we will likely violate the protocol, not to
2933 * mention that we may have interrupted the guts of OpenSSL or some
2934 * authentication library.
2936 if (ClientAuthInProgress && whereToSendOutput == DestRemote)
2937 whereToSendOutput = DestNone;
2940 * Notify the client before exiting, to give a clue on what happened.
2942 * It's dubious to call ereport() from a signal handler. It is certainly
2943 * not async-signal safe. But it seems better to try, than to disconnect
2944 * abruptly and leave the client wondering what happened. It's remotely
2945 * possible that we crash or hang while trying to send the message, but
2946 * receiving a SIGQUIT is a sign that something has already gone badly
2947 * wrong, so there's not much to lose. Assuming the postmaster is still
2948 * running, it will SIGKILL us soon if we get stuck for some reason.
2950 * One thing we can do to make this a tad safer is to clear the error
2951 * context stack, so that context callbacks are not called. That's a lot
2952 * less code that could be reached here, and the context info is unlikely
2953 * to be very relevant to a SIGQUIT report anyway.
2955 error_context_stack = NULL;
2958 * When responding to a postmaster-issued signal, we send the message only
2959 * to the client; sending to the server log just creates log spam, plus
2960 * it's more code that we need to hope will work in a signal handler.
2962 * Ideally these should be ereport(FATAL), but then we'd not get control
2963 * back to force the correct type of process exit.
2965 switch (GetQuitSignalReason())
2967 case PMQUIT_NOT_SENT:
2968 /* Hmm, SIGQUIT arrived out of the blue */
2969 ereport(WARNING,
2970 (errcode(ERRCODE_ADMIN_SHUTDOWN),
2971 errmsg("terminating connection because of unexpected SIGQUIT signal")));
2972 break;
2973 case PMQUIT_FOR_CRASH:
2974 /* A crash-and-restart cycle is in progress */
2975 ereport(WARNING_CLIENT_ONLY,
2976 (errcode(ERRCODE_CRASH_SHUTDOWN),
2977 errmsg("terminating connection because of crash of another server process"),
2978 errdetail("The postmaster has commanded this server process to roll back"
2979 " the current transaction and exit, because another"
2980 " server process exited abnormally and possibly corrupted"
2981 " shared memory."),
2982 errhint("In a moment you should be able to reconnect to the"
2983 " database and repeat your command.")));
2984 break;
2985 case PMQUIT_FOR_STOP:
2986 /* Immediate-mode stop */
2987 ereport(WARNING_CLIENT_ONLY,
2988 (errcode(ERRCODE_ADMIN_SHUTDOWN),
2989 errmsg("terminating connection due to immediate shutdown command")));
2990 break;
2994 * We DO NOT want to run proc_exit() or atexit() callbacks -- we're here
2995 * because shared memory may be corrupted, so we don't want to try to
2996 * clean up our transaction. Just nail the windows shut and get out of
2997 * town. The callbacks wouldn't be safe to run from a signal handler,
2998 * anyway.
3000 * Note we do _exit(2) not _exit(0). This is to force the postmaster into
3001 * a system reset cycle if someone sends a manual SIGQUIT to a random
3002 * backend. This is necessary precisely because we don't clean up our
3003 * shared memory state. (The "dead man switch" mechanism in pmsignal.c
3004 * should ensure the postmaster sees this as a crash, too, but no harm in
3005 * being doubly sure.)
3007 _exit(2);
3011 * Shutdown signal from postmaster: abort transaction and exit
3012 * at soonest convenient time
3014 void
3015 die(SIGNAL_ARGS)
3017 /* Don't joggle the elbow of proc_exit */
3018 if (!proc_exit_inprogress)
3020 InterruptPending = true;
3021 ProcDiePending = true;
3024 /* for the cumulative stats system */
3025 pgStatSessionEndCause = DISCONNECT_KILLED;
3027 /* If we're still here, waken anything waiting on the process latch */
3028 SetLatch(MyLatch);
3031 * If we're in single user mode, we want to quit immediately - we can't
3032 * rely on latches as they wouldn't work when stdin/stdout is a file.
3033 * Rather ugly, but it's unlikely to be worthwhile to invest much more
3034 * effort just for the benefit of single user mode.
3036 if (DoingCommandRead && whereToSendOutput != DestRemote)
3037 ProcessInterrupts();
3041 * Query-cancel signal from postmaster: abort current transaction
3042 * at soonest convenient time
3044 void
3045 StatementCancelHandler(SIGNAL_ARGS)
3048 * Don't joggle the elbow of proc_exit
3050 if (!proc_exit_inprogress)
3052 InterruptPending = true;
3053 QueryCancelPending = true;
3056 /* If we're still here, waken anything waiting on the process latch */
3057 SetLatch(MyLatch);
3060 /* signal handler for floating point exception */
3061 void
3062 FloatExceptionHandler(SIGNAL_ARGS)
3064 /* We're not returning, so no need to save errno */
3065 ereport(ERROR,
3066 (errcode(ERRCODE_FLOATING_POINT_EXCEPTION),
3067 errmsg("floating-point exception"),
3068 errdetail("An invalid floating-point operation was signaled. "
3069 "This probably means an out-of-range result or an "
3070 "invalid operation, such as division by zero.")));
3074 * Tell the next CHECK_FOR_INTERRUPTS() to check for a particular type of
3075 * recovery conflict. Runs in a SIGUSR1 handler.
3077 void
3078 HandleRecoveryConflictInterrupt(ProcSignalReason reason)
3080 RecoveryConflictPendingReasons[reason] = true;
3081 RecoveryConflictPending = true;
3082 InterruptPending = true;
3083 /* latch will be set by procsignal_sigusr1_handler */
3087 * Check one individual conflict reason.
3089 static void
3090 ProcessRecoveryConflictInterrupt(ProcSignalReason reason)
3092 switch (reason)
3094 case PROCSIG_RECOVERY_CONFLICT_STARTUP_DEADLOCK:
3097 * If we aren't waiting for a lock we can never deadlock.
3099 if (GetAwaitedLock() == NULL)
3100 return;
3102 /* Intentional fall through to check wait for pin */
3103 /* FALLTHROUGH */
3105 case PROCSIG_RECOVERY_CONFLICT_BUFFERPIN:
3108 * If PROCSIG_RECOVERY_CONFLICT_BUFFERPIN is requested but we
3109 * aren't blocking the Startup process there is nothing more to
3110 * do.
3112 * When PROCSIG_RECOVERY_CONFLICT_STARTUP_DEADLOCK is requested,
3113 * if we're waiting for locks and the startup process is not
3114 * waiting for buffer pin (i.e., also waiting for locks), we set
3115 * the flag so that ProcSleep() will check for deadlocks.
3117 if (!HoldingBufferPinThatDelaysRecovery())
3119 if (reason == PROCSIG_RECOVERY_CONFLICT_STARTUP_DEADLOCK &&
3120 GetStartupBufferPinWaitBufId() < 0)
3121 CheckDeadLockAlert();
3122 return;
3125 MyProc->recoveryConflictPending = true;
3127 /* Intentional fall through to error handling */
3128 /* FALLTHROUGH */
3130 case PROCSIG_RECOVERY_CONFLICT_LOCK:
3131 case PROCSIG_RECOVERY_CONFLICT_TABLESPACE:
3132 case PROCSIG_RECOVERY_CONFLICT_SNAPSHOT:
3135 * If we aren't in a transaction any longer then ignore.
3137 if (!IsTransactionOrTransactionBlock())
3138 return;
3140 /* FALLTHROUGH */
3142 case PROCSIG_RECOVERY_CONFLICT_LOGICALSLOT:
3145 * If we're not in a subtransaction then we are OK to throw an
3146 * ERROR to resolve the conflict. Otherwise drop through to the
3147 * FATAL case.
3149 * PROCSIG_RECOVERY_CONFLICT_LOGICALSLOT is a special case that
3150 * always throws an ERROR (ie never promotes to FATAL), though it
3151 * still has to respect QueryCancelHoldoffCount, so it shares this
3152 * code path. Logical decoding slots are only acquired while
3153 * performing logical decoding. During logical decoding no user
3154 * controlled code is run. During [sub]transaction abort, the
3155 * slot is released. Therefore user controlled code cannot
3156 * intercept an error before the replication slot is released.
3158 * XXX other times that we can throw just an ERROR *may* be
3159 * PROCSIG_RECOVERY_CONFLICT_LOCK if no locks are held in parent
3160 * transactions
3162 * PROCSIG_RECOVERY_CONFLICT_SNAPSHOT if no snapshots are held by
3163 * parent transactions and the transaction is not
3164 * transaction-snapshot mode
3166 * PROCSIG_RECOVERY_CONFLICT_TABLESPACE if no temp files or
3167 * cursors open in parent transactions
3169 if (reason == PROCSIG_RECOVERY_CONFLICT_LOGICALSLOT ||
3170 !IsSubTransaction())
3173 * If we already aborted then we no longer need to cancel. We
3174 * do this here since we do not wish to ignore aborted
3175 * subtransactions, which must cause FATAL, currently.
3177 if (IsAbortedTransactionBlockState())
3178 return;
3181 * If a recovery conflict happens while we are waiting for
3182 * input from the client, the client is presumably just
3183 * sitting idle in a transaction, preventing recovery from
3184 * making progress. We'll drop through to the FATAL case
3185 * below to dislodge it, in that case.
3187 if (!DoingCommandRead)
3189 /* Avoid losing sync in the FE/BE protocol. */
3190 if (QueryCancelHoldoffCount != 0)
3193 * Re-arm and defer this interrupt until later. See
3194 * similar code in ProcessInterrupts().
3196 RecoveryConflictPendingReasons[reason] = true;
3197 RecoveryConflictPending = true;
3198 InterruptPending = true;
3199 return;
3203 * We are cleared to throw an ERROR. Either it's the
3204 * logical slot case, or we have a top-level transaction
3205 * that we can abort and a conflict that isn't inherently
3206 * non-retryable.
3208 LockErrorCleanup();
3209 pgstat_report_recovery_conflict(reason);
3210 ereport(ERROR,
3211 (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
3212 errmsg("canceling statement due to conflict with recovery"),
3213 errdetail_recovery_conflict(reason)));
3214 break;
3218 /* Intentional fall through to session cancel */
3219 /* FALLTHROUGH */
3221 case PROCSIG_RECOVERY_CONFLICT_DATABASE:
3224 * Retrying is not possible because the database is dropped, or we
3225 * decided above that we couldn't resolve the conflict with an
3226 * ERROR and fell through. Terminate the session.
3228 pgstat_report_recovery_conflict(reason);
3229 ereport(FATAL,
3230 (errcode(reason == PROCSIG_RECOVERY_CONFLICT_DATABASE ?
3231 ERRCODE_DATABASE_DROPPED :
3232 ERRCODE_T_R_SERIALIZATION_FAILURE),
3233 errmsg("terminating connection due to conflict with recovery"),
3234 errdetail_recovery_conflict(reason),
3235 errhint("In a moment you should be able to reconnect to the"
3236 " database and repeat your command.")));
3237 break;
3239 default:
3240 elog(FATAL, "unrecognized conflict mode: %d", (int) reason);
3245 * Check each possible recovery conflict reason.
3247 static void
3248 ProcessRecoveryConflictInterrupts(void)
3251 * We don't need to worry about joggling the elbow of proc_exit, because
3252 * proc_exit_prepare() holds interrupts, so ProcessInterrupts() won't call
3253 * us.
3255 Assert(!proc_exit_inprogress);
3256 Assert(InterruptHoldoffCount == 0);
3257 Assert(RecoveryConflictPending);
3259 RecoveryConflictPending = false;
3261 for (ProcSignalReason reason = PROCSIG_RECOVERY_CONFLICT_FIRST;
3262 reason <= PROCSIG_RECOVERY_CONFLICT_LAST;
3263 reason++)
3265 if (RecoveryConflictPendingReasons[reason])
3267 RecoveryConflictPendingReasons[reason] = false;
3268 ProcessRecoveryConflictInterrupt(reason);
3274 * ProcessInterrupts: out-of-line portion of CHECK_FOR_INTERRUPTS() macro
3276 * If an interrupt condition is pending, and it's safe to service it,
3277 * then clear the flag and accept the interrupt. Called only when
3278 * InterruptPending is true.
3280 * Note: if INTERRUPTS_CAN_BE_PROCESSED() is true, then ProcessInterrupts
3281 * is guaranteed to clear the InterruptPending flag before returning.
3282 * (This is not the same as guaranteeing that it's still clear when we
3283 * return; another interrupt could have arrived. But we promise that
3284 * any pre-existing one will have been serviced.)
3286 void
3287 ProcessInterrupts(void)
3289 /* OK to accept any interrupts now? */
3290 if (InterruptHoldoffCount != 0 || CritSectionCount != 0)
3291 return;
3292 InterruptPending = false;
3294 if (ProcDiePending)
3296 ProcDiePending = false;
3297 QueryCancelPending = false; /* ProcDie trumps QueryCancel */
3298 LockErrorCleanup();
3299 /* As in quickdie, don't risk sending to client during auth */
3300 if (ClientAuthInProgress && whereToSendOutput == DestRemote)
3301 whereToSendOutput = DestNone;
3302 if (ClientAuthInProgress)
3303 ereport(FATAL,
3304 (errcode(ERRCODE_QUERY_CANCELED),
3305 errmsg("canceling authentication due to timeout")));
3306 else if (AmAutoVacuumWorkerProcess())
3307 ereport(FATAL,
3308 (errcode(ERRCODE_ADMIN_SHUTDOWN),
3309 errmsg("terminating autovacuum process due to administrator command")));
3310 else if (IsLogicalWorker())
3311 ereport(FATAL,
3312 (errcode(ERRCODE_ADMIN_SHUTDOWN),
3313 errmsg("terminating logical replication worker due to administrator command")));
3314 else if (IsLogicalLauncher())
3316 ereport(DEBUG1,
3317 (errmsg_internal("logical replication launcher shutting down")));
3320 * The logical replication launcher can be stopped at any time.
3321 * Use exit status 1 so the background worker is restarted.
3323 proc_exit(1);
3325 else if (AmBackgroundWorkerProcess())
3326 ereport(FATAL,
3327 (errcode(ERRCODE_ADMIN_SHUTDOWN),
3328 errmsg("terminating background worker \"%s\" due to administrator command",
3329 MyBgworkerEntry->bgw_type)));
3330 else
3331 ereport(FATAL,
3332 (errcode(ERRCODE_ADMIN_SHUTDOWN),
3333 errmsg("terminating connection due to administrator command")));
3336 if (CheckClientConnectionPending)
3338 CheckClientConnectionPending = false;
3341 * Check for lost connection and re-arm, if still configured, but not
3342 * if we've arrived back at DoingCommandRead state. We don't want to
3343 * wake up idle sessions, and they already know how to detect lost
3344 * connections.
3346 if (!DoingCommandRead && client_connection_check_interval > 0)
3348 if (!pq_check_connection())
3349 ClientConnectionLost = true;
3350 else
3351 enable_timeout_after(CLIENT_CONNECTION_CHECK_TIMEOUT,
3352 client_connection_check_interval);
3356 if (ClientConnectionLost)
3358 QueryCancelPending = false; /* lost connection trumps QueryCancel */
3359 LockErrorCleanup();
3360 /* don't send to client, we already know the connection to be dead. */
3361 whereToSendOutput = DestNone;
3362 ereport(FATAL,
3363 (errcode(ERRCODE_CONNECTION_FAILURE),
3364 errmsg("connection to client lost")));
3368 * Don't allow query cancel interrupts while reading input from the
3369 * client, because we might lose sync in the FE/BE protocol. (Die
3370 * interrupts are OK, because we won't read any further messages from the
3371 * client in that case.)
3373 * See similar logic in ProcessRecoveryConflictInterrupts().
3375 if (QueryCancelPending && QueryCancelHoldoffCount != 0)
3378 * Re-arm InterruptPending so that we process the cancel request as
3379 * soon as we're done reading the message. (XXX this is seriously
3380 * ugly: it complicates INTERRUPTS_CAN_BE_PROCESSED(), and it means we
3381 * can't use that macro directly as the initial test in this function,
3382 * meaning that this code also creates opportunities for other bugs to
3383 * appear.)
3385 InterruptPending = true;
3387 else if (QueryCancelPending)
3389 bool lock_timeout_occurred;
3390 bool stmt_timeout_occurred;
3392 QueryCancelPending = false;
3395 * If LOCK_TIMEOUT and STATEMENT_TIMEOUT indicators are both set, we
3396 * need to clear both, so always fetch both.
3398 lock_timeout_occurred = get_timeout_indicator(LOCK_TIMEOUT, true);
3399 stmt_timeout_occurred = get_timeout_indicator(STATEMENT_TIMEOUT, true);
3402 * If both were set, we want to report whichever timeout completed
3403 * earlier; this ensures consistent behavior if the machine is slow
3404 * enough that the second timeout triggers before we get here. A tie
3405 * is arbitrarily broken in favor of reporting a lock timeout.
3407 if (lock_timeout_occurred && stmt_timeout_occurred &&
3408 get_timeout_finish_time(STATEMENT_TIMEOUT) < get_timeout_finish_time(LOCK_TIMEOUT))
3409 lock_timeout_occurred = false; /* report stmt timeout */
3411 if (lock_timeout_occurred)
3413 LockErrorCleanup();
3414 ereport(ERROR,
3415 (errcode(ERRCODE_LOCK_NOT_AVAILABLE),
3416 errmsg("canceling statement due to lock timeout")));
3418 if (stmt_timeout_occurred)
3420 LockErrorCleanup();
3421 ereport(ERROR,
3422 (errcode(ERRCODE_QUERY_CANCELED),
3423 errmsg("canceling statement due to statement timeout")));
3425 if (AmAutoVacuumWorkerProcess())
3427 LockErrorCleanup();
3428 ereport(ERROR,
3429 (errcode(ERRCODE_QUERY_CANCELED),
3430 errmsg("canceling autovacuum task")));
3434 * If we are reading a command from the client, just ignore the cancel
3435 * request --- sending an extra error message won't accomplish
3436 * anything. Otherwise, go ahead and throw the error.
3438 if (!DoingCommandRead)
3440 LockErrorCleanup();
3441 ereport(ERROR,
3442 (errcode(ERRCODE_QUERY_CANCELED),
3443 errmsg("canceling statement due to user request")));
3447 if (RecoveryConflictPending)
3448 ProcessRecoveryConflictInterrupts();
3450 if (IdleInTransactionSessionTimeoutPending)
3453 * If the GUC has been reset to zero, ignore the signal. This is
3454 * important because the GUC update itself won't disable any pending
3455 * interrupt. We need to unset the flag before the injection point,
3456 * otherwise we could loop in interrupts checking.
3458 IdleInTransactionSessionTimeoutPending = false;
3459 if (IdleInTransactionSessionTimeout > 0)
3461 INJECTION_POINT("idle-in-transaction-session-timeout");
3462 ereport(FATAL,
3463 (errcode(ERRCODE_IDLE_IN_TRANSACTION_SESSION_TIMEOUT),
3464 errmsg("terminating connection due to idle-in-transaction timeout")));
3468 if (TransactionTimeoutPending)
3470 /* As above, ignore the signal if the GUC has been reset to zero. */
3471 TransactionTimeoutPending = false;
3472 if (TransactionTimeout > 0)
3474 INJECTION_POINT("transaction-timeout");
3475 ereport(FATAL,
3476 (errcode(ERRCODE_TRANSACTION_TIMEOUT),
3477 errmsg("terminating connection due to transaction timeout")));
3481 if (IdleSessionTimeoutPending)
3483 /* As above, ignore the signal if the GUC has been reset to zero. */
3484 IdleSessionTimeoutPending = false;
3485 if (IdleSessionTimeout > 0)
3487 INJECTION_POINT("idle-session-timeout");
3488 ereport(FATAL,
3489 (errcode(ERRCODE_IDLE_SESSION_TIMEOUT),
3490 errmsg("terminating connection due to idle-session timeout")));
3495 * If there are pending stats updates and we currently are truly idle
3496 * (matching the conditions in PostgresMain(), report stats now.
3498 if (IdleStatsUpdateTimeoutPending &&
3499 DoingCommandRead && !IsTransactionOrTransactionBlock())
3501 IdleStatsUpdateTimeoutPending = false;
3502 pgstat_report_stat(true);
3505 if (ProcSignalBarrierPending)
3506 ProcessProcSignalBarrier();
3508 if (ParallelMessagePending)
3509 HandleParallelMessages();
3511 if (LogMemoryContextPending)
3512 ProcessLogMemoryContextInterrupt();
3514 if (ParallelApplyMessagePending)
3515 HandleParallelApplyMessages();
3519 * set_stack_base: set up reference point for stack depth checking
3521 * Returns the old reference point, if any.
3523 pg_stack_base_t
3524 set_stack_base(void)
3526 #ifndef HAVE__BUILTIN_FRAME_ADDRESS
3527 char stack_base;
3528 #endif
3529 pg_stack_base_t old;
3531 old = stack_base_ptr;
3534 * Set up reference point for stack depth checking. On recent gcc we use
3535 * __builtin_frame_address() to avoid a warning about storing a local
3536 * variable's address in a long-lived variable.
3538 #ifdef HAVE__BUILTIN_FRAME_ADDRESS
3539 stack_base_ptr = __builtin_frame_address(0);
3540 #else
3541 stack_base_ptr = &stack_base;
3542 #endif
3544 return old;
3548 * restore_stack_base: restore reference point for stack depth checking
3550 * This can be used after set_stack_base() to restore the old value. This
3551 * is currently only used in PL/Java. When PL/Java calls a backend function
3552 * from different thread, the thread's stack is at a different location than
3553 * the main thread's stack, so it sets the base pointer before the call, and
3554 * restores it afterwards.
3556 void
3557 restore_stack_base(pg_stack_base_t base)
3559 stack_base_ptr = base;
3563 * check_stack_depth/stack_is_too_deep: check for excessively deep recursion
3565 * This should be called someplace in any recursive routine that might possibly
3566 * recurse deep enough to overflow the stack. Most Unixen treat stack
3567 * overflow as an unrecoverable SIGSEGV, so we want to error out ourselves
3568 * before hitting the hardware limit.
3570 * check_stack_depth() just throws an error summarily. stack_is_too_deep()
3571 * can be used by code that wants to handle the error condition itself.
3573 void
3574 check_stack_depth(void)
3576 if (stack_is_too_deep())
3578 ereport(ERROR,
3579 (errcode(ERRCODE_STATEMENT_TOO_COMPLEX),
3580 errmsg("stack depth limit exceeded"),
3581 errhint("Increase the configuration parameter \"max_stack_depth\" (currently %dkB), "
3582 "after ensuring the platform's stack depth limit is adequate.",
3583 max_stack_depth)));
3587 bool
3588 stack_is_too_deep(void)
3590 char stack_top_loc;
3591 long stack_depth;
3594 * Compute distance from reference point to my local variables
3596 stack_depth = (long) (stack_base_ptr - &stack_top_loc);
3599 * Take abs value, since stacks grow up on some machines, down on others
3601 if (stack_depth < 0)
3602 stack_depth = -stack_depth;
3605 * Trouble?
3607 * The test on stack_base_ptr prevents us from erroring out if called
3608 * during process setup or in a non-backend process. Logically it should
3609 * be done first, but putting it here avoids wasting cycles during normal
3610 * cases.
3612 if (stack_depth > max_stack_depth_bytes &&
3613 stack_base_ptr != NULL)
3614 return true;
3616 return false;
3619 /* GUC check hook for max_stack_depth */
3620 bool
3621 check_max_stack_depth(int *newval, void **extra, GucSource source)
3623 long newval_bytes = *newval * 1024L;
3624 long stack_rlimit = get_stack_depth_rlimit();
3626 if (stack_rlimit > 0 && newval_bytes > stack_rlimit - STACK_DEPTH_SLOP)
3628 GUC_check_errdetail("\"max_stack_depth\" must not exceed %ldkB.",
3629 (stack_rlimit - STACK_DEPTH_SLOP) / 1024L);
3630 GUC_check_errhint("Increase the platform's stack depth limit via \"ulimit -s\" or local equivalent.");
3631 return false;
3633 return true;
3636 /* GUC assign hook for max_stack_depth */
3637 void
3638 assign_max_stack_depth(int newval, void *extra)
3640 long newval_bytes = newval * 1024L;
3642 max_stack_depth_bytes = newval_bytes;
3646 * GUC check_hook for client_connection_check_interval
3648 bool
3649 check_client_connection_check_interval(int *newval, void **extra, GucSource source)
3651 if (!WaitEventSetCanReportClosed() && *newval != 0)
3653 GUC_check_errdetail("\"client_connection_check_interval\" must be set to 0 on this platform.");
3654 return false;
3656 return true;
3660 * GUC check_hook for log_parser_stats, log_planner_stats, log_executor_stats
3662 * This function and check_log_stats interact to prevent their variables from
3663 * being set in a disallowed combination. This is a hack that doesn't really
3664 * work right; for example it might fail while applying pg_db_role_setting
3665 * values even though the final state would have been acceptable. However,
3666 * since these variables are legacy settings with little production usage,
3667 * we tolerate that.
3669 bool
3670 check_stage_log_stats(bool *newval, void **extra, GucSource source)
3672 if (*newval && log_statement_stats)
3674 GUC_check_errdetail("Cannot enable parameter when \"log_statement_stats\" is true.");
3675 return false;
3677 return true;
3681 * GUC check_hook for log_statement_stats
3683 bool
3684 check_log_stats(bool *newval, void **extra, GucSource source)
3686 if (*newval &&
3687 (log_parser_stats || log_planner_stats || log_executor_stats))
3689 GUC_check_errdetail("Cannot enable \"log_statement_stats\" when "
3690 "\"log_parser_stats\", \"log_planner_stats\", "
3691 "or \"log_executor_stats\" is true.");
3692 return false;
3694 return true;
3697 /* GUC assign hook for transaction_timeout */
3698 void
3699 assign_transaction_timeout(int newval, void *extra)
3701 if (IsTransactionState())
3704 * If transaction_timeout GUC has changed within the transaction block
3705 * enable or disable the timer correspondingly.
3707 if (newval > 0 && !get_timeout_active(TRANSACTION_TIMEOUT))
3708 enable_timeout_after(TRANSACTION_TIMEOUT, newval);
3709 else if (newval <= 0 && get_timeout_active(TRANSACTION_TIMEOUT))
3710 disable_timeout(TRANSACTION_TIMEOUT, false);
3715 * GUC check_hook for restrict_nonsystem_relation_kind
3717 bool
3718 check_restrict_nonsystem_relation_kind(char **newval, void **extra, GucSource source)
3720 char *rawstring;
3721 List *elemlist;
3722 ListCell *l;
3723 int flags = 0;
3725 /* Need a modifiable copy of string */
3726 rawstring = pstrdup(*newval);
3728 if (!SplitIdentifierString(rawstring, ',', &elemlist))
3730 /* syntax error in list */
3731 GUC_check_errdetail("List syntax is invalid.");
3732 pfree(rawstring);
3733 list_free(elemlist);
3734 return false;
3737 foreach(l, elemlist)
3739 char *tok = (char *) lfirst(l);
3741 if (pg_strcasecmp(tok, "view") == 0)
3742 flags |= RESTRICT_RELKIND_VIEW;
3743 else if (pg_strcasecmp(tok, "foreign-table") == 0)
3744 flags |= RESTRICT_RELKIND_FOREIGN_TABLE;
3745 else
3747 GUC_check_errdetail("Unrecognized key word: \"%s\".", tok);
3748 pfree(rawstring);
3749 list_free(elemlist);
3750 return false;
3754 pfree(rawstring);
3755 list_free(elemlist);
3757 /* Save the flags in *extra, for use by the assign function */
3758 *extra = guc_malloc(ERROR, sizeof(int));
3759 *((int *) *extra) = flags;
3761 return true;
3765 * GUC assign_hook for restrict_nonsystem_relation_kind
3767 void
3768 assign_restrict_nonsystem_relation_kind(const char *newval, void *extra)
3770 int *flags = (int *) extra;
3772 restrict_nonsystem_relation_kind = *flags;
3776 * set_debug_options --- apply "-d N" command line option
3778 * -d is not quite the same as setting log_min_messages because it enables
3779 * other output options.
3781 void
3782 set_debug_options(int debug_flag, GucContext context, GucSource source)
3784 if (debug_flag > 0)
3786 char debugstr[64];
3788 sprintf(debugstr, "debug%d", debug_flag);
3789 SetConfigOption("log_min_messages", debugstr, context, source);
3791 else
3792 SetConfigOption("log_min_messages", "notice", context, source);
3794 if (debug_flag >= 1 && context == PGC_POSTMASTER)
3796 SetConfigOption("log_connections", "true", context, source);
3797 SetConfigOption("log_disconnections", "true", context, source);
3799 if (debug_flag >= 2)
3800 SetConfigOption("log_statement", "all", context, source);
3801 if (debug_flag >= 3)
3802 SetConfigOption("debug_print_parse", "true", context, source);
3803 if (debug_flag >= 4)
3804 SetConfigOption("debug_print_plan", "true", context, source);
3805 if (debug_flag >= 5)
3806 SetConfigOption("debug_print_rewritten", "true", context, source);
3810 bool
3811 set_plan_disabling_options(const char *arg, GucContext context, GucSource source)
3813 const char *tmp = NULL;
3815 switch (arg[0])
3817 case 's': /* seqscan */
3818 tmp = "enable_seqscan";
3819 break;
3820 case 'i': /* indexscan */
3821 tmp = "enable_indexscan";
3822 break;
3823 case 'o': /* indexonlyscan */
3824 tmp = "enable_indexonlyscan";
3825 break;
3826 case 'b': /* bitmapscan */
3827 tmp = "enable_bitmapscan";
3828 break;
3829 case 't': /* tidscan */
3830 tmp = "enable_tidscan";
3831 break;
3832 case 'n': /* nestloop */
3833 tmp = "enable_nestloop";
3834 break;
3835 case 'm': /* mergejoin */
3836 tmp = "enable_mergejoin";
3837 break;
3838 case 'h': /* hashjoin */
3839 tmp = "enable_hashjoin";
3840 break;
3842 if (tmp)
3844 SetConfigOption(tmp, "false", context, source);
3845 return true;
3847 else
3848 return false;
3852 const char *
3853 get_stats_option_name(const char *arg)
3855 switch (arg[0])
3857 case 'p':
3858 if (optarg[1] == 'a') /* "parser" */
3859 return "log_parser_stats";
3860 else if (optarg[1] == 'l') /* "planner" */
3861 return "log_planner_stats";
3862 break;
3864 case 'e': /* "executor" */
3865 return "log_executor_stats";
3866 break;
3869 return NULL;
3873 /* ----------------------------------------------------------------
3874 * process_postgres_switches
3875 * Parse command line arguments for backends
3877 * This is called twice, once for the "secure" options coming from the
3878 * postmaster or command line, and once for the "insecure" options coming
3879 * from the client's startup packet. The latter have the same syntax but
3880 * may be restricted in what they can do.
3882 * argv[0] is ignored in either case (it's assumed to be the program name).
3884 * ctx is PGC_POSTMASTER for secure options, PGC_BACKEND for insecure options
3885 * coming from the client, or PGC_SU_BACKEND for insecure options coming from
3886 * a superuser client.
3888 * If a database name is present in the command line arguments, it's
3889 * returned into *dbname (this is allowed only if *dbname is initially NULL).
3890 * ----------------------------------------------------------------
3892 void
3893 process_postgres_switches(int argc, char *argv[], GucContext ctx,
3894 const char **dbname)
3896 bool secure = (ctx == PGC_POSTMASTER);
3897 int errs = 0;
3898 GucSource gucsource;
3899 int flag;
3901 if (secure)
3903 gucsource = PGC_S_ARGV; /* switches came from command line */
3905 /* Ignore the initial --single argument, if present */
3906 if (argc > 1 && strcmp(argv[1], "--single") == 0)
3908 argv++;
3909 argc--;
3912 else
3914 gucsource = PGC_S_CLIENT; /* switches came from client */
3917 #ifdef HAVE_INT_OPTERR
3920 * Turn this off because it's either printed to stderr and not the log
3921 * where we'd want it, or argv[0] is now "--single", which would make for
3922 * a weird error message. We print our own error message below.
3924 opterr = 0;
3925 #endif
3928 * Parse command-line options. CAUTION: keep this in sync with
3929 * postmaster/postmaster.c (the option sets should not conflict) and with
3930 * the common help() function in main/main.c.
3932 while ((flag = getopt(argc, argv, "B:bC:c:D:d:EeFf:h:ijk:lN:nOPp:r:S:sTt:v:W:-:")) != -1)
3934 switch (flag)
3936 case 'B':
3937 SetConfigOption("shared_buffers", optarg, ctx, gucsource);
3938 break;
3940 case 'b':
3941 /* Undocumented flag used for binary upgrades */
3942 if (secure)
3943 IsBinaryUpgrade = true;
3944 break;
3946 case 'C':
3947 /* ignored for consistency with the postmaster */
3948 break;
3950 case 'c':
3951 case '-':
3953 char *name,
3954 *value;
3956 ParseLongOption(optarg, &name, &value);
3957 if (!value)
3959 if (flag == '-')
3960 ereport(ERROR,
3961 (errcode(ERRCODE_SYNTAX_ERROR),
3962 errmsg("--%s requires a value",
3963 optarg)));
3964 else
3965 ereport(ERROR,
3966 (errcode(ERRCODE_SYNTAX_ERROR),
3967 errmsg("-c %s requires a value",
3968 optarg)));
3970 SetConfigOption(name, value, ctx, gucsource);
3971 pfree(name);
3972 pfree(value);
3973 break;
3976 case 'D':
3977 if (secure)
3978 userDoption = strdup(optarg);
3979 break;
3981 case 'd':
3982 set_debug_options(atoi(optarg), ctx, gucsource);
3983 break;
3985 case 'E':
3986 if (secure)
3987 EchoQuery = true;
3988 break;
3990 case 'e':
3991 SetConfigOption("datestyle", "euro", ctx, gucsource);
3992 break;
3994 case 'F':
3995 SetConfigOption("fsync", "false", ctx, gucsource);
3996 break;
3998 case 'f':
3999 if (!set_plan_disabling_options(optarg, ctx, gucsource))
4000 errs++;
4001 break;
4003 case 'h':
4004 SetConfigOption("listen_addresses", optarg, ctx, gucsource);
4005 break;
4007 case 'i':
4008 SetConfigOption("listen_addresses", "*", ctx, gucsource);
4009 break;
4011 case 'j':
4012 if (secure)
4013 UseSemiNewlineNewline = true;
4014 break;
4016 case 'k':
4017 SetConfigOption("unix_socket_directories", optarg, ctx, gucsource);
4018 break;
4020 case 'l':
4021 SetConfigOption("ssl", "true", ctx, gucsource);
4022 break;
4024 case 'N':
4025 SetConfigOption("max_connections", optarg, ctx, gucsource);
4026 break;
4028 case 'n':
4029 /* ignored for consistency with postmaster */
4030 break;
4032 case 'O':
4033 SetConfigOption("allow_system_table_mods", "true", ctx, gucsource);
4034 break;
4036 case 'P':
4037 SetConfigOption("ignore_system_indexes", "true", ctx, gucsource);
4038 break;
4040 case 'p':
4041 SetConfigOption("port", optarg, ctx, gucsource);
4042 break;
4044 case 'r':
4045 /* send output (stdout and stderr) to the given file */
4046 if (secure)
4047 strlcpy(OutputFileName, optarg, MAXPGPATH);
4048 break;
4050 case 'S':
4051 SetConfigOption("work_mem", optarg, ctx, gucsource);
4052 break;
4054 case 's':
4055 SetConfigOption("log_statement_stats", "true", ctx, gucsource);
4056 break;
4058 case 'T':
4059 /* ignored for consistency with the postmaster */
4060 break;
4062 case 't':
4064 const char *tmp = get_stats_option_name(optarg);
4066 if (tmp)
4067 SetConfigOption(tmp, "true", ctx, gucsource);
4068 else
4069 errs++;
4070 break;
4073 case 'v':
4076 * -v is no longer used in normal operation, since
4077 * FrontendProtocol is already set before we get here. We keep
4078 * the switch only for possible use in standalone operation,
4079 * in case we ever support using normal FE/BE protocol with a
4080 * standalone backend.
4082 if (secure)
4083 FrontendProtocol = (ProtocolVersion) atoi(optarg);
4084 break;
4086 case 'W':
4087 SetConfigOption("post_auth_delay", optarg, ctx, gucsource);
4088 break;
4090 default:
4091 errs++;
4092 break;
4095 if (errs)
4096 break;
4100 * Optional database name should be there only if *dbname is NULL.
4102 if (!errs && dbname && *dbname == NULL && argc - optind >= 1)
4103 *dbname = strdup(argv[optind++]);
4105 if (errs || argc != optind)
4107 if (errs)
4108 optind--; /* complain about the previous argument */
4110 /* spell the error message a bit differently depending on context */
4111 if (IsUnderPostmaster)
4112 ereport(FATAL,
4113 errcode(ERRCODE_SYNTAX_ERROR),
4114 errmsg("invalid command-line argument for server process: %s", argv[optind]),
4115 errhint("Try \"%s --help\" for more information.", progname));
4116 else
4117 ereport(FATAL,
4118 errcode(ERRCODE_SYNTAX_ERROR),
4119 errmsg("%s: invalid command-line argument: %s",
4120 progname, argv[optind]),
4121 errhint("Try \"%s --help\" for more information.", progname));
4125 * Reset getopt(3) library so that it will work correctly in subprocesses
4126 * or when this function is called a second time with another array.
4128 optind = 1;
4129 #ifdef HAVE_INT_OPTRESET
4130 optreset = 1; /* some systems need this too */
4131 #endif
4136 * PostgresSingleUserMain
4137 * Entry point for single user mode. argc/argv are the command line
4138 * arguments to be used.
4140 * Performs single user specific setup then calls PostgresMain() to actually
4141 * process queries. Single user mode specific setup should go here, rather
4142 * than PostgresMain() or InitPostgres() when reasonably possible.
4144 void
4145 PostgresSingleUserMain(int argc, char *argv[],
4146 const char *username)
4148 const char *dbname = NULL;
4150 Assert(!IsUnderPostmaster);
4152 /* Initialize startup process environment. */
4153 InitStandaloneProcess(argv[0]);
4156 * Set default values for command-line options.
4158 InitializeGUCOptions();
4161 * Parse command-line options.
4163 process_postgres_switches(argc, argv, PGC_POSTMASTER, &dbname);
4165 /* Must have gotten a database name, or have a default (the username) */
4166 if (dbname == NULL)
4168 dbname = username;
4169 if (dbname == NULL)
4170 ereport(FATAL,
4171 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
4172 errmsg("%s: no database nor user name specified",
4173 progname)));
4176 /* Acquire configuration parameters */
4177 if (!SelectConfigFiles(userDoption, progname))
4178 proc_exit(1);
4181 * Validate we have been given a reasonable-looking DataDir and change
4182 * into it.
4184 checkDataDir();
4185 ChangeToDataDir();
4188 * Create lockfile for data directory.
4190 CreateDataDirLockFile(false);
4192 /* read control file (error checking and contains config ) */
4193 LocalProcessControlFile(false);
4196 * process any libraries that should be preloaded at postmaster start
4198 process_shared_preload_libraries();
4200 /* Initialize MaxBackends */
4201 InitializeMaxBackends();
4204 * We don't need postmaster child slots in single-user mode, but
4205 * initialize them anyway to avoid having special handling.
4207 InitPostmasterChildSlots();
4209 /* Initialize size of fast-path lock cache. */
4210 InitializeFastPathLocks();
4213 * Give preloaded libraries a chance to request additional shared memory.
4215 process_shmem_requests();
4218 * Now that loadable modules have had their chance to request additional
4219 * shared memory, determine the value of any runtime-computed GUCs that
4220 * depend on the amount of shared memory required.
4222 InitializeShmemGUCs();
4225 * Now that modules have been loaded, we can process any custom resource
4226 * managers specified in the wal_consistency_checking GUC.
4228 InitializeWalConsistencyChecking();
4230 CreateSharedMemoryAndSemaphores();
4233 * Remember stand-alone backend startup time,roughly at the same point
4234 * during startup that postmaster does so.
4236 PgStartTime = GetCurrentTimestamp();
4239 * Create a per-backend PGPROC struct in shared memory. We must do this
4240 * before we can use LWLocks.
4242 InitProcess();
4245 * Now that sufficient infrastructure has been initialized, PostgresMain()
4246 * can do the rest.
4248 PostgresMain(dbname, username);
4252 /* ----------------------------------------------------------------
4253 * PostgresMain
4254 * postgres main loop -- all backends, interactive or otherwise loop here
4256 * dbname is the name of the database to connect to, username is the
4257 * PostgreSQL user name to be used for the session.
4259 * NB: Single user mode specific setup should go to PostgresSingleUserMain()
4260 * if reasonably possible.
4261 * ----------------------------------------------------------------
4263 void
4264 PostgresMain(const char *dbname, const char *username)
4266 sigjmp_buf local_sigjmp_buf;
4268 /* these must be volatile to ensure state is preserved across longjmp: */
4269 volatile bool send_ready_for_query = true;
4270 volatile bool idle_in_transaction_timeout_enabled = false;
4271 volatile bool idle_session_timeout_enabled = false;
4273 Assert(dbname != NULL);
4274 Assert(username != NULL);
4276 Assert(GetProcessingMode() == InitProcessing);
4279 * Set up signal handlers. (InitPostmasterChild or InitStandaloneProcess
4280 * has already set up BlockSig and made that the active signal mask.)
4282 * Note that postmaster blocked all signals before forking child process,
4283 * so there is no race condition whereby we might receive a signal before
4284 * we have set up the handler.
4286 * Also note: it's best not to use any signals that are SIG_IGNored in the
4287 * postmaster. If such a signal arrives before we are able to change the
4288 * handler to non-SIG_IGN, it'll get dropped. Instead, make a dummy
4289 * handler in the postmaster to reserve the signal. (Of course, this isn't
4290 * an issue for signals that are locally generated, such as SIGALRM and
4291 * SIGPIPE.)
4293 if (am_walsender)
4294 WalSndSignals();
4295 else
4297 pqsignal(SIGHUP, SignalHandlerForConfigReload);
4298 pqsignal(SIGINT, StatementCancelHandler); /* cancel current query */
4299 pqsignal(SIGTERM, die); /* cancel current query and exit */
4302 * In a postmaster child backend, replace SignalHandlerForCrashExit
4303 * with quickdie, so we can tell the client we're dying.
4305 * In a standalone backend, SIGQUIT can be generated from the keyboard
4306 * easily, while SIGTERM cannot, so we make both signals do die()
4307 * rather than quickdie().
4309 if (IsUnderPostmaster)
4310 pqsignal(SIGQUIT, quickdie); /* hard crash time */
4311 else
4312 pqsignal(SIGQUIT, die); /* cancel current query and exit */
4313 InitializeTimeouts(); /* establishes SIGALRM handler */
4316 * Ignore failure to write to frontend. Note: if frontend closes
4317 * connection, we will notice it and exit cleanly when control next
4318 * returns to outer loop. This seems safer than forcing exit in the
4319 * midst of output during who-knows-what operation...
4321 pqsignal(SIGPIPE, SIG_IGN);
4322 pqsignal(SIGUSR1, procsignal_sigusr1_handler);
4323 pqsignal(SIGUSR2, SIG_IGN);
4324 pqsignal(SIGFPE, FloatExceptionHandler);
4327 * Reset some signals that are accepted by postmaster but not by
4328 * backend
4330 pqsignal(SIGCHLD, SIG_DFL); /* system() requires this on some
4331 * platforms */
4334 /* Early initialization */
4335 BaseInit();
4337 /* We need to allow SIGINT, etc during the initial transaction */
4338 sigprocmask(SIG_SETMASK, &UnBlockSig, NULL);
4341 * Generate a random cancel key, if this is a backend serving a
4342 * connection. InitPostgres() will advertise it in shared memory.
4344 Assert(!MyCancelKeyValid);
4345 if (whereToSendOutput == DestRemote)
4347 if (!pg_strong_random(&MyCancelKey, sizeof(int32)))
4349 ereport(ERROR,
4350 (errcode(ERRCODE_INTERNAL_ERROR),
4351 errmsg("could not generate random cancel key")));
4353 MyCancelKeyValid = true;
4357 * General initialization.
4359 * NOTE: if you are tempted to add code in this vicinity, consider putting
4360 * it inside InitPostgres() instead. In particular, anything that
4361 * involves database access should be there, not here.
4363 * Honor session_preload_libraries if not dealing with a WAL sender.
4365 InitPostgres(dbname, InvalidOid, /* database to connect to */
4366 username, InvalidOid, /* role to connect as */
4367 (!am_walsender) ? INIT_PG_LOAD_SESSION_LIBS : 0,
4368 NULL); /* no out_dbname */
4371 * If the PostmasterContext is still around, recycle the space; we don't
4372 * need it anymore after InitPostgres completes.
4374 if (PostmasterContext)
4376 MemoryContextDelete(PostmasterContext);
4377 PostmasterContext = NULL;
4380 SetProcessingMode(NormalProcessing);
4383 * Now all GUC states are fully set up. Report them to client if
4384 * appropriate.
4386 BeginReportingGUCOptions();
4389 * Also set up handler to log session end; we have to wait till now to be
4390 * sure Log_disconnections has its final value.
4392 if (IsUnderPostmaster && Log_disconnections)
4393 on_proc_exit(log_disconnections, 0);
4395 pgstat_report_connect(MyDatabaseId);
4397 /* Perform initialization specific to a WAL sender process. */
4398 if (am_walsender)
4399 InitWalSender();
4402 * Send this backend's cancellation info to the frontend.
4404 if (whereToSendOutput == DestRemote)
4406 StringInfoData buf;
4408 Assert(MyCancelKeyValid);
4409 pq_beginmessage(&buf, PqMsg_BackendKeyData);
4410 pq_sendint32(&buf, (int32) MyProcPid);
4411 pq_sendint32(&buf, (int32) MyCancelKey);
4412 pq_endmessage(&buf);
4413 /* Need not flush since ReadyForQuery will do it. */
4416 /* Welcome banner for standalone case */
4417 if (whereToSendOutput == DestDebug)
4418 printf("\nPostgreSQL stand-alone backend %s\n", PG_VERSION);
4421 * Create the memory context we will use in the main loop.
4423 * MessageContext is reset once per iteration of the main loop, ie, upon
4424 * completion of processing of each command message from the client.
4426 MessageContext = AllocSetContextCreate(TopMemoryContext,
4427 "MessageContext",
4428 ALLOCSET_DEFAULT_SIZES);
4431 * Create memory context and buffer used for RowDescription messages. As
4432 * SendRowDescriptionMessage(), via exec_describe_statement_message(), is
4433 * frequently executed for ever single statement, we don't want to
4434 * allocate a separate buffer every time.
4436 row_description_context = AllocSetContextCreate(TopMemoryContext,
4437 "RowDescriptionContext",
4438 ALLOCSET_DEFAULT_SIZES);
4439 MemoryContextSwitchTo(row_description_context);
4440 initStringInfo(&row_description_buf);
4441 MemoryContextSwitchTo(TopMemoryContext);
4443 /* Fire any defined login event triggers, if appropriate */
4444 EventTriggerOnLogin();
4447 * POSTGRES main processing loop begins here
4449 * If an exception is encountered, processing resumes here so we abort the
4450 * current transaction and start a new one.
4452 * You might wonder why this isn't coded as an infinite loop around a
4453 * PG_TRY construct. The reason is that this is the bottom of the
4454 * exception stack, and so with PG_TRY there would be no exception handler
4455 * in force at all during the CATCH part. By leaving the outermost setjmp
4456 * always active, we have at least some chance of recovering from an error
4457 * during error recovery. (If we get into an infinite loop thereby, it
4458 * will soon be stopped by overflow of elog.c's internal state stack.)
4460 * Note that we use sigsetjmp(..., 1), so that this function's signal mask
4461 * (to wit, UnBlockSig) will be restored when longjmp'ing to here. This
4462 * is essential in case we longjmp'd out of a signal handler on a platform
4463 * where that leaves the signal blocked. It's not redundant with the
4464 * unblock in AbortTransaction() because the latter is only called if we
4465 * were inside a transaction.
4468 if (sigsetjmp(local_sigjmp_buf, 1) != 0)
4471 * NOTE: if you are tempted to add more code in this if-block,
4472 * consider the high probability that it should be in
4473 * AbortTransaction() instead. The only stuff done directly here
4474 * should be stuff that is guaranteed to apply *only* for outer-level
4475 * error recovery, such as adjusting the FE/BE protocol status.
4478 /* Since not using PG_TRY, must reset error stack by hand */
4479 error_context_stack = NULL;
4481 /* Prevent interrupts while cleaning up */
4482 HOLD_INTERRUPTS();
4485 * Forget any pending QueryCancel request, since we're returning to
4486 * the idle loop anyway, and cancel any active timeout requests. (In
4487 * future we might want to allow some timeout requests to survive, but
4488 * at minimum it'd be necessary to do reschedule_timeouts(), in case
4489 * we got here because of a query cancel interrupting the SIGALRM
4490 * interrupt handler.) Note in particular that we must clear the
4491 * statement and lock timeout indicators, to prevent any future plain
4492 * query cancels from being misreported as timeouts in case we're
4493 * forgetting a timeout cancel.
4495 disable_all_timeouts(false); /* do first to avoid race condition */
4496 QueryCancelPending = false;
4497 idle_in_transaction_timeout_enabled = false;
4498 idle_session_timeout_enabled = false;
4500 /* Not reading from the client anymore. */
4501 DoingCommandRead = false;
4503 /* Make sure libpq is in a good state */
4504 pq_comm_reset();
4506 /* Report the error to the client and/or server log */
4507 EmitErrorReport();
4510 * If Valgrind noticed something during the erroneous query, print the
4511 * query string, assuming we have one.
4513 valgrind_report_error_query(debug_query_string);
4516 * Make sure debug_query_string gets reset before we possibly clobber
4517 * the storage it points at.
4519 debug_query_string = NULL;
4522 * Abort the current transaction in order to recover.
4524 AbortCurrentTransaction();
4526 if (am_walsender)
4527 WalSndErrorCleanup();
4529 PortalErrorCleanup();
4532 * We can't release replication slots inside AbortTransaction() as we
4533 * need to be able to start and abort transactions while having a slot
4534 * acquired. But we never need to hold them across top level errors,
4535 * so releasing here is fine. There also is a before_shmem_exit()
4536 * callback ensuring correct cleanup on FATAL errors.
4538 if (MyReplicationSlot != NULL)
4539 ReplicationSlotRelease();
4541 /* We also want to cleanup temporary slots on error. */
4542 ReplicationSlotCleanup(false);
4544 jit_reset_after_error();
4547 * Now return to normal top-level context and clear ErrorContext for
4548 * next time.
4550 MemoryContextSwitchTo(MessageContext);
4551 FlushErrorState();
4554 * If we were handling an extended-query-protocol message, initiate
4555 * skip till next Sync. This also causes us not to issue
4556 * ReadyForQuery (until we get Sync).
4558 if (doing_extended_query_message)
4559 ignore_till_sync = true;
4561 /* We don't have a transaction command open anymore */
4562 xact_started = false;
4565 * If an error occurred while we were reading a message from the
4566 * client, we have potentially lost track of where the previous
4567 * message ends and the next one begins. Even though we have
4568 * otherwise recovered from the error, we cannot safely read any more
4569 * messages from the client, so there isn't much we can do with the
4570 * connection anymore.
4572 if (pq_is_reading_msg())
4573 ereport(FATAL,
4574 (errcode(ERRCODE_PROTOCOL_VIOLATION),
4575 errmsg("terminating connection because protocol synchronization was lost")));
4577 /* Now we can allow interrupts again */
4578 RESUME_INTERRUPTS();
4581 /* We can now handle ereport(ERROR) */
4582 PG_exception_stack = &local_sigjmp_buf;
4584 if (!ignore_till_sync)
4585 send_ready_for_query = true; /* initially, or after error */
4588 * Non-error queries loop here.
4591 for (;;)
4593 int firstchar;
4594 StringInfoData input_message;
4597 * At top of loop, reset extended-query-message flag, so that any
4598 * errors encountered in "idle" state don't provoke skip.
4600 doing_extended_query_message = false;
4603 * For valgrind reporting purposes, the "current query" begins here.
4605 #ifdef USE_VALGRIND
4606 old_valgrind_error_count = VALGRIND_COUNT_ERRORS;
4607 #endif
4610 * Release storage left over from prior query cycle, and create a new
4611 * query input buffer in the cleared MessageContext.
4613 MemoryContextSwitchTo(MessageContext);
4614 MemoryContextReset(MessageContext);
4616 initStringInfo(&input_message);
4619 * Also consider releasing our catalog snapshot if any, so that it's
4620 * not preventing advance of global xmin while we wait for the client.
4622 InvalidateCatalogSnapshotConditionally();
4625 * (1) If we've reached idle state, tell the frontend we're ready for
4626 * a new query.
4628 * Note: this includes fflush()'ing the last of the prior output.
4630 * This is also a good time to flush out collected statistics to the
4631 * cumulative stats system, and to update the PS stats display. We
4632 * avoid doing those every time through the message loop because it'd
4633 * slow down processing of batched messages, and because we don't want
4634 * to report uncommitted updates (that confuses autovacuum). The
4635 * notification processor wants a call too, if we are not in a
4636 * transaction block.
4638 * Also, if an idle timeout is enabled, start the timer for that.
4640 if (send_ready_for_query)
4642 if (IsAbortedTransactionBlockState())
4644 set_ps_display("idle in transaction (aborted)");
4645 pgstat_report_activity(STATE_IDLEINTRANSACTION_ABORTED, NULL);
4647 /* Start the idle-in-transaction timer */
4648 if (IdleInTransactionSessionTimeout > 0
4649 && (IdleInTransactionSessionTimeout < TransactionTimeout || TransactionTimeout == 0))
4651 idle_in_transaction_timeout_enabled = true;
4652 enable_timeout_after(IDLE_IN_TRANSACTION_SESSION_TIMEOUT,
4653 IdleInTransactionSessionTimeout);
4656 else if (IsTransactionOrTransactionBlock())
4658 set_ps_display("idle in transaction");
4659 pgstat_report_activity(STATE_IDLEINTRANSACTION, NULL);
4661 /* Start the idle-in-transaction timer */
4662 if (IdleInTransactionSessionTimeout > 0
4663 && (IdleInTransactionSessionTimeout < TransactionTimeout || TransactionTimeout == 0))
4665 idle_in_transaction_timeout_enabled = true;
4666 enable_timeout_after(IDLE_IN_TRANSACTION_SESSION_TIMEOUT,
4667 IdleInTransactionSessionTimeout);
4670 else
4672 long stats_timeout;
4675 * Process incoming notifies (including self-notifies), if
4676 * any, and send relevant messages to the client. Doing it
4677 * here helps ensure stable behavior in tests: if any notifies
4678 * were received during the just-finished transaction, they'll
4679 * be seen by the client before ReadyForQuery is.
4681 if (notifyInterruptPending)
4682 ProcessNotifyInterrupt(false);
4685 * Check if we need to report stats. If pgstat_report_stat()
4686 * decides it's too soon to flush out pending stats / lock
4687 * contention prevented reporting, it'll tell us when we
4688 * should try to report stats again (so that stats updates
4689 * aren't unduly delayed if the connection goes idle for a
4690 * long time). We only enable the timeout if we don't already
4691 * have a timeout in progress, because we don't disable the
4692 * timeout below. enable_timeout_after() needs to determine
4693 * the current timestamp, which can have a negative
4694 * performance impact. That's OK because pgstat_report_stat()
4695 * won't have us wake up sooner than a prior call.
4697 stats_timeout = pgstat_report_stat(false);
4698 if (stats_timeout > 0)
4700 if (!get_timeout_active(IDLE_STATS_UPDATE_TIMEOUT))
4701 enable_timeout_after(IDLE_STATS_UPDATE_TIMEOUT,
4702 stats_timeout);
4704 else
4706 /* all stats flushed, no need for the timeout */
4707 if (get_timeout_active(IDLE_STATS_UPDATE_TIMEOUT))
4708 disable_timeout(IDLE_STATS_UPDATE_TIMEOUT, false);
4711 set_ps_display("idle");
4712 pgstat_report_activity(STATE_IDLE, NULL);
4714 /* Start the idle-session timer */
4715 if (IdleSessionTimeout > 0)
4717 idle_session_timeout_enabled = true;
4718 enable_timeout_after(IDLE_SESSION_TIMEOUT,
4719 IdleSessionTimeout);
4723 /* Report any recently-changed GUC options */
4724 ReportChangedGUCOptions();
4726 ReadyForQuery(whereToSendOutput);
4727 send_ready_for_query = false;
4731 * (2) Allow asynchronous signals to be executed immediately if they
4732 * come in while we are waiting for client input. (This must be
4733 * conditional since we don't want, say, reads on behalf of COPY FROM
4734 * STDIN doing the same thing.)
4736 DoingCommandRead = true;
4739 * (3) read a command (loop blocks here)
4741 firstchar = ReadCommand(&input_message);
4744 * (4) turn off the idle-in-transaction and idle-session timeouts if
4745 * active. We do this before step (5) so that any last-moment timeout
4746 * is certain to be detected in step (5).
4748 * At most one of these timeouts will be active, so there's no need to
4749 * worry about combining the timeout.c calls into one.
4751 if (idle_in_transaction_timeout_enabled)
4753 disable_timeout(IDLE_IN_TRANSACTION_SESSION_TIMEOUT, false);
4754 idle_in_transaction_timeout_enabled = false;
4756 if (idle_session_timeout_enabled)
4758 disable_timeout(IDLE_SESSION_TIMEOUT, false);
4759 idle_session_timeout_enabled = false;
4763 * (5) disable async signal conditions again.
4765 * Query cancel is supposed to be a no-op when there is no query in
4766 * progress, so if a query cancel arrived while we were idle, just
4767 * reset QueryCancelPending. ProcessInterrupts() has that effect when
4768 * it's called when DoingCommandRead is set, so check for interrupts
4769 * before resetting DoingCommandRead.
4771 CHECK_FOR_INTERRUPTS();
4772 DoingCommandRead = false;
4775 * (6) check for any other interesting events that happened while we
4776 * slept.
4778 if (ConfigReloadPending)
4780 ConfigReloadPending = false;
4781 ProcessConfigFile(PGC_SIGHUP);
4785 * (7) process the command. But ignore it if we're skipping till
4786 * Sync.
4788 if (ignore_till_sync && firstchar != EOF)
4789 continue;
4791 switch (firstchar)
4793 case PqMsg_Query:
4795 const char *query_string;
4797 /* Set statement_timestamp() */
4798 SetCurrentStatementStartTimestamp();
4800 query_string = pq_getmsgstring(&input_message);
4801 pq_getmsgend(&input_message);
4803 if (am_walsender)
4805 if (!exec_replication_command(query_string))
4806 exec_simple_query(query_string);
4808 else
4809 exec_simple_query(query_string);
4811 valgrind_report_error_query(query_string);
4813 send_ready_for_query = true;
4815 break;
4817 case PqMsg_Parse:
4819 const char *stmt_name;
4820 const char *query_string;
4821 int numParams;
4822 Oid *paramTypes = NULL;
4824 forbidden_in_wal_sender(firstchar);
4826 /* Set statement_timestamp() */
4827 SetCurrentStatementStartTimestamp();
4829 stmt_name = pq_getmsgstring(&input_message);
4830 query_string = pq_getmsgstring(&input_message);
4831 numParams = pq_getmsgint(&input_message, 2);
4832 if (numParams > 0)
4834 paramTypes = palloc_array(Oid, numParams);
4835 for (int i = 0; i < numParams; i++)
4836 paramTypes[i] = pq_getmsgint(&input_message, 4);
4838 pq_getmsgend(&input_message);
4840 exec_parse_message(query_string, stmt_name,
4841 paramTypes, numParams);
4843 valgrind_report_error_query(query_string);
4845 break;
4847 case PqMsg_Bind:
4848 forbidden_in_wal_sender(firstchar);
4850 /* Set statement_timestamp() */
4851 SetCurrentStatementStartTimestamp();
4854 * this message is complex enough that it seems best to put
4855 * the field extraction out-of-line
4857 exec_bind_message(&input_message);
4859 /* exec_bind_message does valgrind_report_error_query */
4860 break;
4862 case PqMsg_Execute:
4864 const char *portal_name;
4865 int max_rows;
4867 forbidden_in_wal_sender(firstchar);
4869 /* Set statement_timestamp() */
4870 SetCurrentStatementStartTimestamp();
4872 portal_name = pq_getmsgstring(&input_message);
4873 max_rows = pq_getmsgint(&input_message, 4);
4874 pq_getmsgend(&input_message);
4876 exec_execute_message(portal_name, max_rows);
4878 /* exec_execute_message does valgrind_report_error_query */
4880 break;
4882 case PqMsg_FunctionCall:
4883 forbidden_in_wal_sender(firstchar);
4885 /* Set statement_timestamp() */
4886 SetCurrentStatementStartTimestamp();
4888 /* Report query to various monitoring facilities. */
4889 pgstat_report_activity(STATE_FASTPATH, NULL);
4890 set_ps_display("<FASTPATH>");
4892 /* start an xact for this function invocation */
4893 start_xact_command();
4896 * Note: we may at this point be inside an aborted
4897 * transaction. We can't throw error for that until we've
4898 * finished reading the function-call message, so
4899 * HandleFunctionRequest() must check for it after doing so.
4900 * Be careful not to do anything that assumes we're inside a
4901 * valid transaction here.
4904 /* switch back to message context */
4905 MemoryContextSwitchTo(MessageContext);
4907 HandleFunctionRequest(&input_message);
4909 /* commit the function-invocation transaction */
4910 finish_xact_command();
4912 valgrind_report_error_query("fastpath function call");
4914 send_ready_for_query = true;
4915 break;
4917 case PqMsg_Close:
4919 int close_type;
4920 const char *close_target;
4922 forbidden_in_wal_sender(firstchar);
4924 close_type = pq_getmsgbyte(&input_message);
4925 close_target = pq_getmsgstring(&input_message);
4926 pq_getmsgend(&input_message);
4928 switch (close_type)
4930 case 'S':
4931 if (close_target[0] != '\0')
4932 DropPreparedStatement(close_target, false);
4933 else
4935 /* special-case the unnamed statement */
4936 drop_unnamed_stmt();
4938 break;
4939 case 'P':
4941 Portal portal;
4943 portal = GetPortalByName(close_target);
4944 if (PortalIsValid(portal))
4945 PortalDrop(portal, false);
4947 break;
4948 default:
4949 ereport(ERROR,
4950 (errcode(ERRCODE_PROTOCOL_VIOLATION),
4951 errmsg("invalid CLOSE message subtype %d",
4952 close_type)));
4953 break;
4956 if (whereToSendOutput == DestRemote)
4957 pq_putemptymessage(PqMsg_CloseComplete);
4959 valgrind_report_error_query("CLOSE message");
4961 break;
4963 case PqMsg_Describe:
4965 int describe_type;
4966 const char *describe_target;
4968 forbidden_in_wal_sender(firstchar);
4970 /* Set statement_timestamp() (needed for xact) */
4971 SetCurrentStatementStartTimestamp();
4973 describe_type = pq_getmsgbyte(&input_message);
4974 describe_target = pq_getmsgstring(&input_message);
4975 pq_getmsgend(&input_message);
4977 switch (describe_type)
4979 case 'S':
4980 exec_describe_statement_message(describe_target);
4981 break;
4982 case 'P':
4983 exec_describe_portal_message(describe_target);
4984 break;
4985 default:
4986 ereport(ERROR,
4987 (errcode(ERRCODE_PROTOCOL_VIOLATION),
4988 errmsg("invalid DESCRIBE message subtype %d",
4989 describe_type)));
4990 break;
4993 valgrind_report_error_query("DESCRIBE message");
4995 break;
4997 case PqMsg_Flush:
4998 pq_getmsgend(&input_message);
4999 if (whereToSendOutput == DestRemote)
5000 pq_flush();
5001 break;
5003 case PqMsg_Sync:
5004 pq_getmsgend(&input_message);
5007 * If pipelining was used, we may be in an implicit
5008 * transaction block. Close it before calling
5009 * finish_xact_command.
5011 EndImplicitTransactionBlock();
5012 finish_xact_command();
5013 valgrind_report_error_query("SYNC message");
5014 send_ready_for_query = true;
5015 break;
5018 * 'X' means that the frontend is closing down the socket. EOF
5019 * means unexpected loss of frontend connection. Either way,
5020 * perform normal shutdown.
5022 case EOF:
5024 /* for the cumulative statistics system */
5025 pgStatSessionEndCause = DISCONNECT_CLIENT_EOF;
5027 /* FALLTHROUGH */
5029 case PqMsg_Terminate:
5032 * Reset whereToSendOutput to prevent ereport from attempting
5033 * to send any more messages to client.
5035 if (whereToSendOutput == DestRemote)
5036 whereToSendOutput = DestNone;
5039 * NOTE: if you are tempted to add more code here, DON'T!
5040 * Whatever you had in mind to do should be set up as an
5041 * on_proc_exit or on_shmem_exit callback, instead. Otherwise
5042 * it will fail to be called during other backend-shutdown
5043 * scenarios.
5045 proc_exit(0);
5047 case PqMsg_CopyData:
5048 case PqMsg_CopyDone:
5049 case PqMsg_CopyFail:
5052 * Accept but ignore these messages, per protocol spec; we
5053 * probably got here because a COPY failed, and the frontend
5054 * is still sending data.
5056 break;
5058 default:
5059 ereport(FATAL,
5060 (errcode(ERRCODE_PROTOCOL_VIOLATION),
5061 errmsg("invalid frontend message type %d",
5062 firstchar)));
5064 } /* end of input-reading loop */
5068 * Throw an error if we're a WAL sender process.
5070 * This is used to forbid anything else than simple query protocol messages
5071 * in a WAL sender process. 'firstchar' specifies what kind of a forbidden
5072 * message was received, and is used to construct the error message.
5074 static void
5075 forbidden_in_wal_sender(char firstchar)
5077 if (am_walsender)
5079 if (firstchar == PqMsg_FunctionCall)
5080 ereport(ERROR,
5081 (errcode(ERRCODE_PROTOCOL_VIOLATION),
5082 errmsg("fastpath function calls not supported in a replication connection")));
5083 else
5084 ereport(ERROR,
5085 (errcode(ERRCODE_PROTOCOL_VIOLATION),
5086 errmsg("extended query protocol not supported in a replication connection")));
5092 * Obtain platform stack depth limit (in bytes)
5094 * Return -1 if unknown
5096 long
5097 get_stack_depth_rlimit(void)
5099 #if defined(HAVE_GETRLIMIT)
5100 static long val = 0;
5102 /* This won't change after process launch, so check just once */
5103 if (val == 0)
5105 struct rlimit rlim;
5107 if (getrlimit(RLIMIT_STACK, &rlim) < 0)
5108 val = -1;
5109 else if (rlim.rlim_cur == RLIM_INFINITY)
5110 val = LONG_MAX;
5111 /* rlim_cur is probably of an unsigned type, so check for overflow */
5112 else if (rlim.rlim_cur >= LONG_MAX)
5113 val = LONG_MAX;
5114 else
5115 val = rlim.rlim_cur;
5117 return val;
5118 #else
5119 /* On Windows we set the backend stack size in src/backend/Makefile */
5120 return WIN32_STACK_RLIMIT;
5121 #endif
5125 static struct rusage Save_r;
5126 static struct timeval Save_t;
5128 void
5129 ResetUsage(void)
5131 getrusage(RUSAGE_SELF, &Save_r);
5132 gettimeofday(&Save_t, NULL);
5135 void
5136 ShowUsage(const char *title)
5138 StringInfoData str;
5139 struct timeval user,
5140 sys;
5141 struct timeval elapse_t;
5142 struct rusage r;
5144 getrusage(RUSAGE_SELF, &r);
5145 gettimeofday(&elapse_t, NULL);
5146 memcpy((char *) &user, (char *) &r.ru_utime, sizeof(user));
5147 memcpy((char *) &sys, (char *) &r.ru_stime, sizeof(sys));
5148 if (elapse_t.tv_usec < Save_t.tv_usec)
5150 elapse_t.tv_sec--;
5151 elapse_t.tv_usec += 1000000;
5153 if (r.ru_utime.tv_usec < Save_r.ru_utime.tv_usec)
5155 r.ru_utime.tv_sec--;
5156 r.ru_utime.tv_usec += 1000000;
5158 if (r.ru_stime.tv_usec < Save_r.ru_stime.tv_usec)
5160 r.ru_stime.tv_sec--;
5161 r.ru_stime.tv_usec += 1000000;
5165 * The only stats we don't show here are ixrss, idrss, isrss. It takes
5166 * some work to interpret them, and most platforms don't fill them in.
5168 initStringInfo(&str);
5170 appendStringInfoString(&str, "! system usage stats:\n");
5171 appendStringInfo(&str,
5172 "!\t%ld.%06ld s user, %ld.%06ld s system, %ld.%06ld s elapsed\n",
5173 (long) (r.ru_utime.tv_sec - Save_r.ru_utime.tv_sec),
5174 (long) (r.ru_utime.tv_usec - Save_r.ru_utime.tv_usec),
5175 (long) (r.ru_stime.tv_sec - Save_r.ru_stime.tv_sec),
5176 (long) (r.ru_stime.tv_usec - Save_r.ru_stime.tv_usec),
5177 (long) (elapse_t.tv_sec - Save_t.tv_sec),
5178 (long) (elapse_t.tv_usec - Save_t.tv_usec));
5179 appendStringInfo(&str,
5180 "!\t[%ld.%06ld s user, %ld.%06ld s system total]\n",
5181 (long) user.tv_sec,
5182 (long) user.tv_usec,
5183 (long) sys.tv_sec,
5184 (long) sys.tv_usec);
5185 #ifndef WIN32
5188 * The following rusage fields are not defined by POSIX, but they're
5189 * present on all current Unix-like systems so we use them without any
5190 * special checks. Some of these could be provided in our Windows
5191 * emulation in src/port/win32getrusage.c with more work.
5193 appendStringInfo(&str,
5194 "!\t%ld kB max resident size\n",
5195 #if defined(__darwin__)
5196 /* in bytes on macOS */
5197 r.ru_maxrss / 1024
5198 #else
5199 /* in kilobytes on most other platforms */
5200 r.ru_maxrss
5201 #endif
5203 appendStringInfo(&str,
5204 "!\t%ld/%ld [%ld/%ld] filesystem blocks in/out\n",
5205 r.ru_inblock - Save_r.ru_inblock,
5206 /* they only drink coffee at dec */
5207 r.ru_oublock - Save_r.ru_oublock,
5208 r.ru_inblock, r.ru_oublock);
5209 appendStringInfo(&str,
5210 "!\t%ld/%ld [%ld/%ld] page faults/reclaims, %ld [%ld] swaps\n",
5211 r.ru_majflt - Save_r.ru_majflt,
5212 r.ru_minflt - Save_r.ru_minflt,
5213 r.ru_majflt, r.ru_minflt,
5214 r.ru_nswap - Save_r.ru_nswap,
5215 r.ru_nswap);
5216 appendStringInfo(&str,
5217 "!\t%ld [%ld] signals rcvd, %ld/%ld [%ld/%ld] messages rcvd/sent\n",
5218 r.ru_nsignals - Save_r.ru_nsignals,
5219 r.ru_nsignals,
5220 r.ru_msgrcv - Save_r.ru_msgrcv,
5221 r.ru_msgsnd - Save_r.ru_msgsnd,
5222 r.ru_msgrcv, r.ru_msgsnd);
5223 appendStringInfo(&str,
5224 "!\t%ld/%ld [%ld/%ld] voluntary/involuntary context switches\n",
5225 r.ru_nvcsw - Save_r.ru_nvcsw,
5226 r.ru_nivcsw - Save_r.ru_nivcsw,
5227 r.ru_nvcsw, r.ru_nivcsw);
5228 #endif /* !WIN32 */
5230 /* remove trailing newline */
5231 if (str.data[str.len - 1] == '\n')
5232 str.data[--str.len] = '\0';
5234 ereport(LOG,
5235 (errmsg_internal("%s", title),
5236 errdetail_internal("%s", str.data)));
5238 pfree(str.data);
5242 * on_proc_exit handler to log end of session
5244 static void
5245 log_disconnections(int code, Datum arg)
5247 Port *port = MyProcPort;
5248 long secs;
5249 int usecs;
5250 int msecs;
5251 int hours,
5252 minutes,
5253 seconds;
5255 TimestampDifference(MyStartTimestamp,
5256 GetCurrentTimestamp(),
5257 &secs, &usecs);
5258 msecs = usecs / 1000;
5260 hours = secs / SECS_PER_HOUR;
5261 secs %= SECS_PER_HOUR;
5262 minutes = secs / SECS_PER_MINUTE;
5263 seconds = secs % SECS_PER_MINUTE;
5265 ereport(LOG,
5266 (errmsg("disconnection: session time: %d:%02d:%02d.%03d "
5267 "user=%s database=%s host=%s%s%s",
5268 hours, minutes, seconds, msecs,
5269 port->user_name, port->database_name, port->remote_host,
5270 port->remote_port[0] ? " port=" : "", port->remote_port)));
5274 * Start statement timeout timer, if enabled.
5276 * If there's already a timeout running, don't restart the timer. That
5277 * enables compromises between accuracy of timeouts and cost of starting a
5278 * timeout.
5280 static void
5281 enable_statement_timeout(void)
5283 /* must be within an xact */
5284 Assert(xact_started);
5286 if (StatementTimeout > 0
5287 && (StatementTimeout < TransactionTimeout || TransactionTimeout == 0))
5289 if (!get_timeout_active(STATEMENT_TIMEOUT))
5290 enable_timeout_after(STATEMENT_TIMEOUT, StatementTimeout);
5292 else
5294 if (get_timeout_active(STATEMENT_TIMEOUT))
5295 disable_timeout(STATEMENT_TIMEOUT, false);
5300 * Disable statement timeout, if active.
5302 static void
5303 disable_statement_timeout(void)
5305 if (get_timeout_active(STATEMENT_TIMEOUT))
5306 disable_timeout(STATEMENT_TIMEOUT, false);