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