1 /*-------------------------------------------------------------------------
4 * POSTGRES C Backend Interface
6 * Portions Copyright (c) 1996-2017, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
11 * src/backend/tcop/postgres.c
14 * this is the "main" module of the postgres backend and
15 * hence the main module of the "traffic cop".
17 *-------------------------------------------------------------------------
26 #include <sys/socket.h>
27 #ifdef HAVE_SYS_SELECT_H
28 #include <sys/select.h>
30 #ifdef HAVE_SYS_RESOURCE_H
32 #include <sys/resource.h>
35 #ifndef HAVE_GETRUSAGE
36 #include "rusagestub.h"
39 #include "access/parallel.h"
40 #include "access/printtup.h"
41 #include "access/xact.h"
42 #include "catalog/pg_type.h"
43 #include "commands/async.h"
44 #include "commands/prepare.h"
45 #include "libpq/libpq.h"
46 #include "libpq/pqformat.h"
47 #include "libpq/pqsignal.h"
48 #include "miscadmin.h"
49 #include "nodes/print.h"
50 #include "optimizer/planner.h"
53 #include "parser/analyze.h"
54 #include "parser/parser.h"
55 #include "pg_getopt.h"
56 #include "postmaster/autovacuum.h"
57 #include "postmaster/postmaster.h"
58 #include "replication/logicallauncher.h"
59 #include "replication/logicalworker.h"
60 #include "replication/slot.h"
61 #include "replication/walsender.h"
62 #include "rewrite/rewriteHandler.h"
63 #include "storage/bufmgr.h"
64 #include "storage/ipc.h"
65 #include "storage/proc.h"
66 #include "storage/procsignal.h"
67 #include "storage/sinval.h"
68 #include "tcop/fastpath.h"
69 #include "tcop/pquery.h"
70 #include "tcop/tcopprot.h"
71 #include "tcop/utility.h"
72 #include "utils/lsyscache.h"
73 #include "utils/memutils.h"
74 #include "utils/ps_status.h"
75 #include "utils/snapmgr.h"
76 #include "utils/timeout.h"
77 #include "utils/timestamp.h"
78 #include "mb/pg_wchar.h"
85 const char *debug_query_string; /* client-supplied query string */
87 /* Note: whereToSendOutput is initialized for the bootstrap/standalone case */
88 CommandDest whereToSendOutput = DestDebug;
90 /* flag for logging end of session */
91 bool Log_disconnections = false;
93 int log_statement = LOGSTMT_NONE;
95 /* GUC variable for maximum stack depth (measured in kilobytes) */
96 int max_stack_depth = 100;
98 /* wait N seconds to allow attach from a debugger */
99 int PostAuthDelay = 0;
108 /* max_stack_depth converted to bytes for speed of checking */
109 static long max_stack_depth_bytes = 100 * 1024L;
112 * Stack base pointer -- initialized by PostmasterMain and inherited by
113 * subprocesses. This is not static because old versions of PL/Java modify
114 * it directly. Newer versions use set_stack_base(), but we want to stay
115 * binary-compatible for the time being.
117 char *stack_base_ptr = NULL;
120 * On IA64 we also have to remember the register stack base.
122 #if defined(__ia64__) || defined(__ia64)
123 char *register_stack_base_ptr = NULL;
127 * Flag to keep track of whether we have started a transaction.
128 * For extended query protocol this has to be remembered across messages.
130 static bool xact_started = false;
133 * Flag to indicate that we are doing the outer loop's read-from-client,
134 * as opposed to any random read from client that might happen within
135 * commands like COPY FROM STDIN.
137 static bool DoingCommandRead = false;
140 * Flags to implement skip-till-Sync-after-error behavior for messages of
141 * the extended query protocol.
143 static bool doing_extended_query_message = false;
144 static bool ignore_till_sync = false;
147 * Flag to keep track of whether statement timeout timer is active.
149 static bool stmt_timeout_active = false;
152 * If an unnamed prepared statement exists, it's stored here.
153 * We keep it separate from the hashtable kept by commands/prepare.c
154 * in order to reduce overhead for short-lived queries.
156 static CachedPlanSource *unnamed_stmt_psrc = NULL;
158 /* assorted command-line switches */
159 static const char *userDoption = NULL; /* -D switch */
160 static bool EchoQuery = false; /* -E switch */
161 static bool UseSemiNewlineNewline = false; /* -j switch */
163 /* whether or not, and why, we were canceled by conflict with recovery */
164 static bool RecoveryConflictPending = false;
165 static bool RecoveryConflictRetryable = true;
166 static ProcSignalReason RecoveryConflictReason;
168 /* reused buffer to pass to SendRowDescriptionMessage() */
169 static MemoryContext row_description_context = NULL;
170 static StringInfoData row_description_buf;
172 /* ----------------------------------------------------------------
173 * decls for routines only used in this file
174 * ----------------------------------------------------------------
176 static int InteractiveBackend(StringInfo inBuf);
177 static int interactive_getc(void);
178 static int SocketBackend(StringInfo inBuf);
179 static int ReadCommand(StringInfo inBuf);
180 static void forbidden_in_wal_sender(char firstchar);
181 static List *pg_rewrite_query(Query *query);
182 static bool check_log_statement(List *stmt_list);
183 static int errdetail_execute(List *raw_parsetree_list);
184 static int errdetail_params(ParamListInfo params);
185 static int errdetail_abort(void);
186 static int errdetail_recovery_conflict(void);
187 static void start_xact_command(void);
188 static void finish_xact_command(void);
189 static bool IsTransactionExitStmt(Node *parsetree);
190 static bool IsTransactionExitStmtList(List *pstmts);
191 static bool IsTransactionStmtList(List *pstmts);
192 static void drop_unnamed_stmt(void);
193 static void log_disconnections(int code, Datum arg);
194 static void enable_statement_timeout(void);
195 static void disable_statement_timeout(void);
198 /* ----------------------------------------------------------------
199 * routines to obtain user input
200 * ----------------------------------------------------------------
204 * InteractiveBackend() is called for user interactive connections
206 * the string entered by the user is placed in its parameter inBuf,
207 * and we act like a Q message was received.
209 * EOF is returned if end-of-file input is seen; time to shut down.
214 InteractiveBackend(StringInfo inBuf)
216 int c; /* character read from getc() */
219 * display a prompt and obtain input from the user
224 resetStringInfo(inBuf);
227 * Read characters until EOF or the appropriate delimiter is seen.
229 while ((c = interactive_getc()) != EOF)
233 if (UseSemiNewlineNewline)
236 * In -j mode, semicolon followed by two newlines ends the
237 * command; otherwise treat newline as regular character.
239 if (inBuf->len > 1 &&
240 inBuf->data[inBuf->len - 1] == '\n' &&
241 inBuf->data[inBuf->len - 2] == ';')
243 /* might as well drop the second newline */
250 * In plain mode, newline ends the command unless preceded by
253 if (inBuf->len > 0 &&
254 inBuf->data[inBuf->len - 1] == '\\')
256 /* discard backslash from inBuf */
257 inBuf->data[--inBuf->len] = '\0';
258 /* discard newline too */
263 /* keep the newline character, but end the command */
264 appendStringInfoChar(inBuf, '\n');
270 /* Not newline, or newline treated as regular character */
271 appendStringInfoChar(inBuf, (char) c);
274 /* No input before EOF signal means time to quit. */
275 if (c == EOF && inBuf->len == 0)
279 * otherwise we have a user query so process it.
282 /* Add '\0' to make it look the same as message case. */
283 appendStringInfoChar(inBuf, (char) '\0');
286 * if the query echo flag was given, print the query..
289 printf("statement: %s\n", inBuf->data);
296 * interactive_getc -- collect one character from stdin
298 * Even though we are not reading from a "client" process, we still want to
299 * respond to signals, particularly SIGTERM/SIGQUIT.
302 interactive_getc(void)
307 * This will not process catchup interrupts or notifications while
308 * reading. But those can't really be relevant for a standalone backend
309 * anyway. To properly handle SIGTERM there's a hack in die() that
310 * directly processes interrupts at this stage...
312 CHECK_FOR_INTERRUPTS();
316 ProcessClientReadInterrupt(true);
322 * SocketBackend() Is called for frontend-backend connections
324 * Returns the message type code, and loads message body data into inBuf.
326 * EOF is returned if the connection is lost.
330 SocketBackend(StringInfo inBuf)
335 * Get message type code from the frontend.
337 HOLD_CANCEL_INTERRUPTS();
339 qtype = pq_getbyte();
341 if (qtype == EOF) /* frontend disconnected */
343 if (IsTransactionState())
345 (errcode(ERRCODE_CONNECTION_FAILURE),
346 errmsg("unexpected EOF on client connection with an open transaction")));
350 * Can't send DEBUG log messages to client at this point. Since
351 * we're disconnecting right away, we don't need to restore
354 whereToSendOutput = DestNone;
356 (errcode(ERRCODE_CONNECTION_DOES_NOT_EXIST),
357 errmsg("unexpected EOF on client connection")));
363 * Validate message type code before trying to read body; if we have lost
364 * sync, better to say "command unknown" than to run out of memory because
365 * we used garbage as a length word.
367 * This also gives us a place to set the doing_extended_query_message flag
368 * as soon as possible.
372 case 'Q': /* simple query */
373 doing_extended_query_message = false;
374 if (PG_PROTOCOL_MAJOR(FrontendProtocol) < 3)
376 /* old style without length word; convert */
377 if (pq_getstring(inBuf))
379 if (IsTransactionState())
381 (errcode(ERRCODE_CONNECTION_FAILURE),
382 errmsg("unexpected EOF on client connection with an open transaction")));
386 * Can't send DEBUG log messages to client at this
387 * point. Since we're disconnecting right away, we
388 * don't need to restore whereToSendOutput.
390 whereToSendOutput = DestNone;
392 (errcode(ERRCODE_CONNECTION_DOES_NOT_EXIST),
393 errmsg("unexpected EOF on client connection")));
400 case 'F': /* fastpath function call */
401 doing_extended_query_message = false;
402 if (PG_PROTOCOL_MAJOR(FrontendProtocol) < 3)
404 if (GetOldFunctionMessage(inBuf))
406 if (IsTransactionState())
408 (errcode(ERRCODE_CONNECTION_FAILURE),
409 errmsg("unexpected EOF on client connection with an open transaction")));
413 * Can't send DEBUG log messages to client at this
414 * point. Since we're disconnecting right away, we
415 * don't need to restore whereToSendOutput.
417 whereToSendOutput = DestNone;
419 (errcode(ERRCODE_CONNECTION_DOES_NOT_EXIST),
420 errmsg("unexpected EOF on client connection")));
427 case 'X': /* terminate */
428 doing_extended_query_message = false;
429 ignore_till_sync = false;
433 case 'C': /* close */
434 case 'D': /* describe */
435 case 'E': /* execute */
436 case 'H': /* flush */
437 case 'P': /* parse */
438 doing_extended_query_message = true;
439 /* these are only legal in protocol 3 */
440 if (PG_PROTOCOL_MAJOR(FrontendProtocol) < 3)
442 (errcode(ERRCODE_PROTOCOL_VIOLATION),
443 errmsg("invalid frontend message type %d", qtype)));
447 /* stop any active skip-till-Sync */
448 ignore_till_sync = false;
449 /* mark not-extended, so that a new error doesn't begin skip */
450 doing_extended_query_message = false;
451 /* only legal in protocol 3 */
452 if (PG_PROTOCOL_MAJOR(FrontendProtocol) < 3)
454 (errcode(ERRCODE_PROTOCOL_VIOLATION),
455 errmsg("invalid frontend message type %d", qtype)));
458 case 'd': /* copy data */
459 case 'c': /* copy done */
460 case 'f': /* copy fail */
461 doing_extended_query_message = false;
462 /* these are only legal in protocol 3 */
463 if (PG_PROTOCOL_MAJOR(FrontendProtocol) < 3)
465 (errcode(ERRCODE_PROTOCOL_VIOLATION),
466 errmsg("invalid frontend message type %d", qtype)));
472 * Otherwise we got garbage from the frontend. We treat this as
473 * fatal because we have probably lost message boundary sync, and
474 * there's no good way to recover.
477 (errcode(ERRCODE_PROTOCOL_VIOLATION),
478 errmsg("invalid frontend message type %d", qtype)));
483 * In protocol version 3, all frontend messages have a length word next
484 * after the type code; we can read the message contents independently of
487 if (PG_PROTOCOL_MAJOR(FrontendProtocol) >= 3)
489 if (pq_getmessage(inBuf, 0))
490 return EOF; /* suitable message already logged */
494 RESUME_CANCEL_INTERRUPTS();
500 * ReadCommand reads a command from either the frontend or
501 * standard input, places it in inBuf, and returns the
502 * message type code (first byte of the message).
503 * EOF is returned if end of file.
507 ReadCommand(StringInfo inBuf)
511 if (whereToSendOutput == DestRemote)
512 result = SocketBackend(inBuf);
514 result = InteractiveBackend(inBuf);
519 * ProcessClientReadInterrupt() - Process interrupts specific to client reads
521 * This is called just after low-level reads. That might be after the read
522 * finished successfully, or it was interrupted via interrupt.
524 * Must preserve errno!
527 ProcessClientReadInterrupt(bool blocked)
529 int save_errno = errno;
531 if (DoingCommandRead)
533 /* Check for general interrupts that arrived while reading */
534 CHECK_FOR_INTERRUPTS();
536 /* Process sinval catchup interrupts that happened while reading */
537 if (catchupInterruptPending)
538 ProcessCatchupInterrupt();
540 /* Process sinval catchup interrupts that happened while reading */
541 if (notifyInterruptPending)
542 ProcessNotifyInterrupt();
544 else if (ProcDiePending && blocked)
547 * We're dying. It's safe (and sane) to handle that now.
549 CHECK_FOR_INTERRUPTS();
556 * ProcessClientWriteInterrupt() - Process interrupts specific to client writes
558 * This is called just after low-level writes. That might be after the read
559 * finished successfully, or it was interrupted via interrupt. 'blocked' tells
562 * Must preserve errno!
565 ProcessClientWriteInterrupt(bool blocked)
567 int save_errno = errno;
570 * We only want to process the interrupt here if socket writes are
571 * blocking to increase the chance to get an error message to the client.
572 * If we're not blocked there'll soon be a CHECK_FOR_INTERRUPTS(). But if
573 * we're blocked we'll never get out of that situation if the client has
576 if (ProcDiePending && blocked)
579 * We're dying. It's safe (and sane) to handle that now. But we don't
580 * want to send the client the error message as that a) would possibly
581 * block again b) would possibly lead to sending an error message to
582 * the client, while we already started to send something else.
584 if (whereToSendOutput == DestRemote)
585 whereToSendOutput = DestNone;
587 CHECK_FOR_INTERRUPTS();
594 * Do raw parsing (only).
596 * A list of parsetrees (RawStmt nodes) is returned, since there might be
597 * multiple commands in the given string.
599 * NOTE: for interactive queries, it is important to keep this routine
600 * separate from the analysis & rewrite stages. Analysis and rewriting
601 * cannot be done in an aborted transaction, since they require access to
602 * database tables. So, we rely on the raw parser to determine whether
603 * we've seen a COMMIT or ABORT command; when we are in abort state, other
604 * commands are not processed any further than the raw parse stage.
607 pg_parse_query(const char *query_string)
609 List *raw_parsetree_list;
611 TRACE_POSTGRESQL_QUERY_PARSE_START(query_string);
613 if (log_parser_stats)
616 raw_parsetree_list = raw_parser(query_string);
618 if (log_parser_stats)
619 ShowUsage("PARSER STATISTICS");
621 #ifdef COPY_PARSE_PLAN_TREES
622 /* Optional debugging check: pass raw parsetrees through copyObject() */
624 List *new_list = copyObject(raw_parsetree_list);
626 /* This checks both copyObject() and the equal() routines... */
627 if (!equal(new_list, raw_parsetree_list))
628 elog(WARNING, "copyObject() failed to produce an equal raw parse tree");
630 raw_parsetree_list = new_list;
634 TRACE_POSTGRESQL_QUERY_PARSE_DONE(query_string);
636 return raw_parsetree_list;
640 * Given a raw parsetree (gram.y output), and optionally information about
641 * types of parameter symbols ($n), perform parse analysis and rule rewriting.
643 * A list of Query nodes is returned, since either the analyzer or the
644 * rewriter might expand one query to several.
646 * NOTE: for reasons mentioned above, this must be separate from raw parsing.
649 pg_analyze_and_rewrite(RawStmt *parsetree, const char *query_string,
650 Oid *paramTypes, int numParams,
651 QueryEnvironment *queryEnv)
654 List *querytree_list;
656 TRACE_POSTGRESQL_QUERY_REWRITE_START(query_string);
659 * (1) Perform parse analysis.
661 if (log_parser_stats)
664 query = parse_analyze(parsetree, query_string, paramTypes, numParams,
667 if (log_parser_stats)
668 ShowUsage("PARSE ANALYSIS STATISTICS");
671 * (2) Rewrite the queries, as necessary
673 querytree_list = pg_rewrite_query(query);
675 TRACE_POSTGRESQL_QUERY_REWRITE_DONE(query_string);
677 return querytree_list;
681 * Do parse analysis and rewriting. This is the same as pg_analyze_and_rewrite
682 * except that external-parameter resolution is determined by parser callback
683 * hooks instead of a fixed list of parameter datatypes.
686 pg_analyze_and_rewrite_params(RawStmt *parsetree,
687 const char *query_string,
688 ParserSetupHook parserSetup,
689 void *parserSetupArg,
690 QueryEnvironment *queryEnv)
694 List *querytree_list;
696 Assert(query_string != NULL); /* required as of 8.4 */
698 TRACE_POSTGRESQL_QUERY_REWRITE_START(query_string);
701 * (1) Perform parse analysis.
703 if (log_parser_stats)
706 pstate = make_parsestate(NULL);
707 pstate->p_sourcetext = query_string;
708 pstate->p_queryEnv = queryEnv;
709 (*parserSetup) (pstate, parserSetupArg);
711 query = transformTopLevelStmt(pstate, parsetree);
713 if (post_parse_analyze_hook)
714 (*post_parse_analyze_hook) (pstate, query);
716 free_parsestate(pstate);
718 if (log_parser_stats)
719 ShowUsage("PARSE ANALYSIS STATISTICS");
722 * (2) Rewrite the queries, as necessary
724 querytree_list = pg_rewrite_query(query);
726 TRACE_POSTGRESQL_QUERY_REWRITE_DONE(query_string);
728 return querytree_list;
732 * Perform rewriting of a query produced by parse analysis.
734 * Note: query must just have come from the parser, because we do not do
735 * AcquireRewriteLocks() on it.
738 pg_rewrite_query(Query *query)
740 List *querytree_list;
742 if (Debug_print_parse)
743 elog_node_display(LOG, "parse tree", query,
746 if (log_parser_stats)
749 if (query->commandType == CMD_UTILITY)
751 /* don't rewrite utilities, just dump 'em into result list */
752 querytree_list = list_make1(query);
756 /* rewrite regular queries */
757 querytree_list = QueryRewrite(query);
760 if (log_parser_stats)
761 ShowUsage("REWRITER STATISTICS");
763 #ifdef COPY_PARSE_PLAN_TREES
764 /* Optional debugging check: pass querytree output through copyObject() */
768 new_list = copyObject(querytree_list);
769 /* This checks both copyObject() and the equal() routines... */
770 if (!equal(new_list, querytree_list))
771 elog(WARNING, "copyObject() failed to produce equal parse tree");
773 querytree_list = new_list;
777 if (Debug_print_rewritten)
778 elog_node_display(LOG, "rewritten parse tree", querytree_list,
781 return querytree_list;
786 * Generate a plan for a single already-rewritten query.
787 * This is a thin wrapper around planner() and takes the same parameters.
790 pg_plan_query(Query *querytree, int cursorOptions, ParamListInfo boundParams)
794 /* Utility commands have no plans. */
795 if (querytree->commandType == CMD_UTILITY)
798 /* Planner must have a snapshot in case it calls user-defined functions. */
799 Assert(ActiveSnapshotSet());
801 TRACE_POSTGRESQL_QUERY_PLAN_START();
803 if (log_planner_stats)
806 /* call the optimizer */
807 plan = planner(querytree, cursorOptions, boundParams);
809 if (log_planner_stats)
810 ShowUsage("PLANNER STATISTICS");
812 #ifdef COPY_PARSE_PLAN_TREES
813 /* Optional debugging check: pass plan output through copyObject() */
815 PlannedStmt *new_plan = copyObject(plan);
818 * equal() currently does not have routines to compare Plan nodes, so
819 * don't try to test equality here. Perhaps fix someday?
822 /* This checks both copyObject() and the equal() routines... */
823 if (!equal(new_plan, plan))
824 elog(WARNING, "copyObject() failed to produce an equal plan tree");
832 * Print plan if debugging.
834 if (Debug_print_plan)
835 elog_node_display(LOG, "plan", plan, Debug_pretty_print);
837 TRACE_POSTGRESQL_QUERY_PLAN_DONE();
843 * Generate plans for a list of already-rewritten queries.
845 * For normal optimizable statements, invoke the planner. For utility
846 * statements, just make a wrapper PlannedStmt node.
848 * The result is a list of PlannedStmt nodes.
851 pg_plan_queries(List *querytrees, int cursorOptions, ParamListInfo boundParams)
853 List *stmt_list = NIL;
854 ListCell *query_list;
856 foreach(query_list, querytrees)
858 Query *query = lfirst_node(Query, query_list);
861 if (query->commandType == CMD_UTILITY)
863 /* Utility commands require no planning. */
864 stmt = makeNode(PlannedStmt);
865 stmt->commandType = CMD_UTILITY;
866 stmt->canSetTag = query->canSetTag;
867 stmt->utilityStmt = query->utilityStmt;
868 stmt->stmt_location = query->stmt_location;
869 stmt->stmt_len = query->stmt_len;
873 stmt = pg_plan_query(query, cursorOptions, boundParams);
876 stmt_list = lappend(stmt_list, stmt);
886 * Execute a "simple Query" protocol message.
889 exec_simple_query(const char *query_string)
891 CommandDest dest = whereToSendOutput;
892 MemoryContext oldcontext;
893 List *parsetree_list;
894 ListCell *parsetree_item;
895 bool save_log_statement_stats = log_statement_stats;
896 bool was_logged = false;
897 bool use_implicit_block;
901 * Report query to various monitoring facilities.
903 debug_query_string = query_string;
905 pgstat_report_activity(STATE_RUNNING, query_string);
907 TRACE_POSTGRESQL_QUERY_START(query_string);
910 * We use save_log_statement_stats so ShowUsage doesn't report incorrect
911 * results because ResetUsage wasn't called.
913 if (save_log_statement_stats)
917 * Start up a transaction command. All queries generated by the
918 * query_string will be in this same command block, *unless* we find a
919 * BEGIN/COMMIT/ABORT statement; we have to force a new xact command after
920 * one of those, else bad things will happen in xact.c. (Note that this
921 * will normally change current memory context.)
923 start_xact_command();
926 * Zap any pre-existing unnamed statement. (While not strictly necessary,
927 * it seems best to define simple-Query mode as if it used the unnamed
928 * statement and portal; this ensures we recover any storage used by prior
929 * unnamed operations.)
934 * Switch to appropriate context for constructing parsetrees.
936 oldcontext = MemoryContextSwitchTo(MessageContext);
939 * Do basic parsing of the query or queries (this should be safe even if
940 * we are in aborted transaction state!)
942 parsetree_list = pg_parse_query(query_string);
944 /* Log immediately if dictated by log_statement */
945 if (check_log_statement(parsetree_list))
948 (errmsg("statement: %s", query_string),
950 errdetail_execute(parsetree_list)));
955 * Switch back to transaction context to enter the loop.
957 MemoryContextSwitchTo(oldcontext);
960 * For historical reasons, if multiple SQL statements are given in a
961 * single "simple Query" message, we execute them as a single transaction,
962 * unless explicit transaction control commands are included to make
963 * portions of the list be separate transactions. To represent this
964 * behavior properly in the transaction machinery, we use an "implicit"
967 use_implicit_block = (list_length(parsetree_list) > 1);
970 * Run through the raw parsetree(s) and process each one.
972 foreach(parsetree_item, parsetree_list)
974 RawStmt *parsetree = lfirst_node(RawStmt, parsetree_item);
975 bool snapshot_set = false;
976 const char *commandTag;
977 char completionTag[COMPLETION_TAG_BUFSIZE];
978 List *querytree_list,
981 DestReceiver *receiver;
985 * Get the command name for use in status display (it also becomes the
986 * default completion tag, down inside PortalRun). Set ps_status and
987 * do any special start-of-SQL-command processing needed by the
990 commandTag = CreateCommandTag(parsetree->stmt);
992 set_ps_display(commandTag, false);
994 BeginCommand(commandTag, dest);
997 * If we are in an aborted transaction, reject all commands except
998 * COMMIT/ABORT. It is important that this test occur before we try
999 * to do parse analysis, rewrite, or planning, since all those phases
1000 * try to do database accesses, which may fail in abort state. (It
1001 * might be safe to allow some additional utility commands in this
1002 * state, but not many...)
1004 if (IsAbortedTransactionBlockState() &&
1005 !IsTransactionExitStmt(parsetree->stmt))
1007 (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
1008 errmsg("current transaction is aborted, "
1009 "commands ignored until end of transaction block"),
1010 errdetail_abort()));
1012 /* Make sure we are in a transaction command */
1013 start_xact_command();
1016 * If using an implicit transaction block, and we're not already in a
1017 * transaction block, start an implicit block to force this statement
1018 * to be grouped together with any following ones. (We must do this
1019 * each time through the loop; otherwise, a COMMIT/ROLLBACK in the
1020 * list would cause later statements to not be grouped.)
1022 if (use_implicit_block)
1023 BeginImplicitTransactionBlock();
1025 /* If we got a cancel signal in parsing or prior command, quit */
1026 CHECK_FOR_INTERRUPTS();
1029 * Set up a snapshot if parse analysis/planning will need one.
1031 if (analyze_requires_snapshot(parsetree))
1033 PushActiveSnapshot(GetTransactionSnapshot());
1034 snapshot_set = true;
1038 * OK to analyze, rewrite, and plan this query.
1040 * Switch to appropriate context for constructing querytrees (again,
1041 * these must outlive the execution context).
1043 oldcontext = MemoryContextSwitchTo(MessageContext);
1045 querytree_list = pg_analyze_and_rewrite(parsetree, query_string,
1048 plantree_list = pg_plan_queries(querytree_list,
1049 CURSOR_OPT_PARALLEL_OK, NULL);
1051 /* Done with the snapshot used for parsing/planning */
1053 PopActiveSnapshot();
1055 /* If we got a cancel signal in analysis or planning, quit */
1056 CHECK_FOR_INTERRUPTS();
1059 * Create unnamed portal to run the query or queries in. If there
1060 * already is one, silently drop it.
1062 portal = CreatePortal("", true, true);
1063 /* Don't display the portal in pg_cursors */
1064 portal->visible = false;
1067 * We don't have to copy anything into the portal, because everything
1068 * we are passing here is in MessageContext, which will outlive the
1071 PortalDefineQuery(portal,
1079 * Start the portal. No parameters here.
1081 PortalStart(portal, NULL, 0, InvalidSnapshot);
1084 * Select the appropriate output format: text unless we are doing a
1085 * FETCH from a binary cursor. (Pretty grotty to have to do this here
1086 * --- but it avoids grottiness in other places. Ah, the joys of
1087 * backward compatibility...)
1089 format = 0; /* TEXT is default */
1090 if (IsA(parsetree->stmt, FetchStmt))
1092 FetchStmt *stmt = (FetchStmt *) parsetree->stmt;
1096 Portal fportal = GetPortalByName(stmt->portalname);
1098 if (PortalIsValid(fportal) &&
1099 (fportal->cursorOptions & CURSOR_OPT_BINARY))
1100 format = 1; /* BINARY */
1103 PortalSetResultFormat(portal, 1, &format);
1106 * Now we can create the destination receiver object.
1108 receiver = CreateDestReceiver(dest);
1109 if (dest == DestRemote)
1110 SetRemoteDestReceiverParams(receiver, portal);
1113 * Switch back to transaction context for execution.
1115 MemoryContextSwitchTo(oldcontext);
1118 * Run the portal to completion, and then drop it (and the receiver).
1120 (void) PortalRun(portal,
1122 true, /* always top level */
1128 receiver->rDestroy(receiver);
1130 PortalDrop(portal, false);
1132 if (lnext(parsetree_item) == NULL)
1135 * If this is the last parsetree of the query string, close down
1136 * transaction statement before reporting command-complete. This
1137 * is so that any end-of-transaction errors are reported before
1138 * the command-complete message is issued, to avoid confusing
1139 * clients who will expect either a command-complete message or an
1140 * error, not one and then the other. Also, if we're using an
1141 * implicit transaction block, we must close that out first.
1143 if (use_implicit_block)
1144 EndImplicitTransactionBlock();
1145 finish_xact_command();
1147 else if (IsA(parsetree->stmt, TransactionStmt))
1150 * If this was a transaction control statement, commit it. We will
1151 * start a new xact command for the next command.
1153 finish_xact_command();
1158 * We need a CommandCounterIncrement after every query, except
1159 * those that start or end a transaction block.
1161 CommandCounterIncrement();
1165 * Tell client that we're done with this query. Note we emit exactly
1166 * one EndCommand report for each raw parsetree, thus one for each SQL
1167 * command the client sent, regardless of rewriting. (But a command
1168 * aborted by error will not send an EndCommand report at all.)
1170 EndCommand(completionTag, dest);
1171 } /* end loop over parsetrees */
1174 * Close down transaction statement, if one is open. (This will only do
1175 * something if the parsetree list was empty; otherwise the last loop
1176 * iteration already did it.)
1178 finish_xact_command();
1181 * If there were no parsetrees, return EmptyQueryResponse message.
1183 if (!parsetree_list)
1187 * Emit duration logging if appropriate.
1189 switch (check_log_duration(msec_str, was_logged))
1193 (errmsg("duration: %s ms", msec_str),
1194 errhidestmt(true)));
1198 (errmsg("duration: %s ms statement: %s",
1199 msec_str, query_string),
1201 errdetail_execute(parsetree_list)));
1205 if (save_log_statement_stats)
1206 ShowUsage("QUERY STATISTICS");
1208 TRACE_POSTGRESQL_QUERY_DONE(query_string);
1210 debug_query_string = NULL;
1214 * exec_parse_message
1216 * Execute a "Parse" protocol message.
1219 exec_parse_message(const char *query_string, /* string to execute */
1220 const char *stmt_name, /* name for prepared stmt */
1221 Oid *paramTypes, /* parameter types */
1222 int numParams) /* number of parameters */
1224 MemoryContext unnamed_stmt_context = NULL;
1225 MemoryContext oldcontext;
1226 List *parsetree_list;
1227 RawStmt *raw_parse_tree;
1228 const char *commandTag;
1229 List *querytree_list;
1230 CachedPlanSource *psrc;
1232 bool save_log_statement_stats = log_statement_stats;
1236 * Report query to various monitoring facilities.
1238 debug_query_string = query_string;
1240 pgstat_report_activity(STATE_RUNNING, query_string);
1242 set_ps_display("PARSE", false);
1244 if (save_log_statement_stats)
1248 (errmsg("parse %s: %s",
1249 *stmt_name ? stmt_name : "<unnamed>",
1253 * Start up a transaction command so we can run parse analysis etc. (Note
1254 * that this will normally change current memory context.) Nothing happens
1255 * if we are already in one. This also arms the statement timeout if
1258 start_xact_command();
1261 * Switch to appropriate context for constructing parsetrees.
1263 * We have two strategies depending on whether the prepared statement is
1264 * named or not. For a named prepared statement, we do parsing in
1265 * MessageContext and copy the finished trees into the prepared
1266 * statement's plancache entry; then the reset of MessageContext releases
1267 * temporary space used by parsing and rewriting. For an unnamed prepared
1268 * statement, we assume the statement isn't going to hang around long, so
1269 * getting rid of temp space quickly is probably not worth the costs of
1270 * copying parse trees. So in this case, we create the plancache entry's
1271 * query_context here, and do all the parsing work therein.
1273 is_named = (stmt_name[0] != '\0');
1276 /* Named prepared statement --- parse in MessageContext */
1277 oldcontext = MemoryContextSwitchTo(MessageContext);
1281 /* Unnamed prepared statement --- release any prior unnamed stmt */
1282 drop_unnamed_stmt();
1283 /* Create context for parsing */
1284 unnamed_stmt_context =
1285 AllocSetContextCreate(MessageContext,
1286 "unnamed prepared statement",
1287 ALLOCSET_DEFAULT_SIZES);
1288 oldcontext = MemoryContextSwitchTo(unnamed_stmt_context);
1292 * Do basic parsing of the query or queries (this should be safe even if
1293 * we are in aborted transaction state!)
1295 parsetree_list = pg_parse_query(query_string);
1298 * We only allow a single user statement in a prepared statement. This is
1299 * mainly to keep the protocol simple --- otherwise we'd need to worry
1300 * about multiple result tupdescs and things like that.
1302 if (list_length(parsetree_list) > 1)
1304 (errcode(ERRCODE_SYNTAX_ERROR),
1305 errmsg("cannot insert multiple commands into a prepared statement")));
1307 if (parsetree_list != NIL)
1310 bool snapshot_set = false;
1313 raw_parse_tree = linitial_node(RawStmt, parsetree_list);
1316 * Get the command name for possible use in status display.
1318 commandTag = CreateCommandTag(raw_parse_tree->stmt);
1321 * If we are in an aborted transaction, reject all commands except
1322 * COMMIT/ROLLBACK. It is important that this test occur before we
1323 * try to do parse analysis, rewrite, or planning, since all those
1324 * phases try to do database accesses, which may fail in abort state.
1325 * (It might be safe to allow some additional utility commands in this
1326 * state, but not many...)
1328 if (IsAbortedTransactionBlockState() &&
1329 !IsTransactionExitStmt(raw_parse_tree->stmt))
1331 (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
1332 errmsg("current transaction is aborted, "
1333 "commands ignored until end of transaction block"),
1334 errdetail_abort()));
1337 * Create the CachedPlanSource before we do parse analysis, since it
1338 * needs to see the unmodified raw parse tree.
1340 psrc = CreateCachedPlan(raw_parse_tree, query_string, commandTag);
1343 * Set up a snapshot if parse analysis will need one.
1345 if (analyze_requires_snapshot(raw_parse_tree))
1347 PushActiveSnapshot(GetTransactionSnapshot());
1348 snapshot_set = true;
1352 * Analyze and rewrite the query. Note that the originally specified
1353 * parameter set is not required to be complete, so we have to use
1354 * parse_analyze_varparams().
1356 if (log_parser_stats)
1359 query = parse_analyze_varparams(raw_parse_tree,
1365 * Check all parameter types got determined.
1367 for (i = 0; i < numParams; i++)
1369 Oid ptype = paramTypes[i];
1371 if (ptype == InvalidOid || ptype == UNKNOWNOID)
1373 (errcode(ERRCODE_INDETERMINATE_DATATYPE),
1374 errmsg("could not determine data type of parameter $%d",
1378 if (log_parser_stats)
1379 ShowUsage("PARSE ANALYSIS STATISTICS");
1381 querytree_list = pg_rewrite_query(query);
1383 /* Done with the snapshot used for parsing */
1385 PopActiveSnapshot();
1389 /* Empty input string. This is legal. */
1390 raw_parse_tree = NULL;
1392 psrc = CreateCachedPlan(raw_parse_tree, query_string, commandTag);
1393 querytree_list = NIL;
1397 * CachedPlanSource must be a direct child of MessageContext before we
1398 * reparent unnamed_stmt_context under it, else we have a disconnected
1399 * circular subgraph. Klugy, but less so than flipping contexts even more
1402 if (unnamed_stmt_context)
1403 MemoryContextSetParent(psrc->context, MessageContext);
1405 /* Finish filling in the CachedPlanSource */
1406 CompleteCachedPlan(psrc,
1408 unnamed_stmt_context,
1413 CURSOR_OPT_PARALLEL_OK, /* allow parallel mode */
1414 true); /* fixed result */
1416 /* If we got a cancel signal during analysis, quit */
1417 CHECK_FOR_INTERRUPTS();
1422 * Store the query as a prepared statement.
1424 StorePreparedStatement(stmt_name, psrc, false);
1429 * We just save the CachedPlanSource into unnamed_stmt_psrc.
1431 SaveCachedPlan(psrc);
1432 unnamed_stmt_psrc = psrc;
1435 MemoryContextSwitchTo(oldcontext);
1438 * We do NOT close the open transaction command here; that only happens
1439 * when the client sends Sync. Instead, do CommandCounterIncrement just
1440 * in case something happened during parse/plan.
1442 CommandCounterIncrement();
1445 * Send ParseComplete.
1447 if (whereToSendOutput == DestRemote)
1448 pq_putemptymessage('1');
1451 * Emit duration logging if appropriate.
1453 switch (check_log_duration(msec_str, false))
1457 (errmsg("duration: %s ms", msec_str),
1458 errhidestmt(true)));
1462 (errmsg("duration: %s ms parse %s: %s",
1464 *stmt_name ? stmt_name : "<unnamed>",
1466 errhidestmt(true)));
1470 if (save_log_statement_stats)
1471 ShowUsage("PARSE MESSAGE STATISTICS");
1473 debug_query_string = NULL;
1479 * Process a "Bind" message to create a portal from a prepared statement
1482 exec_bind_message(StringInfo input_message)
1484 const char *portal_name;
1485 const char *stmt_name;
1487 int16 *pformats = NULL;
1490 int16 *rformats = NULL;
1491 CachedPlanSource *psrc;
1495 char *saved_stmt_name;
1496 ParamListInfo params;
1497 MemoryContext oldContext;
1498 bool save_log_statement_stats = log_statement_stats;
1499 bool snapshot_set = false;
1502 /* Get the fixed part of the message */
1503 portal_name = pq_getmsgstring(input_message);
1504 stmt_name = pq_getmsgstring(input_message);
1507 (errmsg("bind %s to %s",
1508 *portal_name ? portal_name : "<unnamed>",
1509 *stmt_name ? stmt_name : "<unnamed>")));
1511 /* Find prepared statement */
1512 if (stmt_name[0] != '\0')
1514 PreparedStatement *pstmt;
1516 pstmt = FetchPreparedStatement(stmt_name, true);
1517 psrc = pstmt->plansource;
1521 /* special-case the unnamed statement */
1522 psrc = unnamed_stmt_psrc;
1525 (errcode(ERRCODE_UNDEFINED_PSTATEMENT),
1526 errmsg("unnamed prepared statement does not exist")));
1530 * Report query to various monitoring facilities.
1532 debug_query_string = psrc->query_string;
1534 pgstat_report_activity(STATE_RUNNING, psrc->query_string);
1536 set_ps_display("BIND", false);
1538 if (save_log_statement_stats)
1542 * Start up a transaction command so we can call functions etc. (Note that
1543 * this will normally change current memory context.) Nothing happens if
1544 * we are already in one. This also arms the statement timeout if
1547 start_xact_command();
1549 /* Switch back to message context */
1550 MemoryContextSwitchTo(MessageContext);
1552 /* Get the parameter format codes */
1553 numPFormats = pq_getmsgint(input_message, 2);
1554 if (numPFormats > 0)
1558 pformats = (int16 *) palloc(numPFormats * sizeof(int16));
1559 for (i = 0; i < numPFormats; i++)
1560 pformats[i] = pq_getmsgint(input_message, 2);
1563 /* Get the parameter value count */
1564 numParams = pq_getmsgint(input_message, 2);
1566 if (numPFormats > 1 && numPFormats != numParams)
1568 (errcode(ERRCODE_PROTOCOL_VIOLATION),
1569 errmsg("bind message has %d parameter formats but %d parameters",
1570 numPFormats, numParams)));
1572 if (numParams != psrc->num_params)
1574 (errcode(ERRCODE_PROTOCOL_VIOLATION),
1575 errmsg("bind message supplies %d parameters, but prepared statement \"%s\" requires %d",
1576 numParams, stmt_name, psrc->num_params)));
1579 * If we are in aborted transaction state, the only portals we can
1580 * actually run are those containing COMMIT or ROLLBACK commands. We
1581 * disallow binding anything else to avoid problems with infrastructure
1582 * that expects to run inside a valid transaction. We also disallow
1583 * binding any parameters, since we can't risk calling user-defined I/O
1586 if (IsAbortedTransactionBlockState() &&
1587 (!(psrc->raw_parse_tree &&
1588 IsTransactionExitStmt(psrc->raw_parse_tree->stmt)) ||
1591 (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
1592 errmsg("current transaction is aborted, "
1593 "commands ignored until end of transaction block"),
1594 errdetail_abort()));
1597 * Create the portal. Allow silent replacement of an existing portal only
1598 * if the unnamed portal is specified.
1600 if (portal_name[0] == '\0')
1601 portal = CreatePortal(portal_name, true, true);
1603 portal = CreatePortal(portal_name, false, false);
1606 * Prepare to copy stuff into the portal's memory context. We do all this
1607 * copying first, because it could possibly fail (out-of-memory) and we
1608 * don't want a failure to occur between GetCachedPlan and
1609 * PortalDefineQuery; that would result in leaking our plancache refcount.
1611 oldContext = MemoryContextSwitchTo(PortalGetHeapMemory(portal));
1613 /* Copy the plan's query string into the portal */
1614 query_string = pstrdup(psrc->query_string);
1616 /* Likewise make a copy of the statement name, unless it's unnamed */
1618 saved_stmt_name = pstrdup(stmt_name);
1620 saved_stmt_name = NULL;
1623 * Set a snapshot if we have parameters to fetch (since the input
1624 * functions might need it) or the query isn't a utility command (and
1625 * hence could require redoing parse analysis and planning). We keep the
1626 * snapshot active till we're done, so that plancache.c doesn't have to
1629 if (numParams > 0 ||
1630 (psrc->raw_parse_tree &&
1631 analyze_requires_snapshot(psrc->raw_parse_tree)))
1633 PushActiveSnapshot(GetTransactionSnapshot());
1634 snapshot_set = true;
1638 * Fetch parameters, if any, and store in the portal's memory context.
1644 params = (ParamListInfo) palloc(offsetof(ParamListInfoData, params) +
1645 numParams * sizeof(ParamExternData));
1646 /* we have static list of params, so no hooks needed */
1647 params->paramFetch = NULL;
1648 params->paramFetchArg = NULL;
1649 params->parserSetup = NULL;
1650 params->parserSetupArg = NULL;
1651 params->numParams = numParams;
1652 params->paramMask = NULL;
1654 for (paramno = 0; paramno < numParams; paramno++)
1656 Oid ptype = psrc->param_types[paramno];
1660 StringInfoData pbuf;
1664 plength = pq_getmsgint(input_message, 4);
1665 isNull = (plength == -1);
1669 const char *pvalue = pq_getmsgbytes(input_message, plength);
1672 * Rather than copying data around, we just set up a phony
1673 * StringInfo pointing to the correct portion of the message
1674 * buffer. We assume we can scribble on the message buffer so
1675 * as to maintain the convention that StringInfos have a
1676 * trailing null. This is grotty but is a big win when
1677 * dealing with very large parameter strings.
1679 pbuf.data = (char *) pvalue;
1680 pbuf.maxlen = plength + 1;
1684 csave = pbuf.data[plength];
1685 pbuf.data[plength] = '\0';
1689 pbuf.data = NULL; /* keep compiler quiet */
1693 if (numPFormats > 1)
1694 pformat = pformats[paramno];
1695 else if (numPFormats > 0)
1696 pformat = pformats[0];
1698 pformat = 0; /* default = text */
1700 if (pformat == 0) /* text mode */
1706 getTypeInputInfo(ptype, &typinput, &typioparam);
1709 * We have to do encoding conversion before calling the
1715 pstring = pg_client_to_server(pbuf.data, plength);
1717 pval = OidInputFunctionCall(typinput, pstring, typioparam, -1);
1719 /* Free result of encoding conversion, if any */
1720 if (pstring && pstring != pbuf.data)
1723 else if (pformat == 1) /* binary mode */
1730 * Call the parameter type's binary input converter
1732 getTypeBinaryInputInfo(ptype, &typreceive, &typioparam);
1739 pval = OidReceiveFunctionCall(typreceive, bufptr, typioparam, -1);
1741 /* Trouble if it didn't eat the whole buffer */
1742 if (!isNull && pbuf.cursor != pbuf.len)
1744 (errcode(ERRCODE_INVALID_BINARY_REPRESENTATION),
1745 errmsg("incorrect binary data format in bind parameter %d",
1751 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1752 errmsg("unsupported format code: %d",
1754 pval = 0; /* keep compiler quiet */
1757 /* Restore message buffer contents */
1759 pbuf.data[plength] = csave;
1761 params->params[paramno].value = pval;
1762 params->params[paramno].isnull = isNull;
1765 * We mark the params as CONST. This ensures that any custom plan
1766 * makes full use of the parameter values.
1768 params->params[paramno].pflags = PARAM_FLAG_CONST;
1769 params->params[paramno].ptype = ptype;
1775 /* Done storing stuff in portal's context */
1776 MemoryContextSwitchTo(oldContext);
1778 /* Get the result format codes */
1779 numRFormats = pq_getmsgint(input_message, 2);
1780 if (numRFormats > 0)
1784 rformats = (int16 *) palloc(numRFormats * sizeof(int16));
1785 for (i = 0; i < numRFormats; i++)
1786 rformats[i] = pq_getmsgint(input_message, 2);
1789 pq_getmsgend(input_message);
1792 * Obtain a plan from the CachedPlanSource. Any cruft from (re)planning
1793 * will be generated in MessageContext. The plan refcount will be
1794 * assigned to the Portal, so it will be released at portal destruction.
1796 cplan = GetCachedPlan(psrc, params, false, NULL);
1799 * Now we can define the portal.
1801 * DO NOT put any code that could possibly throw an error between the
1802 * above GetCachedPlan call and here.
1804 PortalDefineQuery(portal,
1811 /* Done with the snapshot used for parameter I/O and parsing/planning */
1813 PopActiveSnapshot();
1816 * And we're ready to start portal execution.
1818 PortalStart(portal, params, 0, InvalidSnapshot);
1821 * Apply the result format requests to the portal.
1823 PortalSetResultFormat(portal, numRFormats, rformats);
1826 * Send BindComplete.
1828 if (whereToSendOutput == DestRemote)
1829 pq_putemptymessage('2');
1832 * Emit duration logging if appropriate.
1834 switch (check_log_duration(msec_str, false))
1838 (errmsg("duration: %s ms", msec_str),
1839 errhidestmt(true)));
1843 (errmsg("duration: %s ms bind %s%s%s: %s",
1845 *stmt_name ? stmt_name : "<unnamed>",
1846 *portal_name ? "/" : "",
1847 *portal_name ? portal_name : "",
1848 psrc->query_string),
1850 errdetail_params(params)));
1854 if (save_log_statement_stats)
1855 ShowUsage("BIND MESSAGE STATISTICS");
1857 debug_query_string = NULL;
1861 * exec_execute_message
1863 * Process an "Execute" message for a portal
1866 exec_execute_message(const char *portal_name, long max_rows)
1869 DestReceiver *receiver;
1872 char completionTag[COMPLETION_TAG_BUFSIZE];
1873 const char *sourceText;
1874 const char *prepStmtName;
1875 ParamListInfo portalParams;
1876 bool save_log_statement_stats = log_statement_stats;
1877 bool is_xact_command;
1878 bool execute_is_fetch;
1879 bool was_logged = false;
1882 /* Adjust destination to tell printtup.c what to do */
1883 dest = whereToSendOutput;
1884 if (dest == DestRemote)
1885 dest = DestRemoteExecute;
1887 portal = GetPortalByName(portal_name);
1888 if (!PortalIsValid(portal))
1890 (errcode(ERRCODE_UNDEFINED_CURSOR),
1891 errmsg("portal \"%s\" does not exist", portal_name)));
1894 * If the original query was a null string, just return
1895 * EmptyQueryResponse.
1897 if (portal->commandTag == NULL)
1899 Assert(portal->stmts == NIL);
1904 /* Does the portal contain a transaction command? */
1905 is_xact_command = IsTransactionStmtList(portal->stmts);
1908 * We must copy the sourceText and prepStmtName into MessageContext in
1909 * case the portal is destroyed during finish_xact_command. Can avoid the
1910 * copy if it's not an xact command, though.
1912 if (is_xact_command)
1914 sourceText = pstrdup(portal->sourceText);
1915 if (portal->prepStmtName)
1916 prepStmtName = pstrdup(portal->prepStmtName);
1918 prepStmtName = "<unnamed>";
1921 * An xact command shouldn't have any parameters, which is a good
1922 * thing because they wouldn't be around after finish_xact_command.
1924 portalParams = NULL;
1928 sourceText = portal->sourceText;
1929 if (portal->prepStmtName)
1930 prepStmtName = portal->prepStmtName;
1932 prepStmtName = "<unnamed>";
1933 portalParams = portal->portalParams;
1937 * Report query to various monitoring facilities.
1939 debug_query_string = sourceText;
1941 pgstat_report_activity(STATE_RUNNING, sourceText);
1943 set_ps_display(portal->commandTag, false);
1945 if (save_log_statement_stats)
1948 BeginCommand(portal->commandTag, dest);
1951 * Create dest receiver in MessageContext (we don't want it in transaction
1952 * context, because that may get deleted if portal contains VACUUM).
1954 receiver = CreateDestReceiver(dest);
1955 if (dest == DestRemoteExecute)
1956 SetRemoteDestReceiverParams(receiver, portal);
1959 * Ensure we are in a transaction command (this should normally be the
1960 * case already due to prior BIND).
1962 start_xact_command();
1965 * If we re-issue an Execute protocol request against an existing portal,
1966 * then we are only fetching more rows rather than completely re-executing
1967 * the query from the start. atStart is never reset for a v3 portal, so we
1968 * are safe to use this check.
1970 execute_is_fetch = !portal->atStart;
1972 /* Log immediately if dictated by log_statement */
1973 if (check_log_statement(portal->stmts))
1976 (errmsg("%s %s%s%s: %s",
1978 _("execute fetch from") :
1981 *portal_name ? "/" : "",
1982 *portal_name ? portal_name : "",
1985 errdetail_params(portalParams)));
1990 * If we are in aborted transaction state, the only portals we can
1991 * actually run are those containing COMMIT or ROLLBACK commands.
1993 if (IsAbortedTransactionBlockState() &&
1994 !IsTransactionExitStmtList(portal->stmts))
1996 (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
1997 errmsg("current transaction is aborted, "
1998 "commands ignored until end of transaction block"),
1999 errdetail_abort()));
2001 /* Check for cancel signal before we start execution */
2002 CHECK_FOR_INTERRUPTS();
2005 * Okay to run the portal.
2008 max_rows = FETCH_ALL;
2010 completed = PortalRun(portal,
2012 true, /* always top level */
2013 !execute_is_fetch && max_rows == FETCH_ALL,
2018 receiver->rDestroy(receiver);
2022 if (is_xact_command)
2025 * If this was a transaction control statement, commit it. We
2026 * will start a new xact command for the next command (if any).
2028 finish_xact_command();
2033 * We need a CommandCounterIncrement after every query, except
2034 * those that start or end a transaction block.
2036 CommandCounterIncrement();
2038 /* full command has been executed, reset timeout */
2039 disable_statement_timeout();
2042 /* Send appropriate CommandComplete to client */
2043 EndCommand(completionTag, dest);
2047 /* Portal run not complete, so send PortalSuspended */
2048 if (whereToSendOutput == DestRemote)
2049 pq_putemptymessage('s');
2053 * Emit duration logging if appropriate.
2055 switch (check_log_duration(msec_str, was_logged))
2059 (errmsg("duration: %s ms", msec_str),
2060 errhidestmt(true)));
2064 (errmsg("duration: %s ms %s %s%s%s: %s",
2067 _("execute fetch from") :
2070 *portal_name ? "/" : "",
2071 *portal_name ? portal_name : "",
2074 errdetail_params(portalParams)));
2078 if (save_log_statement_stats)
2079 ShowUsage("EXECUTE MESSAGE STATISTICS");
2081 debug_query_string = NULL;
2085 * check_log_statement
2086 * Determine whether command should be logged because of log_statement
2088 * stmt_list can be either raw grammar output or a list of planned
2092 check_log_statement(List *stmt_list)
2094 ListCell *stmt_item;
2096 if (log_statement == LOGSTMT_NONE)
2098 if (log_statement == LOGSTMT_ALL)
2101 /* Else we have to inspect the statement(s) to see whether to log */
2102 foreach(stmt_item, stmt_list)
2104 Node *stmt = (Node *) lfirst(stmt_item);
2106 if (GetCommandLogLevel(stmt) <= log_statement)
2114 * check_log_duration
2115 * Determine whether current command's duration should be logged
2118 * 0 if no logging is needed
2119 * 1 if just the duration should be logged
2120 * 2 if duration and query details should be logged
2122 * If logging is needed, the duration in msec is formatted into msec_str[],
2123 * which must be a 32-byte buffer.
2125 * was_logged should be true if caller already logged query details (this
2126 * essentially prevents 2 from being returned).
2129 check_log_duration(char *msec_str, bool was_logged)
2131 if (log_duration || log_min_duration_statement >= 0)
2138 TimestampDifference(GetCurrentStatementStartTimestamp(),
2139 GetCurrentTimestamp(),
2141 msecs = usecs / 1000;
2144 * This odd-looking test for log_min_duration_statement being exceeded
2145 * is designed to avoid integer overflow with very long durations:
2146 * don't compute secs * 1000 until we've verified it will fit in int.
2148 exceeded = (log_min_duration_statement == 0 ||
2149 (log_min_duration_statement > 0 &&
2150 (secs > log_min_duration_statement / 1000 ||
2151 secs * 1000 + msecs >= log_min_duration_statement)));
2153 if (exceeded || log_duration)
2155 snprintf(msec_str, 32, "%ld.%03d",
2156 secs * 1000 + msecs, usecs % 1000);
2157 if (exceeded && !was_logged)
2170 * Add an errdetail() line showing the query referenced by an EXECUTE, if any.
2171 * The argument is the raw parsetree list.
2174 errdetail_execute(List *raw_parsetree_list)
2176 ListCell *parsetree_item;
2178 foreach(parsetree_item, raw_parsetree_list)
2180 RawStmt *parsetree = lfirst_node(RawStmt, parsetree_item);
2182 if (IsA(parsetree->stmt, ExecuteStmt))
2184 ExecuteStmt *stmt = (ExecuteStmt *) parsetree->stmt;
2185 PreparedStatement *pstmt;
2187 pstmt = FetchPreparedStatement(stmt->name, false);
2190 errdetail("prepare: %s", pstmt->plansource->query_string);
2202 * Add an errdetail() line showing bind-parameter data, if available.
2205 errdetail_params(ParamListInfo params)
2207 /* We mustn't call user-defined I/O functions when in an aborted xact */
2208 if (params && params->numParams > 0 && !IsAbortedTransactionBlockState())
2210 StringInfoData param_str;
2211 MemoryContext oldcontext;
2214 /* Make sure any trash is generated in MessageContext */
2215 oldcontext = MemoryContextSwitchTo(MessageContext);
2217 initStringInfo(¶m_str);
2219 for (paramno = 0; paramno < params->numParams; paramno++)
2221 ParamExternData *prm = ¶ms->params[paramno];
2227 appendStringInfo(¶m_str, "%s$%d = ",
2228 paramno > 0 ? ", " : "",
2231 if (prm->isnull || !OidIsValid(prm->ptype))
2233 appendStringInfoString(¶m_str, "NULL");
2237 getTypeOutputInfo(prm->ptype, &typoutput, &typisvarlena);
2239 pstring = OidOutputFunctionCall(typoutput, prm->value);
2241 appendStringInfoCharMacro(¶m_str, '\'');
2242 for (p = pstring; *p; p++)
2244 if (*p == '\'') /* double single quotes */
2245 appendStringInfoCharMacro(¶m_str, *p);
2246 appendStringInfoCharMacro(¶m_str, *p);
2248 appendStringInfoCharMacro(¶m_str, '\'');
2253 errdetail("parameters: %s", param_str.data);
2255 pfree(param_str.data);
2257 MemoryContextSwitchTo(oldcontext);
2266 * Add an errdetail() line showing abort reason, if any.
2269 errdetail_abort(void)
2271 if (MyProc->recoveryConflictPending)
2272 errdetail("abort reason: recovery conflict");
2278 * errdetail_recovery_conflict
2280 * Add an errdetail() line showing conflict source.
2283 errdetail_recovery_conflict(void)
2285 switch (RecoveryConflictReason)
2287 case PROCSIG_RECOVERY_CONFLICT_BUFFERPIN:
2288 errdetail("User was holding shared buffer pin for too long.");
2290 case PROCSIG_RECOVERY_CONFLICT_LOCK:
2291 errdetail("User was holding a relation lock for too long.");
2293 case PROCSIG_RECOVERY_CONFLICT_TABLESPACE:
2294 errdetail("User was or might have been using tablespace that must be dropped.");
2296 case PROCSIG_RECOVERY_CONFLICT_SNAPSHOT:
2297 errdetail("User query might have needed to see row versions that must be removed.");
2299 case PROCSIG_RECOVERY_CONFLICT_STARTUP_DEADLOCK:
2300 errdetail("User transaction caused buffer deadlock with recovery.");
2302 case PROCSIG_RECOVERY_CONFLICT_DATABASE:
2303 errdetail("User was connected to a database that must be dropped.");
2314 * exec_describe_statement_message
2316 * Process a "Describe" message for a prepared statement
2319 exec_describe_statement_message(const char *stmt_name)
2321 CachedPlanSource *psrc;
2325 * Start up a transaction command. (Note that this will normally change
2326 * current memory context.) Nothing happens if we are already in one.
2328 start_xact_command();
2330 /* Switch back to message context */
2331 MemoryContextSwitchTo(MessageContext);
2333 /* Find prepared statement */
2334 if (stmt_name[0] != '\0')
2336 PreparedStatement *pstmt;
2338 pstmt = FetchPreparedStatement(stmt_name, true);
2339 psrc = pstmt->plansource;
2343 /* special-case the unnamed statement */
2344 psrc = unnamed_stmt_psrc;
2347 (errcode(ERRCODE_UNDEFINED_PSTATEMENT),
2348 errmsg("unnamed prepared statement does not exist")));
2351 /* Prepared statements shouldn't have changeable result descs */
2352 Assert(psrc->fixed_result);
2355 * If we are in aborted transaction state, we can't run
2356 * SendRowDescriptionMessage(), because that needs catalog accesses.
2357 * Hence, refuse to Describe statements that return data. (We shouldn't
2358 * just refuse all Describes, since that might break the ability of some
2359 * clients to issue COMMIT or ROLLBACK commands, if they use code that
2360 * blindly Describes whatever it does.) We can Describe parameters
2361 * without doing anything dangerous, so we don't restrict that.
2363 if (IsAbortedTransactionBlockState() &&
2366 (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
2367 errmsg("current transaction is aborted, "
2368 "commands ignored until end of transaction block"),
2369 errdetail_abort()));
2371 if (whereToSendOutput != DestRemote)
2372 return; /* can't actually do anything... */
2375 * First describe the parameters...
2377 pq_beginmessage_reuse(&row_description_buf, 't'); /* parameter description
2379 pq_sendint16(&row_description_buf, psrc->num_params);
2381 for (i = 0; i < psrc->num_params; i++)
2383 Oid ptype = psrc->param_types[i];
2385 pq_sendint32(&row_description_buf, (int) ptype);
2387 pq_endmessage_reuse(&row_description_buf);
2390 * Next send RowDescription or NoData to describe the result...
2392 if (psrc->resultDesc)
2396 /* Get the plan's primary targetlist */
2397 tlist = CachedPlanGetTargetList(psrc, NULL);
2399 SendRowDescriptionMessage(&row_description_buf,
2405 pq_putemptymessage('n'); /* NoData */
2410 * exec_describe_portal_message
2412 * Process a "Describe" message for a portal
2415 exec_describe_portal_message(const char *portal_name)
2420 * Start up a transaction command. (Note that this will normally change
2421 * current memory context.) Nothing happens if we are already in one.
2423 start_xact_command();
2425 /* Switch back to message context */
2426 MemoryContextSwitchTo(MessageContext);
2428 portal = GetPortalByName(portal_name);
2429 if (!PortalIsValid(portal))
2431 (errcode(ERRCODE_UNDEFINED_CURSOR),
2432 errmsg("portal \"%s\" does not exist", portal_name)));
2435 * If we are in aborted transaction state, we can't run
2436 * SendRowDescriptionMessage(), because that needs catalog accesses.
2437 * Hence, refuse to Describe portals that return data. (We shouldn't just
2438 * refuse all Describes, since that might break the ability of some
2439 * clients to issue COMMIT or ROLLBACK commands, if they use code that
2440 * blindly Describes whatever it does.)
2442 if (IsAbortedTransactionBlockState() &&
2445 (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
2446 errmsg("current transaction is aborted, "
2447 "commands ignored until end of transaction block"),
2448 errdetail_abort()));
2450 if (whereToSendOutput != DestRemote)
2451 return; /* can't actually do anything... */
2453 if (portal->tupDesc)
2454 SendRowDescriptionMessage(&row_description_buf,
2456 FetchPortalTargetList(portal),
2459 pq_putemptymessage('n'); /* NoData */
2464 * Convenience routines for starting/committing a single command.
2467 start_xact_command(void)
2471 StartTransactionCommand();
2473 xact_started = true;
2477 * Start statement timeout if necessary. Note that this'll intentionally
2478 * not reset the clock on an already started timeout, to avoid the timing
2479 * overhead when start_xact_command() is invoked repeatedly, without an
2480 * interceding finish_xact_command() (e.g. parse/bind/execute). If that's
2481 * not desired, the timeout has to be disabled explicitly.
2483 enable_statement_timeout();
2487 finish_xact_command(void)
2489 /* cancel active statement timeout after each command */
2490 disable_statement_timeout();
2494 CommitTransactionCommand();
2496 #ifdef MEMORY_CONTEXT_CHECKING
2497 /* Check all memory contexts that weren't freed during commit */
2498 /* (those that were, were checked before being deleted) */
2499 MemoryContextCheck(TopMemoryContext);
2502 #ifdef SHOW_MEMORY_STATS
2503 /* Print mem stats after each commit for leak tracking */
2504 MemoryContextStats(TopMemoryContext);
2507 xact_started = false;
2513 * Convenience routines for checking whether a statement is one of the
2514 * ones that we allow in transaction-aborted state.
2517 /* Test a bare parsetree */
2519 IsTransactionExitStmt(Node *parsetree)
2521 if (parsetree && IsA(parsetree, TransactionStmt))
2523 TransactionStmt *stmt = (TransactionStmt *) parsetree;
2525 if (stmt->kind == TRANS_STMT_COMMIT ||
2526 stmt->kind == TRANS_STMT_PREPARE ||
2527 stmt->kind == TRANS_STMT_ROLLBACK ||
2528 stmt->kind == TRANS_STMT_ROLLBACK_TO)
2534 /* Test a list that contains PlannedStmt nodes */
2536 IsTransactionExitStmtList(List *pstmts)
2538 if (list_length(pstmts) == 1)
2540 PlannedStmt *pstmt = linitial_node(PlannedStmt, pstmts);
2542 if (pstmt->commandType == CMD_UTILITY &&
2543 IsTransactionExitStmt(pstmt->utilityStmt))
2549 /* Test a list that contains PlannedStmt nodes */
2551 IsTransactionStmtList(List *pstmts)
2553 if (list_length(pstmts) == 1)
2555 PlannedStmt *pstmt = linitial_node(PlannedStmt, pstmts);
2557 if (pstmt->commandType == CMD_UTILITY &&
2558 IsA(pstmt->utilityStmt, TransactionStmt))
2564 /* Release any existing unnamed prepared statement */
2566 drop_unnamed_stmt(void)
2568 /* paranoia to avoid a dangling pointer in case of error */
2569 if (unnamed_stmt_psrc)
2571 CachedPlanSource *psrc = unnamed_stmt_psrc;
2573 unnamed_stmt_psrc = NULL;
2574 DropCachedPlan(psrc);
2579 /* --------------------------------
2580 * signal handler routines used in PostgresMain()
2581 * --------------------------------
2585 * quickdie() occurs when signalled SIGQUIT by the postmaster.
2587 * Some backend has bought the farm,
2588 * so we need to stop what we're doing and exit.
2591 quickdie(SIGNAL_ARGS)
2593 sigaddset(&BlockSig, SIGQUIT); /* prevent nested calls */
2594 PG_SETMASK(&BlockSig);
2597 * Prevent interrupts while exiting; though we just blocked signals that
2598 * would queue new interrupts, one may have been pending. We don't want a
2599 * quickdie() downgraded to a mere query cancel.
2604 * If we're aborting out of client auth, don't risk trying to send
2605 * anything to the client; we will likely violate the protocol, not to
2606 * mention that we may have interrupted the guts of OpenSSL or some
2607 * authentication library.
2609 if (ClientAuthInProgress && whereToSendOutput == DestRemote)
2610 whereToSendOutput = DestNone;
2613 * Ideally this should be ereport(FATAL), but then we'd not get control
2617 (errcode(ERRCODE_CRASH_SHUTDOWN),
2618 errmsg("terminating connection because of crash of another server process"),
2619 errdetail("The postmaster has commanded this server process to roll back"
2620 " the current transaction and exit, because another"
2621 " server process exited abnormally and possibly corrupted"
2623 errhint("In a moment you should be able to reconnect to the"
2624 " database and repeat your command.")));
2627 * We DO NOT want to run proc_exit() callbacks -- we're here because
2628 * shared memory may be corrupted, so we don't want to try to clean up our
2629 * transaction. Just nail the windows shut and get out of town. Now that
2630 * there's an atexit callback to prevent third-party code from breaking
2631 * things by calling exit() directly, we have to reset the callbacks
2632 * explicitly to make this work as intended.
2637 * Note we do exit(2) not exit(0). This is to force the postmaster into a
2638 * system reset cycle if some idiot DBA sends a manual SIGQUIT to a random
2639 * backend. This is necessary precisely because we don't clean up our
2640 * shared memory state. (The "dead man switch" mechanism in pmsignal.c
2641 * should ensure the postmaster sees this as a crash, too, but no harm in
2642 * being doubly sure.)
2648 * Shutdown signal from postmaster: abort transaction and exit
2649 * at soonest convenient time
2654 int save_errno = errno;
2656 /* Don't joggle the elbow of proc_exit */
2657 if (!proc_exit_inprogress)
2659 InterruptPending = true;
2660 ProcDiePending = true;
2663 /* If we're still here, waken anything waiting on the process latch */
2667 * If we're in single user mode, we want to quit immediately - we can't
2668 * rely on latches as they wouldn't work when stdin/stdout is a file.
2669 * Rather ugly, but it's unlikely to be worthwhile to invest much more
2670 * effort just for the benefit of single user mode.
2672 if (DoingCommandRead && whereToSendOutput != DestRemote)
2673 ProcessInterrupts();
2679 * Query-cancel signal from postmaster: abort current transaction
2680 * at soonest convenient time
2683 StatementCancelHandler(SIGNAL_ARGS)
2685 int save_errno = errno;
2688 * Don't joggle the elbow of proc_exit
2690 if (!proc_exit_inprogress)
2692 InterruptPending = true;
2693 QueryCancelPending = true;
2696 /* If we're still here, waken anything waiting on the process latch */
2702 /* signal handler for floating point exception */
2704 FloatExceptionHandler(SIGNAL_ARGS)
2706 /* We're not returning, so no need to save errno */
2708 (errcode(ERRCODE_FLOATING_POINT_EXCEPTION),
2709 errmsg("floating-point exception"),
2710 errdetail("An invalid floating-point operation was signaled. "
2711 "This probably means an out-of-range result or an "
2712 "invalid operation, such as division by zero.")));
2716 * SIGHUP: set flag to re-read config file at next convenient time.
2718 * Sets the ConfigReloadPending flag, which should be checked at convenient
2719 * places inside main loops. (Better than doing the reading in the signal
2723 PostgresSigHupHandler(SIGNAL_ARGS)
2725 int save_errno = errno;
2727 ConfigReloadPending = true;
2734 * RecoveryConflictInterrupt: out-of-line portion of recovery conflict
2735 * handling following receipt of SIGUSR1. Designed to be similar to die()
2736 * and StatementCancelHandler(). Called only by a normal user backend
2737 * that begins a transaction during recovery.
2740 RecoveryConflictInterrupt(ProcSignalReason reason)
2742 int save_errno = errno;
2745 * Don't joggle the elbow of proc_exit
2747 if (!proc_exit_inprogress)
2749 RecoveryConflictReason = reason;
2752 case PROCSIG_RECOVERY_CONFLICT_STARTUP_DEADLOCK:
2755 * If we aren't waiting for a lock we can never deadlock.
2757 if (!IsWaitingForLock())
2760 /* Intentional drop through to check wait for pin */
2762 case PROCSIG_RECOVERY_CONFLICT_BUFFERPIN:
2765 * If we aren't blocking the Startup process there is nothing
2768 if (!HoldingBufferPinThatDelaysRecovery())
2771 MyProc->recoveryConflictPending = true;
2773 /* Intentional drop through to error handling */
2775 case PROCSIG_RECOVERY_CONFLICT_LOCK:
2776 case PROCSIG_RECOVERY_CONFLICT_TABLESPACE:
2777 case PROCSIG_RECOVERY_CONFLICT_SNAPSHOT:
2780 * If we aren't in a transaction any longer then ignore.
2782 if (!IsTransactionOrTransactionBlock())
2786 * If we can abort just the current subtransaction then we are
2787 * OK to throw an ERROR to resolve the conflict. Otherwise
2788 * drop through to the FATAL case.
2790 * XXX other times that we can throw just an ERROR *may* be
2791 * PROCSIG_RECOVERY_CONFLICT_LOCK if no locks are held in
2792 * parent transactions
2794 * PROCSIG_RECOVERY_CONFLICT_SNAPSHOT if no snapshots are held
2795 * by parent transactions and the transaction is not
2796 * transaction-snapshot mode
2798 * PROCSIG_RECOVERY_CONFLICT_TABLESPACE if no temp files or
2799 * cursors open in parent transactions
2801 if (!IsSubTransaction())
2804 * If we already aborted then we no longer need to cancel.
2805 * We do this here since we do not wish to ignore aborted
2806 * subtransactions, which must cause FATAL, currently.
2808 if (IsAbortedTransactionBlockState())
2811 RecoveryConflictPending = true;
2812 QueryCancelPending = true;
2813 InterruptPending = true;
2817 /* Intentional drop through to session cancel */
2819 case PROCSIG_RECOVERY_CONFLICT_DATABASE:
2820 RecoveryConflictPending = true;
2821 ProcDiePending = true;
2822 InterruptPending = true;
2826 elog(FATAL, "unrecognized conflict mode: %d",
2830 Assert(RecoveryConflictPending && (QueryCancelPending || ProcDiePending));
2833 * All conflicts apart from database cause dynamic errors where the
2834 * command or transaction can be retried at a later point with some
2835 * potential for success. No need to reset this, since non-retryable
2836 * conflict errors are currently FATAL.
2838 if (reason == PROCSIG_RECOVERY_CONFLICT_DATABASE)
2839 RecoveryConflictRetryable = false;
2843 * Set the process latch. This function essentially emulates signal
2844 * handlers like die() and StatementCancelHandler() and it seems prudent
2845 * to behave similarly as they do.
2853 * ProcessInterrupts: out-of-line portion of CHECK_FOR_INTERRUPTS() macro
2855 * If an interrupt condition is pending, and it's safe to service it,
2856 * then clear the flag and accept the interrupt. Called only when
2857 * InterruptPending is true.
2860 ProcessInterrupts(void)
2862 /* OK to accept any interrupts now? */
2863 if (InterruptHoldoffCount != 0 || CritSectionCount != 0)
2865 InterruptPending = false;
2869 ProcDiePending = false;
2870 QueryCancelPending = false; /* ProcDie trumps QueryCancel */
2872 /* As in quickdie, don't risk sending to client during auth */
2873 if (ClientAuthInProgress && whereToSendOutput == DestRemote)
2874 whereToSendOutput = DestNone;
2875 if (ClientAuthInProgress)
2877 (errcode(ERRCODE_QUERY_CANCELED),
2878 errmsg("canceling authentication due to timeout")));
2879 else if (IsAutoVacuumWorkerProcess())
2881 (errcode(ERRCODE_ADMIN_SHUTDOWN),
2882 errmsg("terminating autovacuum process due to administrator command")));
2883 else if (IsLogicalWorker())
2885 (errcode(ERRCODE_ADMIN_SHUTDOWN),
2886 errmsg("terminating logical replication worker due to administrator command")));
2887 else if (IsLogicalLauncher())
2890 (errmsg("logical replication launcher shutting down")));
2893 * The logical replication launcher can be stopped at any time.
2894 * Use exit status 1 so the background worker is restarted.
2898 else if (RecoveryConflictPending && RecoveryConflictRetryable)
2900 pgstat_report_recovery_conflict(RecoveryConflictReason);
2902 (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
2903 errmsg("terminating connection due to conflict with recovery"),
2904 errdetail_recovery_conflict()));
2906 else if (RecoveryConflictPending)
2908 /* Currently there is only one non-retryable recovery conflict */
2909 Assert(RecoveryConflictReason == PROCSIG_RECOVERY_CONFLICT_DATABASE);
2910 pgstat_report_recovery_conflict(RecoveryConflictReason);
2912 (errcode(ERRCODE_DATABASE_DROPPED),
2913 errmsg("terminating connection due to conflict with recovery"),
2914 errdetail_recovery_conflict()));
2918 (errcode(ERRCODE_ADMIN_SHUTDOWN),
2919 errmsg("terminating connection due to administrator command")));
2921 if (ClientConnectionLost)
2923 QueryCancelPending = false; /* lost connection trumps QueryCancel */
2925 /* don't send to client, we already know the connection to be dead. */
2926 whereToSendOutput = DestNone;
2928 (errcode(ERRCODE_CONNECTION_FAILURE),
2929 errmsg("connection to client lost")));
2933 * If a recovery conflict happens while we are waiting for input from the
2934 * client, the client is presumably just sitting idle in a transaction,
2935 * preventing recovery from making progress. Terminate the connection to
2938 if (RecoveryConflictPending && DoingCommandRead)
2940 QueryCancelPending = false; /* this trumps QueryCancel */
2941 RecoveryConflictPending = false;
2943 pgstat_report_recovery_conflict(RecoveryConflictReason);
2945 (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
2946 errmsg("terminating connection due to conflict with recovery"),
2947 errdetail_recovery_conflict(),
2948 errhint("In a moment you should be able to reconnect to the"
2949 " database and repeat your command.")));
2953 * Don't allow query cancel interrupts while reading input from the
2954 * client, because we might lose sync in the FE/BE protocol. (Die
2955 * interrupts are OK, because we won't read any further messages from
2956 * the client in that case.)
2958 if (QueryCancelPending && QueryCancelHoldoffCount != 0)
2961 * Re-arm InterruptPending so that we process the cancel request
2962 * as soon as we're done reading the message.
2964 InterruptPending = true;
2966 else if (QueryCancelPending)
2968 bool lock_timeout_occurred;
2969 bool stmt_timeout_occurred;
2971 QueryCancelPending = false;
2974 * If LOCK_TIMEOUT and STATEMENT_TIMEOUT indicators are both set, we
2975 * need to clear both, so always fetch both.
2977 lock_timeout_occurred = get_timeout_indicator(LOCK_TIMEOUT, true);
2978 stmt_timeout_occurred = get_timeout_indicator(STATEMENT_TIMEOUT, true);
2981 * If both were set, we want to report whichever timeout completed
2982 * earlier; this ensures consistent behavior if the machine is slow
2983 * enough that the second timeout triggers before we get here. A tie
2984 * is arbitrarily broken in favor of reporting a lock timeout.
2986 if (lock_timeout_occurred && stmt_timeout_occurred &&
2987 get_timeout_finish_time(STATEMENT_TIMEOUT) < get_timeout_finish_time(LOCK_TIMEOUT))
2988 lock_timeout_occurred = false; /* report stmt timeout */
2990 if (lock_timeout_occurred)
2994 (errcode(ERRCODE_LOCK_NOT_AVAILABLE),
2995 errmsg("canceling statement due to lock timeout")));
2997 if (stmt_timeout_occurred)
3001 (errcode(ERRCODE_QUERY_CANCELED),
3002 errmsg("canceling statement due to statement timeout")));
3004 if (IsAutoVacuumWorkerProcess())
3008 (errcode(ERRCODE_QUERY_CANCELED),
3009 errmsg("canceling autovacuum task")));
3011 if (RecoveryConflictPending)
3013 RecoveryConflictPending = false;
3015 pgstat_report_recovery_conflict(RecoveryConflictReason);
3017 (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
3018 errmsg("canceling statement due to conflict with recovery"),
3019 errdetail_recovery_conflict()));
3023 * If we are reading a command from the client, just ignore the cancel
3024 * request --- sending an extra error message won't accomplish
3025 * anything. Otherwise, go ahead and throw the error.
3027 if (!DoingCommandRead)
3031 (errcode(ERRCODE_QUERY_CANCELED),
3032 errmsg("canceling statement due to user request")));
3036 if (IdleInTransactionSessionTimeoutPending)
3038 /* Has the timeout setting changed since last we looked? */
3039 if (IdleInTransactionSessionTimeout > 0)
3041 (errcode(ERRCODE_IDLE_IN_TRANSACTION_SESSION_TIMEOUT),
3042 errmsg("terminating connection due to idle-in-transaction timeout")));
3044 IdleInTransactionSessionTimeoutPending = false;
3048 if (ParallelMessagePending)
3049 HandleParallelMessages();
3054 * IA64-specific code to fetch the AR.BSP register for stack depth checks.
3056 * We currently support gcc, icc, and HP-UX's native compiler here.
3058 * Note: while icc accepts gcc asm blocks on x86[_64], this is not true on
3059 * ia64 (at least not in icc versions before 12.x). So we have to carry a
3060 * separate implementation for it.
3062 #if defined(__ia64__) || defined(__ia64)
3064 #if defined(__hpux) && !defined(__GNUC__) && !defined(__INTEL_COMPILER)
3065 /* Assume it's HP-UX native compiler */
3066 #include <ia64/sys/inline.h>
3067 #define ia64_get_bsp() ((char *) (_Asm_mov_from_ar(_AREG_BSP, _NO_FENCE)))
3068 #elif defined(__INTEL_COMPILER)
3070 #include <asm/ia64regs.h>
3071 #define ia64_get_bsp() ((char *) __getReg(_IA64_REG_AR_BSP))
3074 static __inline__ char *
3079 /* the ;; is a "stop", seems to be required before fetching BSP */
3080 __asm__ __volatile__(
3092 * set_stack_base: set up reference point for stack depth checking
3094 * Returns the old reference point, if any.
3097 set_stack_base(void)
3100 pg_stack_base_t old;
3102 #if defined(__ia64__) || defined(__ia64)
3103 old.stack_base_ptr = stack_base_ptr;
3104 old.register_stack_base_ptr = register_stack_base_ptr;
3106 old = stack_base_ptr;
3109 /* Set up reference point for stack depth checking */
3110 stack_base_ptr = &stack_base;
3111 #if defined(__ia64__) || defined(__ia64)
3112 register_stack_base_ptr = ia64_get_bsp();
3119 * restore_stack_base: restore reference point for stack depth checking
3121 * This can be used after set_stack_base() to restore the old value. This
3122 * is currently only used in PL/Java. When PL/Java calls a backend function
3123 * from different thread, the thread's stack is at a different location than
3124 * the main thread's stack, so it sets the base pointer before the call, and
3125 * restores it afterwards.
3128 restore_stack_base(pg_stack_base_t base)
3130 #if defined(__ia64__) || defined(__ia64)
3131 stack_base_ptr = base.stack_base_ptr;
3132 register_stack_base_ptr = base.register_stack_base_ptr;
3134 stack_base_ptr = base;
3139 * check_stack_depth/stack_is_too_deep: check for excessively deep recursion
3141 * This should be called someplace in any recursive routine that might possibly
3142 * recurse deep enough to overflow the stack. Most Unixen treat stack
3143 * overflow as an unrecoverable SIGSEGV, so we want to error out ourselves
3144 * before hitting the hardware limit.
3146 * check_stack_depth() just throws an error summarily. stack_is_too_deep()
3147 * can be used by code that wants to handle the error condition itself.
3150 check_stack_depth(void)
3152 if (stack_is_too_deep())
3155 (errcode(ERRCODE_STATEMENT_TOO_COMPLEX),
3156 errmsg("stack depth limit exceeded"),
3157 errhint("Increase the configuration parameter \"max_stack_depth\" (currently %dkB), "
3158 "after ensuring the platform's stack depth limit is adequate.",
3164 stack_is_too_deep(void)
3170 * Compute distance from reference point to my local variables
3172 stack_depth = (long) (stack_base_ptr - &stack_top_loc);
3175 * Take abs value, since stacks grow up on some machines, down on others
3177 if (stack_depth < 0)
3178 stack_depth = -stack_depth;
3183 * The test on stack_base_ptr prevents us from erroring out if called
3184 * during process setup or in a non-backend process. Logically it should
3185 * be done first, but putting it here avoids wasting cycles during normal
3188 if (stack_depth > max_stack_depth_bytes &&
3189 stack_base_ptr != NULL)
3193 * On IA64 there is a separate "register" stack that requires its own
3194 * independent check. For this, we have to measure the change in the
3195 * "BSP" pointer from PostgresMain to here. Logic is just as above,
3196 * except that we know IA64's register stack grows up.
3198 * Note we assume that the same max_stack_depth applies to both stacks.
3200 #if defined(__ia64__) || defined(__ia64)
3201 stack_depth = (long) (ia64_get_bsp() - register_stack_base_ptr);
3203 if (stack_depth > max_stack_depth_bytes &&
3204 register_stack_base_ptr != NULL)
3211 /* GUC check hook for max_stack_depth */
3213 check_max_stack_depth(int *newval, void **extra, GucSource source)
3215 long newval_bytes = *newval * 1024L;
3216 long stack_rlimit = get_stack_depth_rlimit();
3218 if (stack_rlimit > 0 && newval_bytes > stack_rlimit - STACK_DEPTH_SLOP)
3220 GUC_check_errdetail("\"max_stack_depth\" must not exceed %ldkB.",
3221 (stack_rlimit - STACK_DEPTH_SLOP) / 1024L);
3222 GUC_check_errhint("Increase the platform's stack depth limit via \"ulimit -s\" or local equivalent.");
3228 /* GUC assign hook for max_stack_depth */
3230 assign_max_stack_depth(int newval, void *extra)
3232 long newval_bytes = newval * 1024L;
3234 max_stack_depth_bytes = newval_bytes;
3239 * set_debug_options --- apply "-d N" command line option
3241 * -d is not quite the same as setting log_min_messages because it enables
3242 * other output options.
3245 set_debug_options(int debug_flag, GucContext context, GucSource source)
3251 sprintf(debugstr, "debug%d", debug_flag);
3252 SetConfigOption("log_min_messages", debugstr, context, source);
3255 SetConfigOption("log_min_messages", "notice", context, source);
3257 if (debug_flag >= 1 && context == PGC_POSTMASTER)
3259 SetConfigOption("log_connections", "true", context, source);
3260 SetConfigOption("log_disconnections", "true", context, source);
3262 if (debug_flag >= 2)
3263 SetConfigOption("log_statement", "all", context, source);
3264 if (debug_flag >= 3)
3265 SetConfigOption("debug_print_parse", "true", context, source);
3266 if (debug_flag >= 4)
3267 SetConfigOption("debug_print_plan", "true", context, source);
3268 if (debug_flag >= 5)
3269 SetConfigOption("debug_print_rewritten", "true", context, source);
3274 set_plan_disabling_options(const char *arg, GucContext context, GucSource source)
3276 const char *tmp = NULL;
3280 case 's': /* seqscan */
3281 tmp = "enable_seqscan";
3283 case 'i': /* indexscan */
3284 tmp = "enable_indexscan";
3286 case 'o': /* indexonlyscan */
3287 tmp = "enable_indexonlyscan";
3289 case 'b': /* bitmapscan */
3290 tmp = "enable_bitmapscan";
3292 case 't': /* tidscan */
3293 tmp = "enable_tidscan";
3295 case 'n': /* nestloop */
3296 tmp = "enable_nestloop";
3298 case 'm': /* mergejoin */
3299 tmp = "enable_mergejoin";
3301 case 'h': /* hashjoin */
3302 tmp = "enable_hashjoin";
3307 SetConfigOption(tmp, "false", context, source);
3316 get_stats_option_name(const char *arg)
3321 if (optarg[1] == 'a') /* "parser" */
3322 return "log_parser_stats";
3323 else if (optarg[1] == 'l') /* "planner" */
3324 return "log_planner_stats";
3327 case 'e': /* "executor" */
3328 return "log_executor_stats";
3336 /* ----------------------------------------------------------------
3337 * process_postgres_switches
3338 * Parse command line arguments for PostgresMain
3340 * This is called twice, once for the "secure" options coming from the
3341 * postmaster or command line, and once for the "insecure" options coming
3342 * from the client's startup packet. The latter have the same syntax but
3343 * may be restricted in what they can do.
3345 * argv[0] is ignored in either case (it's assumed to be the program name).
3347 * ctx is PGC_POSTMASTER for secure options, PGC_BACKEND for insecure options
3348 * coming from the client, or PGC_SU_BACKEND for insecure options coming from
3349 * a superuser client.
3351 * If a database name is present in the command line arguments, it's
3352 * returned into *dbname (this is allowed only if *dbname is initially NULL).
3353 * ----------------------------------------------------------------
3356 process_postgres_switches(int argc, char *argv[], GucContext ctx,
3357 const char **dbname)
3359 bool secure = (ctx == PGC_POSTMASTER);
3361 GucSource gucsource;
3366 gucsource = PGC_S_ARGV; /* switches came from command line */
3368 /* Ignore the initial --single argument, if present */
3369 if (argc > 1 && strcmp(argv[1], "--single") == 0)
3377 gucsource = PGC_S_CLIENT; /* switches came from client */
3380 #ifdef HAVE_INT_OPTERR
3383 * Turn this off because it's either printed to stderr and not the log
3384 * where we'd want it, or argv[0] is now "--single", which would make for
3385 * a weird error message. We print our own error message below.
3391 * Parse command-line options. CAUTION: keep this in sync with
3392 * postmaster/postmaster.c (the option sets should not conflict) and with
3393 * the common help() function in main/main.c.
3395 while ((flag = getopt(argc, argv, "B:bc:C:D:d:EeFf:h:ijk:lN:nOo:Pp:r:S:sTt:v:W:-:")) != -1)
3400 SetConfigOption("shared_buffers", optarg, ctx, gucsource);
3404 /* Undocumented flag used for binary upgrades */
3406 IsBinaryUpgrade = true;
3410 /* ignored for consistency with the postmaster */
3415 userDoption = strdup(optarg);
3419 set_debug_options(atoi(optarg), ctx, gucsource);
3428 SetConfigOption("datestyle", "euro", ctx, gucsource);
3432 SetConfigOption("fsync", "false", ctx, gucsource);
3436 if (!set_plan_disabling_options(optarg, ctx, gucsource))
3441 SetConfigOption("listen_addresses", optarg, ctx, gucsource);
3445 SetConfigOption("listen_addresses", "*", ctx, gucsource);
3450 UseSemiNewlineNewline = true;
3454 SetConfigOption("unix_socket_directories", optarg, ctx, gucsource);
3458 SetConfigOption("ssl", "true", ctx, gucsource);
3462 SetConfigOption("max_connections", optarg, ctx, gucsource);
3466 /* ignored for consistency with postmaster */
3470 SetConfigOption("allow_system_table_mods", "true", ctx, gucsource);
3478 SetConfigOption("ignore_system_indexes", "true", ctx, gucsource);
3482 SetConfigOption("port", optarg, ctx, gucsource);
3486 /* send output (stdout and stderr) to the given file */
3488 strlcpy(OutputFileName, optarg, MAXPGPATH);
3492 SetConfigOption("work_mem", optarg, ctx, gucsource);
3496 SetConfigOption("log_statement_stats", "true", ctx, gucsource);
3500 /* ignored for consistency with the postmaster */
3505 const char *tmp = get_stats_option_name(optarg);
3508 SetConfigOption(tmp, "true", ctx, gucsource);
3517 * -v is no longer used in normal operation, since
3518 * FrontendProtocol is already set before we get here. We keep
3519 * the switch only for possible use in standalone operation,
3520 * in case we ever support using normal FE/BE protocol with a
3521 * standalone backend.
3524 FrontendProtocol = (ProtocolVersion) atoi(optarg);
3528 SetConfigOption("post_auth_delay", optarg, ctx, gucsource);
3537 ParseLongOption(optarg, &name, &value);
3542 (errcode(ERRCODE_SYNTAX_ERROR),
3543 errmsg("--%s requires a value",
3547 (errcode(ERRCODE_SYNTAX_ERROR),
3548 errmsg("-c %s requires a value",
3551 SetConfigOption(name, value, ctx, gucsource);
3568 * Optional database name should be there only if *dbname is NULL.
3570 if (!errs && dbname && *dbname == NULL && argc - optind >= 1)
3571 *dbname = strdup(argv[optind++]);
3573 if (errs || argc != optind)
3576 optind--; /* complain about the previous argument */
3578 /* spell the error message a bit differently depending on context */
3579 if (IsUnderPostmaster)
3581 (errcode(ERRCODE_SYNTAX_ERROR),
3582 errmsg("invalid command-line argument for server process: %s", argv[optind]),
3583 errhint("Try \"%s --help\" for more information.", progname)));
3586 (errcode(ERRCODE_SYNTAX_ERROR),
3587 errmsg("%s: invalid command-line argument: %s",
3588 progname, argv[optind]),
3589 errhint("Try \"%s --help\" for more information.", progname)));
3593 * Reset getopt(3) library so that it will work correctly in subprocesses
3594 * or when this function is called a second time with another array.
3597 #ifdef HAVE_INT_OPTRESET
3598 optreset = 1; /* some systems need this too */
3603 /* ----------------------------------------------------------------
3605 * postgres main loop -- all backends, interactive or otherwise start here
3607 * argc/argv are the command line arguments to be used. (When being forked
3608 * by the postmaster, these are not the original argv array of the process.)
3609 * dbname is the name of the database to connect to, or NULL if the database
3610 * name should be extracted from the command line arguments or defaulted.
3611 * username is the PostgreSQL user name to be used for the session.
3612 * ----------------------------------------------------------------
3615 PostgresMain(int argc, char *argv[],
3617 const char *username)
3620 StringInfoData input_message;
3621 sigjmp_buf local_sigjmp_buf;
3622 volatile bool send_ready_for_query = true;
3623 bool disable_idle_in_transaction_timeout = false;
3625 /* Initialize startup process environment if necessary. */
3626 if (!IsUnderPostmaster)
3627 InitStandaloneProcess(argv[0]);
3629 SetProcessingMode(InitProcessing);
3632 * Set default values for command-line options.
3634 if (!IsUnderPostmaster)
3635 InitializeGUCOptions();
3638 * Parse command-line options.
3640 process_postgres_switches(argc, argv, PGC_POSTMASTER, &dbname);
3642 /* Must have gotten a database name, or have a default (the username) */
3648 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
3649 errmsg("%s: no database nor user name specified",
3653 /* Acquire configuration parameters, unless inherited from postmaster */
3654 if (!IsUnderPostmaster)
3656 if (!SelectConfigFiles(userDoption, progname))
3661 * Set up signal handlers and masks.
3663 * Note that postmaster blocked all signals before forking child process,
3664 * so there is no race condition whereby we might receive a signal before
3665 * we have set up the handler.
3667 * Also note: it's best not to use any signals that are SIG_IGNored in the
3668 * postmaster. If such a signal arrives before we are able to change the
3669 * handler to non-SIG_IGN, it'll get dropped. Instead, make a dummy
3670 * handler in the postmaster to reserve the signal. (Of course, this isn't
3671 * an issue for signals that are locally generated, such as SIGALRM and
3678 pqsignal(SIGHUP, PostgresSigHupHandler); /* set flag to read config
3680 pqsignal(SIGINT, StatementCancelHandler); /* cancel current query */
3681 pqsignal(SIGTERM, die); /* cancel current query and exit */
3684 * In a standalone backend, SIGQUIT can be generated from the keyboard
3685 * easily, while SIGTERM cannot, so we make both signals do die()
3686 * rather than quickdie().
3688 if (IsUnderPostmaster)
3689 pqsignal(SIGQUIT, quickdie); /* hard crash time */
3691 pqsignal(SIGQUIT, die); /* cancel current query and exit */
3692 InitializeTimeouts(); /* establishes SIGALRM handler */
3695 * Ignore failure to write to frontend. Note: if frontend closes
3696 * connection, we will notice it and exit cleanly when control next
3697 * returns to outer loop. This seems safer than forcing exit in the
3698 * midst of output during who-knows-what operation...
3700 pqsignal(SIGPIPE, SIG_IGN);
3701 pqsignal(SIGUSR1, procsignal_sigusr1_handler);
3702 pqsignal(SIGUSR2, SIG_IGN);
3703 pqsignal(SIGFPE, FloatExceptionHandler);
3706 * Reset some signals that are accepted by postmaster but not by
3709 pqsignal(SIGCHLD, SIG_DFL); /* system() requires this on some
3715 if (IsUnderPostmaster)
3717 /* We allow SIGQUIT (quickdie) at all times */
3718 sigdelset(&BlockSig, SIGQUIT);
3721 PG_SETMASK(&BlockSig); /* block everything except SIGQUIT */
3723 if (!IsUnderPostmaster)
3726 * Validate we have been given a reasonable-looking DataDir (if under
3727 * postmaster, assume postmaster did this already).
3730 ValidatePgVersion(DataDir);
3732 /* Change into DataDir (if under postmaster, was done already) */
3736 * Create lockfile for data directory.
3738 CreateDataDirLockFile(false);
3740 /* read control file (error checking and contains config ) */
3741 LocalProcessControlFile(false);
3743 /* Initialize MaxBackends (if under postmaster, was done already) */
3744 InitializeMaxBackends();
3747 /* Early initialization */
3751 * Create a per-backend PGPROC struct in shared memory, except in the
3752 * EXEC_BACKEND case where this was done in SubPostmasterMain. We must do
3753 * this before we can use LWLocks (and in the EXEC_BACKEND case we already
3754 * had to do some stuff with LWLocks).
3757 if (!IsUnderPostmaster)
3763 /* We need to allow SIGINT, etc during the initial transaction */
3764 PG_SETMASK(&UnBlockSig);
3767 * General initialization.
3769 * NOTE: if you are tempted to add code in this vicinity, consider putting
3770 * it inside InitPostgres() instead. In particular, anything that
3771 * involves database access should be there, not here.
3773 InitPostgres(dbname, InvalidOid, username, InvalidOid, NULL);
3776 * If the PostmasterContext is still around, recycle the space; we don't
3777 * need it anymore after InitPostgres completes. Note this does not trash
3778 * *MyProcPort, because ConnCreate() allocated that space with malloc()
3779 * ... else we'd need to copy the Port data first. Also, subsidiary data
3780 * such as the username isn't lost either; see ProcessStartupPacket().
3782 if (PostmasterContext)
3784 MemoryContextDelete(PostmasterContext);
3785 PostmasterContext = NULL;
3788 SetProcessingMode(NormalProcessing);
3791 * Now all GUC states are fully set up. Report them to client if
3794 BeginReportingGUCOptions();
3797 * Also set up handler to log session end; we have to wait till now to be
3798 * sure Log_disconnections has its final value.
3800 if (IsUnderPostmaster && Log_disconnections)
3801 on_proc_exit(log_disconnections, 0);
3803 /* Perform initialization specific to a WAL sender process. */
3808 * process any libraries that should be preloaded at backend start (this
3809 * likewise can't be done until GUC settings are complete)
3811 process_session_preload_libraries();
3814 * Send this backend's cancellation info to the frontend.
3816 if (whereToSendOutput == DestRemote)
3820 pq_beginmessage(&buf, 'K');
3821 pq_sendint32(&buf, (int32) MyProcPid);
3822 pq_sendint32(&buf, (int32) MyCancelKey);
3823 pq_endmessage(&buf);
3824 /* Need not flush since ReadyForQuery will do it. */
3827 /* Welcome banner for standalone case */
3828 if (whereToSendOutput == DestDebug)
3829 printf("\nPostgreSQL stand-alone backend %s\n", PG_VERSION);
3832 * Create the memory context we will use in the main loop.
3834 * MessageContext is reset once per iteration of the main loop, ie, upon
3835 * completion of processing of each command message from the client.
3837 MessageContext = AllocSetContextCreate(TopMemoryContext,
3839 ALLOCSET_DEFAULT_SIZES);
3842 * Create memory context and buffer used for RowDescription messages. As
3843 * SendRowDescriptionMessage(), via exec_describe_statement_message(), is
3844 * frequently executed for ever single statement, we don't want to
3845 * allocate a separate buffer every time.
3847 row_description_context = AllocSetContextCreate(TopMemoryContext,
3848 "RowDescriptionContext",
3849 ALLOCSET_DEFAULT_SIZES);
3850 MemoryContextSwitchTo(row_description_context);
3851 initStringInfo(&row_description_buf);
3852 MemoryContextSwitchTo(TopMemoryContext);
3855 * Remember stand-alone backend startup time
3857 if (!IsUnderPostmaster)
3858 PgStartTime = GetCurrentTimestamp();
3861 * POSTGRES main processing loop begins here
3863 * If an exception is encountered, processing resumes here so we abort the
3864 * current transaction and start a new one.
3866 * You might wonder why this isn't coded as an infinite loop around a
3867 * PG_TRY construct. The reason is that this is the bottom of the
3868 * exception stack, and so with PG_TRY there would be no exception handler
3869 * in force at all during the CATCH part. By leaving the outermost setjmp
3870 * always active, we have at least some chance of recovering from an error
3871 * during error recovery. (If we get into an infinite loop thereby, it
3872 * will soon be stopped by overflow of elog.c's internal state stack.)
3874 * Note that we use sigsetjmp(..., 1), so that this function's signal mask
3875 * (to wit, UnBlockSig) will be restored when longjmp'ing to here. This
3876 * is essential in case we longjmp'd out of a signal handler on a platform
3877 * where that leaves the signal blocked. It's not redundant with the
3878 * unblock in AbortTransaction() because the latter is only called if we
3879 * were inside a transaction.
3882 if (sigsetjmp(local_sigjmp_buf, 1) != 0)
3885 * NOTE: if you are tempted to add more code in this if-block,
3886 * consider the high probability that it should be in
3887 * AbortTransaction() instead. The only stuff done directly here
3888 * should be stuff that is guaranteed to apply *only* for outer-level
3889 * error recovery, such as adjusting the FE/BE protocol status.
3892 /* Since not using PG_TRY, must reset error stack by hand */
3893 error_context_stack = NULL;
3895 /* Prevent interrupts while cleaning up */
3899 * Forget any pending QueryCancel request, since we're returning to
3900 * the idle loop anyway, and cancel any active timeout requests. (In
3901 * future we might want to allow some timeout requests to survive, but
3902 * at minimum it'd be necessary to do reschedule_timeouts(), in case
3903 * we got here because of a query cancel interrupting the SIGALRM
3904 * interrupt handler.) Note in particular that we must clear the
3905 * statement and lock timeout indicators, to prevent any future plain
3906 * query cancels from being misreported as timeouts in case we're
3907 * forgetting a timeout cancel.
3909 disable_all_timeouts(false);
3910 QueryCancelPending = false; /* second to avoid race condition */
3912 /* Not reading from the client anymore. */
3913 DoingCommandRead = false;
3915 /* Make sure libpq is in a good state */
3918 /* Report the error to the client and/or server log */
3922 * Make sure debug_query_string gets reset before we possibly clobber
3923 * the storage it points at.
3925 debug_query_string = NULL;
3928 * Abort the current transaction in order to recover.
3930 AbortCurrentTransaction();
3933 WalSndErrorCleanup();
3936 * We can't release replication slots inside AbortTransaction() as we
3937 * need to be able to start and abort transactions while having a slot
3938 * acquired. But we never need to hold them across top level errors,
3939 * so releasing here is fine. There's another cleanup in ProcKill()
3940 * ensuring we'll correctly cleanup on FATAL errors as well.
3942 if (MyReplicationSlot != NULL)
3943 ReplicationSlotRelease();
3945 /* We also want to cleanup temporary slots on error. */
3946 ReplicationSlotCleanup();
3949 * Now return to normal top-level context and clear ErrorContext for
3952 MemoryContextSwitchTo(TopMemoryContext);
3956 * If we were handling an extended-query-protocol message, initiate
3957 * skip till next Sync. This also causes us not to issue
3958 * ReadyForQuery (until we get Sync).
3960 if (doing_extended_query_message)
3961 ignore_till_sync = true;
3963 /* We don't have a transaction command open anymore */
3964 xact_started = false;
3967 * If an error occurred while we were reading a message from the
3968 * client, we have potentially lost track of where the previous
3969 * message ends and the next one begins. Even though we have
3970 * otherwise recovered from the error, we cannot safely read any more
3971 * messages from the client, so there isn't much we can do with the
3972 * connection anymore.
3974 if (pq_is_reading_msg())
3976 (errcode(ERRCODE_PROTOCOL_VIOLATION),
3977 errmsg("terminating connection because protocol synchronization was lost")));
3979 /* Now we can allow interrupts again */
3980 RESUME_INTERRUPTS();
3983 /* We can now handle ereport(ERROR) */
3984 PG_exception_stack = &local_sigjmp_buf;
3986 if (!ignore_till_sync)
3987 send_ready_for_query = true; /* initially, or after error */
3990 * Non-error queries loop here.
3996 * At top of loop, reset extended-query-message flag, so that any
3997 * errors encountered in "idle" state don't provoke skip.
3999 doing_extended_query_message = false;
4002 * Release storage left over from prior query cycle, and create a new
4003 * query input buffer in the cleared MessageContext.
4005 MemoryContextSwitchTo(MessageContext);
4006 MemoryContextResetAndDeleteChildren(MessageContext);
4008 initStringInfo(&input_message);
4011 * Also consider releasing our catalog snapshot if any, so that it's
4012 * not preventing advance of global xmin while we wait for the client.
4014 InvalidateCatalogSnapshotConditionally();
4017 * (1) If we've reached idle state, tell the frontend we're ready for
4020 * Note: this includes fflush()'ing the last of the prior output.
4022 * This is also a good time to send collected statistics to the
4023 * collector, and to update the PS stats display. We avoid doing
4024 * those every time through the message loop because it'd slow down
4025 * processing of batched messages, and because we don't want to report
4026 * uncommitted updates (that confuses autovacuum). The notification
4027 * processor wants a call too, if we are not in a transaction block.
4029 if (send_ready_for_query)
4031 if (IsAbortedTransactionBlockState())
4033 set_ps_display("idle in transaction (aborted)", false);
4034 pgstat_report_activity(STATE_IDLEINTRANSACTION_ABORTED, NULL);
4036 /* Start the idle-in-transaction timer */
4037 if (IdleInTransactionSessionTimeout > 0)
4039 disable_idle_in_transaction_timeout = true;
4040 enable_timeout_after(IDLE_IN_TRANSACTION_SESSION_TIMEOUT,
4041 IdleInTransactionSessionTimeout);
4044 else if (IsTransactionOrTransactionBlock())
4046 set_ps_display("idle in transaction", false);
4047 pgstat_report_activity(STATE_IDLEINTRANSACTION, NULL);
4049 /* Start the idle-in-transaction timer */
4050 if (IdleInTransactionSessionTimeout > 0)
4052 disable_idle_in_transaction_timeout = true;
4053 enable_timeout_after(IDLE_IN_TRANSACTION_SESSION_TIMEOUT,
4054 IdleInTransactionSessionTimeout);
4059 ProcessCompletedNotifies();
4060 pgstat_report_stat(false);
4062 set_ps_display("idle", false);
4063 pgstat_report_activity(STATE_IDLE, NULL);
4066 ReadyForQuery(whereToSendOutput);
4067 send_ready_for_query = false;
4071 * (2) Allow asynchronous signals to be executed immediately if they
4072 * come in while we are waiting for client input. (This must be
4073 * conditional since we don't want, say, reads on behalf of COPY FROM
4074 * STDIN doing the same thing.)
4076 DoingCommandRead = true;
4079 * (3) read a command (loop blocks here)
4081 firstchar = ReadCommand(&input_message);
4084 * (4) disable async signal conditions again.
4086 * Query cancel is supposed to be a no-op when there is no query in
4087 * progress, so if a query cancel arrived while we were idle, just
4088 * reset QueryCancelPending. ProcessInterrupts() has that effect when
4089 * it's called when DoingCommandRead is set, so check for interrupts
4090 * before resetting DoingCommandRead.
4092 CHECK_FOR_INTERRUPTS();
4093 DoingCommandRead = false;
4096 * (5) turn off the idle-in-transaction timeout
4098 if (disable_idle_in_transaction_timeout)
4100 disable_timeout(IDLE_IN_TRANSACTION_SESSION_TIMEOUT, false);
4101 disable_idle_in_transaction_timeout = false;
4105 * (6) check for any other interesting events that happened while we
4108 if (ConfigReloadPending)
4110 ConfigReloadPending = false;
4111 ProcessConfigFile(PGC_SIGHUP);
4115 * (7) process the command. But ignore it if we're skipping till
4118 if (ignore_till_sync && firstchar != EOF)
4123 case 'Q': /* simple query */
4125 const char *query_string;
4127 /* Set statement_timestamp() */
4128 SetCurrentStatementStartTimestamp();
4130 query_string = pq_getmsgstring(&input_message);
4131 pq_getmsgend(&input_message);
4135 if (!exec_replication_command(query_string))
4136 exec_simple_query(query_string);
4139 exec_simple_query(query_string);
4141 send_ready_for_query = true;
4145 case 'P': /* parse */
4147 const char *stmt_name;
4148 const char *query_string;
4150 Oid *paramTypes = NULL;
4152 forbidden_in_wal_sender(firstchar);
4154 /* Set statement_timestamp() */
4155 SetCurrentStatementStartTimestamp();
4157 stmt_name = pq_getmsgstring(&input_message);
4158 query_string = pq_getmsgstring(&input_message);
4159 numParams = pq_getmsgint(&input_message, 2);
4164 paramTypes = (Oid *) palloc(numParams * sizeof(Oid));
4165 for (i = 0; i < numParams; i++)
4166 paramTypes[i] = pq_getmsgint(&input_message, 4);
4168 pq_getmsgend(&input_message);
4170 exec_parse_message(query_string, stmt_name,
4171 paramTypes, numParams);
4175 case 'B': /* bind */
4176 forbidden_in_wal_sender(firstchar);
4178 /* Set statement_timestamp() */
4179 SetCurrentStatementStartTimestamp();
4182 * this message is complex enough that it seems best to put
4183 * the field extraction out-of-line
4185 exec_bind_message(&input_message);
4188 case 'E': /* execute */
4190 const char *portal_name;
4193 forbidden_in_wal_sender(firstchar);
4195 /* Set statement_timestamp() */
4196 SetCurrentStatementStartTimestamp();
4198 portal_name = pq_getmsgstring(&input_message);
4199 max_rows = pq_getmsgint(&input_message, 4);
4200 pq_getmsgend(&input_message);
4202 exec_execute_message(portal_name, max_rows);
4206 case 'F': /* fastpath function call */
4207 forbidden_in_wal_sender(firstchar);
4209 /* Set statement_timestamp() */
4210 SetCurrentStatementStartTimestamp();
4212 /* Report query to various monitoring facilities. */
4213 pgstat_report_activity(STATE_FASTPATH, NULL);
4214 set_ps_display("<FASTPATH>", false);
4216 /* start an xact for this function invocation */
4217 start_xact_command();
4220 * Note: we may at this point be inside an aborted
4221 * transaction. We can't throw error for that until we've
4222 * finished reading the function-call message, so
4223 * HandleFunctionRequest() must check for it after doing so.
4224 * Be careful not to do anything that assumes we're inside a
4225 * valid transaction here.
4228 /* switch back to message context */
4229 MemoryContextSwitchTo(MessageContext);
4231 HandleFunctionRequest(&input_message);
4233 /* commit the function-invocation transaction */
4234 finish_xact_command();
4236 send_ready_for_query = true;
4239 case 'C': /* close */
4242 const char *close_target;
4244 forbidden_in_wal_sender(firstchar);
4246 close_type = pq_getmsgbyte(&input_message);
4247 close_target = pq_getmsgstring(&input_message);
4248 pq_getmsgend(&input_message);
4253 if (close_target[0] != '\0')
4254 DropPreparedStatement(close_target, false);
4257 /* special-case the unnamed statement */
4258 drop_unnamed_stmt();
4265 portal = GetPortalByName(close_target);
4266 if (PortalIsValid(portal))
4267 PortalDrop(portal, false);
4272 (errcode(ERRCODE_PROTOCOL_VIOLATION),
4273 errmsg("invalid CLOSE message subtype %d",
4278 if (whereToSendOutput == DestRemote)
4279 pq_putemptymessage('3'); /* CloseComplete */
4283 case 'D': /* describe */
4286 const char *describe_target;
4288 forbidden_in_wal_sender(firstchar);
4290 /* Set statement_timestamp() (needed for xact) */
4291 SetCurrentStatementStartTimestamp();
4293 describe_type = pq_getmsgbyte(&input_message);
4294 describe_target = pq_getmsgstring(&input_message);
4295 pq_getmsgend(&input_message);
4297 switch (describe_type)
4300 exec_describe_statement_message(describe_target);
4303 exec_describe_portal_message(describe_target);
4307 (errcode(ERRCODE_PROTOCOL_VIOLATION),
4308 errmsg("invalid DESCRIBE message subtype %d",
4315 case 'H': /* flush */
4316 pq_getmsgend(&input_message);
4317 if (whereToSendOutput == DestRemote)
4321 case 'S': /* sync */
4322 pq_getmsgend(&input_message);
4323 finish_xact_command();
4324 send_ready_for_query = true;
4328 * 'X' means that the frontend is closing down the socket. EOF
4329 * means unexpected loss of frontend connection. Either way,
4330 * perform normal shutdown.
4336 * Reset whereToSendOutput to prevent ereport from attempting
4337 * to send any more messages to client.
4339 if (whereToSendOutput == DestRemote)
4340 whereToSendOutput = DestNone;
4343 * NOTE: if you are tempted to add more code here, DON'T!
4344 * Whatever you had in mind to do should be set up as an
4345 * on_proc_exit or on_shmem_exit callback, instead. Otherwise
4346 * it will fail to be called during other backend-shutdown
4351 case 'd': /* copy data */
4352 case 'c': /* copy done */
4353 case 'f': /* copy fail */
4356 * Accept but ignore these messages, per protocol spec; we
4357 * probably got here because a COPY failed, and the frontend
4358 * is still sending data.
4364 (errcode(ERRCODE_PROTOCOL_VIOLATION),
4365 errmsg("invalid frontend message type %d",
4368 } /* end of input-reading loop */
4372 * Throw an error if we're a WAL sender process.
4374 * This is used to forbid anything else than simple query protocol messages
4375 * in a WAL sender process. 'firstchar' specifies what kind of a forbidden
4376 * message was received, and is used to construct the error message.
4379 forbidden_in_wal_sender(char firstchar)
4383 if (firstchar == 'F')
4385 (errcode(ERRCODE_PROTOCOL_VIOLATION),
4386 errmsg("fastpath function calls not supported in a replication connection")));
4389 (errcode(ERRCODE_PROTOCOL_VIOLATION),
4390 errmsg("extended query protocol not supported in a replication connection")));
4396 * Obtain platform stack depth limit (in bytes)
4398 * Return -1 if unknown
4401 get_stack_depth_rlimit(void)
4403 #if defined(HAVE_GETRLIMIT) && defined(RLIMIT_STACK)
4404 static long val = 0;
4406 /* This won't change after process launch, so check just once */
4411 if (getrlimit(RLIMIT_STACK, &rlim) < 0)
4413 else if (rlim.rlim_cur == RLIM_INFINITY)
4415 /* rlim_cur is probably of an unsigned type, so check for overflow */
4416 else if (rlim.rlim_cur >= LONG_MAX)
4419 val = rlim.rlim_cur;
4422 #else /* no getrlimit */
4423 #if defined(WIN32) || defined(__CYGWIN__)
4424 /* On Windows we set the backend stack size in src/backend/Makefile */
4425 return WIN32_STACK_RLIMIT;
4426 #else /* not windows ... give up */
4433 static struct rusage Save_r;
4434 static struct timeval Save_t;
4439 getrusage(RUSAGE_SELF, &Save_r);
4440 gettimeofday(&Save_t, NULL);
4444 ShowUsage(const char *title)
4447 struct timeval user,
4449 struct timeval elapse_t;
4452 getrusage(RUSAGE_SELF, &r);
4453 gettimeofday(&elapse_t, NULL);
4454 memcpy((char *) &user, (char *) &r.ru_utime, sizeof(user));
4455 memcpy((char *) &sys, (char *) &r.ru_stime, sizeof(sys));
4456 if (elapse_t.tv_usec < Save_t.tv_usec)
4459 elapse_t.tv_usec += 1000000;
4461 if (r.ru_utime.tv_usec < Save_r.ru_utime.tv_usec)
4463 r.ru_utime.tv_sec--;
4464 r.ru_utime.tv_usec += 1000000;
4466 if (r.ru_stime.tv_usec < Save_r.ru_stime.tv_usec)
4468 r.ru_stime.tv_sec--;
4469 r.ru_stime.tv_usec += 1000000;
4473 * The only stats we don't show here are ixrss, idrss, isrss. It takes
4474 * some work to interpret them, and most platforms don't fill them in.
4476 initStringInfo(&str);
4478 appendStringInfoString(&str, "! system usage stats:\n");
4479 appendStringInfo(&str,
4480 "!\t%ld.%06ld s user, %ld.%06ld s system, %ld.%06ld s elapsed\n",
4481 (long) (r.ru_utime.tv_sec - Save_r.ru_utime.tv_sec),
4482 (long) (r.ru_utime.tv_usec - Save_r.ru_utime.tv_usec),
4483 (long) (r.ru_stime.tv_sec - Save_r.ru_stime.tv_sec),
4484 (long) (r.ru_stime.tv_usec - Save_r.ru_stime.tv_usec),
4485 (long) (elapse_t.tv_sec - Save_t.tv_sec),
4486 (long) (elapse_t.tv_usec - Save_t.tv_usec));
4487 appendStringInfo(&str,
4488 "!\t[%ld.%06ld s user, %ld.%06ld s system total]\n",
4490 (long) user.tv_usec,
4492 (long) sys.tv_usec);
4493 #if defined(HAVE_GETRUSAGE)
4494 appendStringInfo(&str,
4495 "!\t%ld kB max resident size\n",
4496 #if defined(__darwin__)
4497 /* in bytes on macOS */
4500 /* in kilobytes on most other platforms */
4504 appendStringInfo(&str,
4505 "!\t%ld/%ld [%ld/%ld] filesystem blocks in/out\n",
4506 r.ru_inblock - Save_r.ru_inblock,
4507 /* they only drink coffee at dec */
4508 r.ru_oublock - Save_r.ru_oublock,
4509 r.ru_inblock, r.ru_oublock);
4510 appendStringInfo(&str,
4511 "!\t%ld/%ld [%ld/%ld] page faults/reclaims, %ld [%ld] swaps\n",
4512 r.ru_majflt - Save_r.ru_majflt,
4513 r.ru_minflt - Save_r.ru_minflt,
4514 r.ru_majflt, r.ru_minflt,
4515 r.ru_nswap - Save_r.ru_nswap,
4517 appendStringInfo(&str,
4518 "!\t%ld [%ld] signals rcvd, %ld/%ld [%ld/%ld] messages rcvd/sent\n",
4519 r.ru_nsignals - Save_r.ru_nsignals,
4521 r.ru_msgrcv - Save_r.ru_msgrcv,
4522 r.ru_msgsnd - Save_r.ru_msgsnd,
4523 r.ru_msgrcv, r.ru_msgsnd);
4524 appendStringInfo(&str,
4525 "!\t%ld/%ld [%ld/%ld] voluntary/involuntary context switches\n",
4526 r.ru_nvcsw - Save_r.ru_nvcsw,
4527 r.ru_nivcsw - Save_r.ru_nivcsw,
4528 r.ru_nvcsw, r.ru_nivcsw);
4529 #endif /* HAVE_GETRUSAGE */
4531 /* remove trailing newline */
4532 if (str.data[str.len - 1] == '\n')
4533 str.data[--str.len] = '\0';
4536 (errmsg_internal("%s", title),
4537 errdetail_internal("%s", str.data)));
4543 * on_proc_exit handler to log end of session
4546 log_disconnections(int code, Datum arg)
4548 Port *port = MyProcPort;
4556 TimestampDifference(port->SessionStartTime,
4557 GetCurrentTimestamp(),
4559 msecs = usecs / 1000;
4561 hours = secs / SECS_PER_HOUR;
4562 secs %= SECS_PER_HOUR;
4563 minutes = secs / SECS_PER_MINUTE;
4564 seconds = secs % SECS_PER_MINUTE;
4567 (errmsg("disconnection: session time: %d:%02d:%02d.%03d "
4568 "user=%s database=%s host=%s%s%s",
4569 hours, minutes, seconds, msecs,
4570 port->user_name, port->database_name, port->remote_host,
4571 port->remote_port[0] ? " port=" : "", port->remote_port)));
4575 * Start statement timeout timer, if enabled.
4577 * If there's already a timeout running, don't restart the timer. That
4578 * enables compromises between accuracy of timeouts and cost of starting a
4582 enable_statement_timeout(void)
4584 /* must be within an xact */
4585 Assert(xact_started);
4587 if (StatementTimeout > 0)
4589 if (!stmt_timeout_active)
4591 enable_timeout_after(STATEMENT_TIMEOUT, StatementTimeout);
4592 stmt_timeout_active = true;
4596 disable_timeout(STATEMENT_TIMEOUT, false);
4600 * Disable statement timeout, if active.
4603 disable_statement_timeout(void)
4605 if (stmt_timeout_active)
4607 disable_timeout(STATEMENT_TIMEOUT, false);
4609 stmt_timeout_active = false;