1 /*-------------------------------------------------------------------------
4 * POSTGRES C Backend Interface
6 * Portions Copyright (c) 1996-2015, 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/slot.h"
59 #include "replication/walsender.h"
60 #include "rewrite/rewriteHandler.h"
61 #include "storage/bufmgr.h"
62 #include "storage/ipc.h"
63 #include "storage/proc.h"
64 #include "storage/procsignal.h"
65 #include "storage/sinval.h"
66 #include "tcop/fastpath.h"
67 #include "tcop/pquery.h"
68 #include "tcop/tcopprot.h"
69 #include "tcop/utility.h"
70 #include "utils/lsyscache.h"
71 #include "utils/memutils.h"
72 #include "utils/ps_status.h"
73 #include "utils/snapmgr.h"
74 #include "utils/timeout.h"
75 #include "utils/timestamp.h"
76 #include "mb/pg_wchar.h"
83 const char *debug_query_string; /* client-supplied query string */
85 /* Note: whereToSendOutput is initialized for the bootstrap/standalone case */
86 CommandDest whereToSendOutput = DestDebug;
88 /* flag for logging end of session */
89 bool Log_disconnections = false;
91 int log_statement = LOGSTMT_NONE;
93 /* GUC variable for maximum stack depth (measured in kilobytes) */
94 int max_stack_depth = 100;
96 /* wait N seconds to allow attach from a debugger */
97 int PostAuthDelay = 0;
106 /* max_stack_depth converted to bytes for speed of checking */
107 static long max_stack_depth_bytes = 100 * 1024L;
110 * Stack base pointer -- initialized by PostmasterMain and inherited by
111 * subprocesses. This is not static because old versions of PL/Java modify
112 * it directly. Newer versions use set_stack_base(), but we want to stay
113 * binary-compatible for the time being.
115 char *stack_base_ptr = NULL;
118 * On IA64 we also have to remember the register stack base.
120 #if defined(__ia64__) || defined(__ia64)
121 char *register_stack_base_ptr = NULL;
125 * Flag to mark SIGHUP. Whenever the main loop comes around it
126 * will reread the configuration file. (Better than doing the
127 * reading in the signal handler, ey?)
129 static volatile sig_atomic_t got_SIGHUP = false;
132 * Flag to keep track of whether we have started a transaction.
133 * For extended query protocol this has to be remembered across messages.
135 static bool xact_started = false;
138 * Flag to indicate that we are doing the outer loop's read-from-client,
139 * as opposed to any random read from client that might happen within
140 * commands like COPY FROM STDIN.
142 static bool DoingCommandRead = false;
145 * Flags to implement skip-till-Sync-after-error behavior for messages of
146 * the extended query protocol.
148 static bool doing_extended_query_message = false;
149 static bool ignore_till_sync = 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 */
161 static bool EchoQuery = false; /* -E switch */
164 * people who want to use EOF should #define DONTUSENEWLINE in
167 #ifndef TCOP_DONTUSENEWLINE
168 static int UseNewLine = 1; /* Use newlines query delimiters (the default) */
170 static int UseNewLine = 0; /* Use EOF as query delimiters */
171 #endif /* TCOP_DONTUSENEWLINE */
173 /* whether or not, and why, we were canceled by conflict with recovery */
174 static bool RecoveryConflictPending = false;
175 static bool RecoveryConflictRetryable = true;
176 static ProcSignalReason RecoveryConflictReason;
178 /* ----------------------------------------------------------------
179 * decls for routines only used in this file
180 * ----------------------------------------------------------------
182 static int InteractiveBackend(StringInfo inBuf);
183 static int interactive_getc(void);
184 static int SocketBackend(StringInfo inBuf);
185 static int ReadCommand(StringInfo inBuf);
186 static void forbidden_in_wal_sender(char firstchar);
187 static List *pg_rewrite_query(Query *query);
188 static bool check_log_statement(List *stmt_list);
189 static int errdetail_execute(List *raw_parsetree_list);
190 static int errdetail_params(ParamListInfo params);
191 static int errdetail_abort(void);
192 static int errdetail_recovery_conflict(void);
193 static void start_xact_command(void);
194 static void finish_xact_command(void);
195 static bool IsTransactionExitStmt(Node *parsetree);
196 static bool IsTransactionExitStmtList(List *parseTrees);
197 static bool IsTransactionStmtList(List *parseTrees);
198 static void drop_unnamed_stmt(void);
199 static void SigHupHandler(SIGNAL_ARGS);
200 static void log_disconnections(int code, Datum arg);
203 /* ----------------------------------------------------------------
204 * routines to obtain user input
205 * ----------------------------------------------------------------
209 * InteractiveBackend() is called for user interactive connections
211 * the string entered by the user is placed in its parameter inBuf,
212 * and we act like a Q message was received.
214 * EOF is returned if end-of-file input is seen; time to shut down.
219 InteractiveBackend(StringInfo inBuf)
221 int c; /* character read from getc() */
222 bool end = false; /* end-of-input flag */
223 bool backslashSeen = false; /* have we seen a \ ? */
226 * display a prompt and obtain input from the user
231 resetStringInfo(inBuf);
236 * if we are using \n as a delimiter, then read characters until the
239 while ((c = interactive_getc()) != EOF)
245 /* discard backslash from inBuf */
246 inBuf->data[--inBuf->len] = '\0';
247 backslashSeen = false;
252 /* keep the newline character */
253 appendStringInfoChar(inBuf, '\n');
258 backslashSeen = true;
260 backslashSeen = false;
262 appendStringInfoChar(inBuf, (char) c);
271 * otherwise read characters until EOF.
273 while ((c = interactive_getc()) != EOF)
274 appendStringInfoChar(inBuf, (char) c);
276 /* No input before EOF signal means time to quit. */
285 * otherwise we have a user query so process it.
288 /* Add '\0' to make it look the same as message case. */
289 appendStringInfoChar(inBuf, (char) '\0');
292 * if the query echo flag was given, print the query..
295 printf("statement: %s\n", inBuf->data);
302 * interactive_getc -- collect one character from stdin
304 * Even though we are not reading from a "client" process, we still want to
305 * respond to signals, particularly SIGTERM/SIGQUIT.
308 interactive_getc(void)
313 * This will not process catchup interrupts or notifications while
314 * reading. But those can't really be relevant for a standalone backend
315 * anyway. To properly handle SIGTERM there's a hack in die() that
316 * directly processes interrupts at this stage...
318 CHECK_FOR_INTERRUPTS();
322 ProcessClientReadInterrupt(true);
328 * SocketBackend() Is called for frontend-backend connections
330 * Returns the message type code, and loads message body data into inBuf.
332 * EOF is returned if the connection is lost.
336 SocketBackend(StringInfo inBuf)
341 * Get message type code from the frontend.
343 HOLD_CANCEL_INTERRUPTS();
345 qtype = pq_getbyte();
347 if (qtype == EOF) /* frontend disconnected */
349 if (IsTransactionState())
351 (errcode(ERRCODE_CONNECTION_FAILURE),
352 errmsg("unexpected EOF on client connection with an open transaction")));
356 * Can't send DEBUG log messages to client at this point. Since
357 * we're disconnecting right away, we don't need to restore
360 whereToSendOutput = DestNone;
362 (errcode(ERRCODE_CONNECTION_DOES_NOT_EXIST),
363 errmsg("unexpected EOF on client connection")));
369 * Validate message type code before trying to read body; if we have lost
370 * sync, better to say "command unknown" than to run out of memory because
371 * we used garbage as a length word.
373 * This also gives us a place to set the doing_extended_query_message flag
374 * as soon as possible.
378 case 'Q': /* simple query */
379 doing_extended_query_message = false;
380 if (PG_PROTOCOL_MAJOR(FrontendProtocol) < 3)
382 /* old style without length word; convert */
383 if (pq_getstring(inBuf))
385 if (IsTransactionState())
387 (errcode(ERRCODE_CONNECTION_FAILURE),
388 errmsg("unexpected EOF on client connection with an open transaction")));
392 * Can't send DEBUG log messages to client at this
393 * point. Since we're disconnecting right away, we
394 * don't need to restore whereToSendOutput.
396 whereToSendOutput = DestNone;
398 (errcode(ERRCODE_CONNECTION_DOES_NOT_EXIST),
399 errmsg("unexpected EOF on client connection")));
406 case 'F': /* fastpath function call */
407 doing_extended_query_message = false;
408 if (PG_PROTOCOL_MAJOR(FrontendProtocol) < 3)
410 if (GetOldFunctionMessage(inBuf))
412 if (IsTransactionState())
414 (errcode(ERRCODE_CONNECTION_FAILURE),
415 errmsg("unexpected EOF on client connection with an open transaction")));
419 * Can't send DEBUG log messages to client at this
420 * point. Since we're disconnecting right away, we
421 * don't need to restore whereToSendOutput.
423 whereToSendOutput = DestNone;
425 (errcode(ERRCODE_CONNECTION_DOES_NOT_EXIST),
426 errmsg("unexpected EOF on client connection")));
433 case 'X': /* terminate */
434 doing_extended_query_message = false;
435 ignore_till_sync = false;
439 case 'C': /* close */
440 case 'D': /* describe */
441 case 'E': /* execute */
442 case 'H': /* flush */
443 case 'P': /* parse */
444 doing_extended_query_message = true;
445 /* these are only legal in protocol 3 */
446 if (PG_PROTOCOL_MAJOR(FrontendProtocol) < 3)
448 (errcode(ERRCODE_PROTOCOL_VIOLATION),
449 errmsg("invalid frontend message type %d", qtype)));
453 /* stop any active skip-till-Sync */
454 ignore_till_sync = false;
455 /* mark not-extended, so that a new error doesn't begin skip */
456 doing_extended_query_message = false;
457 /* only legal in protocol 3 */
458 if (PG_PROTOCOL_MAJOR(FrontendProtocol) < 3)
460 (errcode(ERRCODE_PROTOCOL_VIOLATION),
461 errmsg("invalid frontend message type %d", qtype)));
464 case 'd': /* copy data */
465 case 'c': /* copy done */
466 case 'f': /* copy fail */
467 doing_extended_query_message = false;
468 /* these are only legal in protocol 3 */
469 if (PG_PROTOCOL_MAJOR(FrontendProtocol) < 3)
471 (errcode(ERRCODE_PROTOCOL_VIOLATION),
472 errmsg("invalid frontend message type %d", qtype)));
478 * Otherwise we got garbage from the frontend. We treat this as
479 * fatal because we have probably lost message boundary sync, and
480 * there's no good way to recover.
483 (errcode(ERRCODE_PROTOCOL_VIOLATION),
484 errmsg("invalid frontend message type %d", qtype)));
489 * In protocol version 3, all frontend messages have a length word next
490 * after the type code; we can read the message contents independently of
493 if (PG_PROTOCOL_MAJOR(FrontendProtocol) >= 3)
495 if (pq_getmessage(inBuf, 0))
496 return EOF; /* suitable message already logged */
500 RESUME_CANCEL_INTERRUPTS();
506 * ReadCommand reads a command from either the frontend or
507 * standard input, places it in inBuf, and returns the
508 * message type code (first byte of the message).
509 * EOF is returned if end of file.
513 ReadCommand(StringInfo inBuf)
517 if (whereToSendOutput == DestRemote)
518 result = SocketBackend(inBuf);
520 result = InteractiveBackend(inBuf);
525 * ProcessClientReadInterrupt() - Process interrupts specific to client reads
527 * This is called just after low-level reads. That might be after the read
528 * finished successfully, or it was interrupted via interrupt.
530 * Must preserve errno!
533 ProcessClientReadInterrupt(bool blocked)
535 int save_errno = errno;
537 if (DoingCommandRead)
539 /* Check for general interrupts that arrived while reading */
540 CHECK_FOR_INTERRUPTS();
542 /* Process sinval catchup interrupts that happened while reading */
543 if (catchupInterruptPending)
544 ProcessCatchupInterrupt();
546 /* Process sinval catchup interrupts that happened while reading */
547 if (notifyInterruptPending)
548 ProcessNotifyInterrupt();
550 else if (ProcDiePending && blocked)
553 * We're dying. It's safe (and sane) to handle that now.
555 CHECK_FOR_INTERRUPTS();
562 * ProcessClientWriteInterrupt() - Process interrupts specific to client writes
564 * This is called just after low-level writes. That might be after the read
565 * finished successfully, or it was interrupted via interrupt. 'blocked' tells
568 * Must preserve errno!
571 ProcessClientWriteInterrupt(bool blocked)
573 int save_errno = errno;
576 * We only want to process the interrupt here if socket writes are
577 * blocking to increase the chance to get an error message to the client.
578 * If we're not blocked there'll soon be a CHECK_FOR_INTERRUPTS(). But if
579 * we're blocked we'll never get out of that situation if the client has
582 if (ProcDiePending && blocked)
585 * We're dying. It's safe (and sane) to handle that now. But we don't
586 * want to send the client the error message as that a) would possibly
587 * block again b) would possibly lead to sending an error message to
588 * the client, while we already started to send something else.
590 if (whereToSendOutput == DestRemote)
591 whereToSendOutput = DestNone;
593 CHECK_FOR_INTERRUPTS();
600 * Do raw parsing (only).
602 * A list of parsetrees is returned, since there might be multiple
603 * commands in the given string.
605 * NOTE: for interactive queries, it is important to keep this routine
606 * separate from the analysis & rewrite stages. Analysis and rewriting
607 * cannot be done in an aborted transaction, since they require access to
608 * database tables. So, we rely on the raw parser to determine whether
609 * we've seen a COMMIT or ABORT command; when we are in abort state, other
610 * commands are not processed any further than the raw parse stage.
613 pg_parse_query(const char *query_string)
615 List *raw_parsetree_list;
617 TRACE_POSTGRESQL_QUERY_PARSE_START(query_string);
619 if (log_parser_stats)
622 raw_parsetree_list = raw_parser(query_string);
624 if (log_parser_stats)
625 ShowUsage("PARSER STATISTICS");
627 #ifdef COPY_PARSE_PLAN_TREES
628 /* Optional debugging check: pass raw parsetrees through copyObject() */
630 List *new_list = (List *) copyObject(raw_parsetree_list);
632 /* This checks both copyObject() and the equal() routines... */
633 if (!equal(new_list, raw_parsetree_list))
634 elog(WARNING, "copyObject() failed to produce an equal raw parse tree");
636 raw_parsetree_list = new_list;
640 TRACE_POSTGRESQL_QUERY_PARSE_DONE(query_string);
642 return raw_parsetree_list;
646 * Given a raw parsetree (gram.y output), and optionally information about
647 * types of parameter symbols ($n), perform parse analysis and rule rewriting.
649 * A list of Query nodes is returned, since either the analyzer or the
650 * rewriter might expand one query to several.
652 * NOTE: for reasons mentioned above, this must be separate from raw parsing.
655 pg_analyze_and_rewrite(Node *parsetree, const char *query_string,
656 Oid *paramTypes, int numParams)
659 List *querytree_list;
661 TRACE_POSTGRESQL_QUERY_REWRITE_START(query_string);
664 * (1) Perform parse analysis.
666 if (log_parser_stats)
669 query = parse_analyze(parsetree, query_string, paramTypes, numParams);
671 if (log_parser_stats)
672 ShowUsage("PARSE ANALYSIS STATISTICS");
675 * (2) Rewrite the queries, as necessary
677 querytree_list = pg_rewrite_query(query);
679 TRACE_POSTGRESQL_QUERY_REWRITE_DONE(query_string);
681 return querytree_list;
685 * Do parse analysis and rewriting. This is the same as pg_analyze_and_rewrite
686 * except that external-parameter resolution is determined by parser callback
687 * hooks instead of a fixed list of parameter datatypes.
690 pg_analyze_and_rewrite_params(Node *parsetree,
691 const char *query_string,
692 ParserSetupHook parserSetup,
693 void *parserSetupArg)
697 List *querytree_list;
699 Assert(query_string != NULL); /* required as of 8.4 */
701 TRACE_POSTGRESQL_QUERY_REWRITE_START(query_string);
704 * (1) Perform parse analysis.
706 if (log_parser_stats)
709 pstate = make_parsestate(NULL);
710 pstate->p_sourcetext = query_string;
711 (*parserSetup) (pstate, parserSetupArg);
713 query = transformTopLevelStmt(pstate, parsetree);
715 if (post_parse_analyze_hook)
716 (*post_parse_analyze_hook) (pstate, query);
718 free_parsestate(pstate);
720 if (log_parser_stats)
721 ShowUsage("PARSE ANALYSIS STATISTICS");
724 * (2) Rewrite the queries, as necessary
726 querytree_list = pg_rewrite_query(query);
728 TRACE_POSTGRESQL_QUERY_REWRITE_DONE(query_string);
730 return querytree_list;
734 * Perform rewriting of a query produced by parse analysis.
736 * Note: query must just have come from the parser, because we do not do
737 * AcquireRewriteLocks() on it.
740 pg_rewrite_query(Query *query)
742 List *querytree_list;
744 if (Debug_print_parse)
745 elog_node_display(LOG, "parse tree", query,
748 if (log_parser_stats)
751 if (query->commandType == CMD_UTILITY)
753 /* don't rewrite utilities, just dump 'em into result list */
754 querytree_list = list_make1(query);
758 /* rewrite regular queries */
759 querytree_list = QueryRewrite(query);
762 if (log_parser_stats)
763 ShowUsage("REWRITER STATISTICS");
765 #ifdef COPY_PARSE_PLAN_TREES
766 /* Optional debugging check: pass querytree output through copyObject() */
770 new_list = (List *) copyObject(querytree_list);
771 /* This checks both copyObject() and the equal() routines... */
772 if (!equal(new_list, querytree_list))
773 elog(WARNING, "copyObject() failed to produce equal parse tree");
775 querytree_list = new_list;
779 if (Debug_print_rewritten)
780 elog_node_display(LOG, "rewritten parse tree", querytree_list,
783 return querytree_list;
788 * Generate a plan for a single already-rewritten query.
789 * This is a thin wrapper around planner() and takes the same parameters.
792 pg_plan_query(Query *querytree, int cursorOptions, ParamListInfo boundParams)
796 /* Utility commands have no plans. */
797 if (querytree->commandType == CMD_UTILITY)
800 /* Planner must have a snapshot in case it calls user-defined functions. */
801 Assert(ActiveSnapshotSet());
803 TRACE_POSTGRESQL_QUERY_PLAN_START();
805 if (log_planner_stats)
808 /* call the optimizer */
809 plan = planner(querytree, cursorOptions, boundParams);
811 if (log_planner_stats)
812 ShowUsage("PLANNER STATISTICS");
814 #ifdef COPY_PARSE_PLAN_TREES
815 /* Optional debugging check: pass plan output through copyObject() */
817 PlannedStmt *new_plan = (PlannedStmt *) copyObject(plan);
820 * equal() currently does not have routines to compare Plan nodes, so
821 * don't try to test equality here. Perhaps fix someday?
824 /* This checks both copyObject() and the equal() routines... */
825 if (!equal(new_plan, plan))
826 elog(WARNING, "copyObject() failed to produce an equal plan tree");
834 * Print plan if debugging.
836 if (Debug_print_plan)
837 elog_node_display(LOG, "plan", plan, Debug_pretty_print);
839 TRACE_POSTGRESQL_QUERY_PLAN_DONE();
845 * Generate plans for a list of already-rewritten queries.
847 * Normal optimizable statements generate PlannedStmt entries in the result
848 * list. Utility statements are simply represented by their statement 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 = (Query *) lfirst(query_list);
861 if (query->commandType == CMD_UTILITY)
863 /* Utility commands have no plans. */
864 stmt = query->utilityStmt;
868 stmt = (Node *) pg_plan_query(query, cursorOptions, boundParams);
871 stmt_list = lappend(stmt_list, stmt);
881 * Execute a "simple Query" protocol message.
884 exec_simple_query(const char *query_string)
886 CommandDest dest = whereToSendOutput;
887 MemoryContext oldcontext;
888 List *parsetree_list;
889 ListCell *parsetree_item;
890 bool save_log_statement_stats = log_statement_stats;
891 bool was_logged = false;
897 * Report query to various monitoring facilities.
899 debug_query_string = query_string;
901 pgstat_report_activity(STATE_RUNNING, query_string);
903 TRACE_POSTGRESQL_QUERY_START(query_string);
906 * We use save_log_statement_stats so ShowUsage doesn't report incorrect
907 * results because ResetUsage wasn't called.
909 if (save_log_statement_stats)
913 * Start up a transaction command. All queries generated by the
914 * query_string will be in this same command block, *unless* we find a
915 * BEGIN/COMMIT/ABORT statement; we have to force a new xact command after
916 * one of those, else bad things will happen in xact.c. (Note that this
917 * will normally change current memory context.)
919 start_xact_command();
922 * Zap any pre-existing unnamed statement. (While not strictly necessary,
923 * it seems best to define simple-Query mode as if it used the unnamed
924 * statement and portal; this ensures we recover any storage used by prior
925 * unnamed operations.)
930 * Switch to appropriate context for constructing parsetrees.
932 oldcontext = MemoryContextSwitchTo(MessageContext);
935 * Do basic parsing of the query or queries (this should be safe even if
936 * we are in aborted transaction state!)
938 parsetree_list = pg_parse_query(query_string);
940 /* Log immediately if dictated by log_statement */
941 if (check_log_statement(parsetree_list))
944 (errmsg("statement: %s", query_string),
946 errdetail_execute(parsetree_list)));
951 * Switch back to transaction context to enter the loop.
953 MemoryContextSwitchTo(oldcontext);
956 * We'll tell PortalRun it's a top-level command iff there's exactly one
957 * raw parsetree. If more than one, it's effectively a transaction block
958 * and we want PreventTransactionChain to reject unsafe commands. (Note:
959 * we're assuming that query rewrite cannot add commands that are
960 * significant to PreventTransactionChain.)
962 isTopLevel = (list_length(parsetree_list) == 1);
965 * Run through the raw parsetree(s) and process each one.
967 foreach(parsetree_item, parsetree_list)
969 Node *parsetree = (Node *) lfirst(parsetree_item);
970 bool snapshot_set = false;
971 const char *commandTag;
972 char completionTag[COMPLETION_TAG_BUFSIZE];
973 List *querytree_list,
976 DestReceiver *receiver;
980 * Get the command name for use in status display (it also becomes the
981 * default completion tag, down inside PortalRun). Set ps_status and
982 * do any special start-of-SQL-command processing needed by the
985 commandTag = CreateCommandTag(parsetree);
987 set_ps_display(commandTag, false);
989 BeginCommand(commandTag, dest);
992 * If we are in an aborted transaction, reject all commands except
993 * COMMIT/ABORT. It is important that this test occur before we try
994 * to do parse analysis, rewrite, or planning, since all those phases
995 * try to do database accesses, which may fail in abort state. (It
996 * might be safe to allow some additional utility commands in this
997 * state, but not many...)
999 if (IsAbortedTransactionBlockState() &&
1000 !IsTransactionExitStmt(parsetree))
1002 (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
1003 errmsg("current transaction is aborted, "
1004 "commands ignored until end of transaction block"),
1005 errdetail_abort()));
1007 /* Make sure we are in a transaction command */
1008 start_xact_command();
1010 /* If we got a cancel signal in parsing or prior command, quit */
1011 CHECK_FOR_INTERRUPTS();
1014 * Set up a snapshot if parse analysis/planning will need one.
1016 if (analyze_requires_snapshot(parsetree))
1018 PushActiveSnapshot(GetTransactionSnapshot());
1019 snapshot_set = true;
1023 * OK to analyze, rewrite, and plan this query.
1025 * Switch to appropriate context for constructing querytrees (again,
1026 * these must outlive the execution context).
1028 oldcontext = MemoryContextSwitchTo(MessageContext);
1030 querytree_list = pg_analyze_and_rewrite(parsetree, query_string,
1033 plantree_list = pg_plan_queries(querytree_list,
1034 CURSOR_OPT_PARALLEL_OK, NULL);
1036 /* Done with the snapshot used for parsing/planning */
1038 PopActiveSnapshot();
1040 /* If we got a cancel signal in analysis or planning, quit */
1041 CHECK_FOR_INTERRUPTS();
1044 * Create unnamed portal to run the query or queries in. If there
1045 * already is one, silently drop it.
1047 portal = CreatePortal("", true, true);
1048 /* Don't display the portal in pg_cursors */
1049 portal->visible = false;
1052 * We don't have to copy anything into the portal, because everything
1053 * we are passing here is in MessageContext, which will outlive the
1056 PortalDefineQuery(portal,
1064 * Start the portal. No parameters here.
1066 PortalStart(portal, NULL, 0, InvalidSnapshot);
1069 * Select the appropriate output format: text unless we are doing a
1070 * FETCH from a binary cursor. (Pretty grotty to have to do this here
1071 * --- but it avoids grottiness in other places. Ah, the joys of
1072 * backward compatibility...)
1074 format = 0; /* TEXT is default */
1075 if (IsA(parsetree, FetchStmt))
1077 FetchStmt *stmt = (FetchStmt *) parsetree;
1081 Portal fportal = GetPortalByName(stmt->portalname);
1083 if (PortalIsValid(fportal) &&
1084 (fportal->cursorOptions & CURSOR_OPT_BINARY))
1085 format = 1; /* BINARY */
1088 PortalSetResultFormat(portal, 1, &format);
1091 * Now we can create the destination receiver object.
1093 receiver = CreateDestReceiver(dest);
1094 if (dest == DestRemote)
1095 SetRemoteDestReceiverParams(receiver, portal);
1098 * Switch back to transaction context for execution.
1100 MemoryContextSwitchTo(oldcontext);
1103 * Run the portal to completion, and then drop it (and the receiver).
1105 (void) PortalRun(portal,
1112 (*receiver->rDestroy) (receiver);
1114 PortalDrop(portal, false);
1116 if (IsA(parsetree, TransactionStmt))
1119 * If this was a transaction control statement, commit it. We will
1120 * start a new xact command for the next command (if any).
1122 finish_xact_command();
1124 else if (lnext(parsetree_item) == NULL)
1127 * If this is the last parsetree of the query string, close down
1128 * transaction statement before reporting command-complete. This
1129 * is so that any end-of-transaction errors are reported before
1130 * the command-complete message is issued, to avoid confusing
1131 * clients who will expect either a command-complete message or an
1132 * error, not one and then the other. But for compatibility with
1133 * historical Postgres behavior, we do not force a transaction
1134 * boundary between queries appearing in a single query string.
1136 finish_xact_command();
1141 * We need a CommandCounterIncrement after every query, except
1142 * those that start or end a transaction block.
1144 CommandCounterIncrement();
1148 * Tell client that we're done with this query. Note we emit exactly
1149 * one EndCommand report for each raw parsetree, thus one for each SQL
1150 * command the client sent, regardless of rewriting. (But a command
1151 * aborted by error will not send an EndCommand report at all.)
1153 EndCommand(completionTag, dest);
1154 } /* end loop over parsetrees */
1157 * Close down transaction statement, if one is open.
1159 finish_xact_command();
1162 * If there were no parsetrees, return EmptyQueryResponse message.
1164 if (!parsetree_list)
1168 * Emit duration logging if appropriate.
1170 switch (check_log_duration(msec_str, was_logged))
1174 (errmsg("duration: %s ms", msec_str),
1175 errhidestmt(true)));
1179 (errmsg("duration: %s ms statement: %s",
1180 msec_str, query_string),
1182 errdetail_execute(parsetree_list)));
1186 if (save_log_statement_stats)
1187 ShowUsage("QUERY STATISTICS");
1189 TRACE_POSTGRESQL_QUERY_DONE(query_string);
1191 debug_query_string = NULL;
1195 * exec_parse_message
1197 * Execute a "Parse" protocol message.
1200 exec_parse_message(const char *query_string, /* string to execute */
1201 const char *stmt_name, /* name for prepared stmt */
1202 Oid *paramTypes, /* parameter types */
1203 int numParams) /* number of parameters */
1205 MemoryContext unnamed_stmt_context = NULL;
1206 MemoryContext oldcontext;
1207 List *parsetree_list;
1208 Node *raw_parse_tree;
1209 const char *commandTag;
1210 List *querytree_list;
1211 CachedPlanSource *psrc;
1213 bool save_log_statement_stats = log_statement_stats;
1217 * Report query to various monitoring facilities.
1219 debug_query_string = query_string;
1221 pgstat_report_activity(STATE_RUNNING, query_string);
1223 set_ps_display("PARSE", false);
1225 if (save_log_statement_stats)
1229 (errmsg("parse %s: %s",
1230 *stmt_name ? stmt_name : "<unnamed>",
1234 * Start up a transaction command so we can run parse analysis etc. (Note
1235 * that this will normally change current memory context.) Nothing happens
1236 * if we are already in one.
1238 start_xact_command();
1241 * Switch to appropriate context for constructing parsetrees.
1243 * We have two strategies depending on whether the prepared statement is
1244 * named or not. For a named prepared statement, we do parsing in
1245 * MessageContext and copy the finished trees into the prepared
1246 * statement's plancache entry; then the reset of MessageContext releases
1247 * temporary space used by parsing and rewriting. For an unnamed prepared
1248 * statement, we assume the statement isn't going to hang around long, so
1249 * getting rid of temp space quickly is probably not worth the costs of
1250 * copying parse trees. So in this case, we create the plancache entry's
1251 * query_context here, and do all the parsing work therein.
1253 is_named = (stmt_name[0] != '\0');
1256 /* Named prepared statement --- parse in MessageContext */
1257 oldcontext = MemoryContextSwitchTo(MessageContext);
1261 /* Unnamed prepared statement --- release any prior unnamed stmt */
1262 drop_unnamed_stmt();
1263 /* Create context for parsing */
1264 unnamed_stmt_context =
1265 AllocSetContextCreate(MessageContext,
1266 "unnamed prepared statement",
1267 ALLOCSET_DEFAULT_MINSIZE,
1268 ALLOCSET_DEFAULT_INITSIZE,
1269 ALLOCSET_DEFAULT_MAXSIZE);
1270 oldcontext = MemoryContextSwitchTo(unnamed_stmt_context);
1274 * Do basic parsing of the query or queries (this should be safe even if
1275 * we are in aborted transaction state!)
1277 parsetree_list = pg_parse_query(query_string);
1280 * We only allow a single user statement in a prepared statement. This is
1281 * mainly to keep the protocol simple --- otherwise we'd need to worry
1282 * about multiple result tupdescs and things like that.
1284 if (list_length(parsetree_list) > 1)
1286 (errcode(ERRCODE_SYNTAX_ERROR),
1287 errmsg("cannot insert multiple commands into a prepared statement")));
1289 if (parsetree_list != NIL)
1292 bool snapshot_set = false;
1295 raw_parse_tree = (Node *) linitial(parsetree_list);
1298 * Get the command name for possible use in status display.
1300 commandTag = CreateCommandTag(raw_parse_tree);
1303 * If we are in an aborted transaction, reject all commands except
1304 * COMMIT/ROLLBACK. It is important that this test occur before we
1305 * try to do parse analysis, rewrite, or planning, since all those
1306 * phases try to do database accesses, which may fail in abort state.
1307 * (It might be safe to allow some additional utility commands in this
1308 * state, but not many...)
1310 if (IsAbortedTransactionBlockState() &&
1311 !IsTransactionExitStmt(raw_parse_tree))
1313 (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
1314 errmsg("current transaction is aborted, "
1315 "commands ignored until end of transaction block"),
1316 errdetail_abort()));
1319 * Create the CachedPlanSource before we do parse analysis, since it
1320 * needs to see the unmodified raw parse tree.
1322 psrc = CreateCachedPlan(raw_parse_tree, query_string, commandTag);
1325 * Set up a snapshot if parse analysis will need one.
1327 if (analyze_requires_snapshot(raw_parse_tree))
1329 PushActiveSnapshot(GetTransactionSnapshot());
1330 snapshot_set = true;
1334 * Analyze and rewrite the query. Note that the originally specified
1335 * parameter set is not required to be complete, so we have to use
1336 * parse_analyze_varparams().
1338 if (log_parser_stats)
1341 query = parse_analyze_varparams(raw_parse_tree,
1347 * Check all parameter types got determined.
1349 for (i = 0; i < numParams; i++)
1351 Oid ptype = paramTypes[i];
1353 if (ptype == InvalidOid || ptype == UNKNOWNOID)
1355 (errcode(ERRCODE_INDETERMINATE_DATATYPE),
1356 errmsg("could not determine data type of parameter $%d",
1360 if (log_parser_stats)
1361 ShowUsage("PARSE ANALYSIS STATISTICS");
1363 querytree_list = pg_rewrite_query(query);
1365 /* Done with the snapshot used for parsing */
1367 PopActiveSnapshot();
1371 /* Empty input string. This is legal. */
1372 raw_parse_tree = NULL;
1374 psrc = CreateCachedPlan(raw_parse_tree, query_string, commandTag);
1375 querytree_list = NIL;
1379 * CachedPlanSource must be a direct child of MessageContext before we
1380 * reparent unnamed_stmt_context under it, else we have a disconnected
1381 * circular subgraph. Klugy, but less so than flipping contexts even more
1384 if (unnamed_stmt_context)
1385 MemoryContextSetParent(psrc->context, MessageContext);
1387 /* Finish filling in the CachedPlanSource */
1388 CompleteCachedPlan(psrc,
1390 unnamed_stmt_context,
1395 0, /* default cursor options */
1396 true); /* fixed result */
1398 /* If we got a cancel signal during analysis, quit */
1399 CHECK_FOR_INTERRUPTS();
1404 * Store the query as a prepared statement.
1406 StorePreparedStatement(stmt_name, psrc, false);
1411 * We just save the CachedPlanSource into unnamed_stmt_psrc.
1413 SaveCachedPlan(psrc);
1414 unnamed_stmt_psrc = psrc;
1417 MemoryContextSwitchTo(oldcontext);
1420 * We do NOT close the open transaction command here; that only happens
1421 * when the client sends Sync. Instead, do CommandCounterIncrement just
1422 * in case something happened during parse/plan.
1424 CommandCounterIncrement();
1427 * Send ParseComplete.
1429 if (whereToSendOutput == DestRemote)
1430 pq_putemptymessage('1');
1433 * Emit duration logging if appropriate.
1435 switch (check_log_duration(msec_str, false))
1439 (errmsg("duration: %s ms", msec_str),
1440 errhidestmt(true)));
1444 (errmsg("duration: %s ms parse %s: %s",
1446 *stmt_name ? stmt_name : "<unnamed>",
1448 errhidestmt(true)));
1452 if (save_log_statement_stats)
1453 ShowUsage("PARSE MESSAGE STATISTICS");
1455 debug_query_string = NULL;
1461 * Process a "Bind" message to create a portal from a prepared statement
1464 exec_bind_message(StringInfo input_message)
1466 const char *portal_name;
1467 const char *stmt_name;
1469 int16 *pformats = NULL;
1472 int16 *rformats = NULL;
1473 CachedPlanSource *psrc;
1477 char *saved_stmt_name;
1478 ParamListInfo params;
1479 MemoryContext oldContext;
1480 bool save_log_statement_stats = log_statement_stats;
1481 bool snapshot_set = false;
1484 /* Get the fixed part of the message */
1485 portal_name = pq_getmsgstring(input_message);
1486 stmt_name = pq_getmsgstring(input_message);
1489 (errmsg("bind %s to %s",
1490 *portal_name ? portal_name : "<unnamed>",
1491 *stmt_name ? stmt_name : "<unnamed>")));
1493 /* Find prepared statement */
1494 if (stmt_name[0] != '\0')
1496 PreparedStatement *pstmt;
1498 pstmt = FetchPreparedStatement(stmt_name, true);
1499 psrc = pstmt->plansource;
1503 /* special-case the unnamed statement */
1504 psrc = unnamed_stmt_psrc;
1507 (errcode(ERRCODE_UNDEFINED_PSTATEMENT),
1508 errmsg("unnamed prepared statement does not exist")));
1512 * Report query to various monitoring facilities.
1514 debug_query_string = psrc->query_string;
1516 pgstat_report_activity(STATE_RUNNING, psrc->query_string);
1518 set_ps_display("BIND", false);
1520 if (save_log_statement_stats)
1524 * Start up a transaction command so we can call functions etc. (Note that
1525 * this will normally change current memory context.) Nothing happens if
1526 * we are already in one.
1528 start_xact_command();
1530 /* Switch back to message context */
1531 MemoryContextSwitchTo(MessageContext);
1533 /* Get the parameter format codes */
1534 numPFormats = pq_getmsgint(input_message, 2);
1535 if (numPFormats > 0)
1539 pformats = (int16 *) palloc(numPFormats * sizeof(int16));
1540 for (i = 0; i < numPFormats; i++)
1541 pformats[i] = pq_getmsgint(input_message, 2);
1544 /* Get the parameter value count */
1545 numParams = pq_getmsgint(input_message, 2);
1547 if (numPFormats > 1 && numPFormats != numParams)
1549 (errcode(ERRCODE_PROTOCOL_VIOLATION),
1550 errmsg("bind message has %d parameter formats but %d parameters",
1551 numPFormats, numParams)));
1553 if (numParams != psrc->num_params)
1555 (errcode(ERRCODE_PROTOCOL_VIOLATION),
1556 errmsg("bind message supplies %d parameters, but prepared statement \"%s\" requires %d",
1557 numParams, stmt_name, psrc->num_params)));
1560 * If we are in aborted transaction state, the only portals we can
1561 * actually run are those containing COMMIT or ROLLBACK commands. We
1562 * disallow binding anything else to avoid problems with infrastructure
1563 * that expects to run inside a valid transaction. We also disallow
1564 * binding any parameters, since we can't risk calling user-defined I/O
1567 if (IsAbortedTransactionBlockState() &&
1568 (!IsTransactionExitStmt(psrc->raw_parse_tree) ||
1571 (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
1572 errmsg("current transaction is aborted, "
1573 "commands ignored until end of transaction block"),
1574 errdetail_abort()));
1577 * Create the portal. Allow silent replacement of an existing portal only
1578 * if the unnamed portal is specified.
1580 if (portal_name[0] == '\0')
1581 portal = CreatePortal(portal_name, true, true);
1583 portal = CreatePortal(portal_name, false, false);
1586 * Prepare to copy stuff into the portal's memory context. We do all this
1587 * copying first, because it could possibly fail (out-of-memory) and we
1588 * don't want a failure to occur between GetCachedPlan and
1589 * PortalDefineQuery; that would result in leaking our plancache refcount.
1591 oldContext = MemoryContextSwitchTo(PortalGetHeapMemory(portal));
1593 /* Copy the plan's query string into the portal */
1594 query_string = pstrdup(psrc->query_string);
1596 /* Likewise make a copy of the statement name, unless it's unnamed */
1598 saved_stmt_name = pstrdup(stmt_name);
1600 saved_stmt_name = NULL;
1603 * Set a snapshot if we have parameters to fetch (since the input
1604 * functions might need it) or the query isn't a utility command (and
1605 * hence could require redoing parse analysis and planning). We keep the
1606 * snapshot active till we're done, so that plancache.c doesn't have to
1609 if (numParams > 0 ||
1610 (psrc->raw_parse_tree &&
1611 analyze_requires_snapshot(psrc->raw_parse_tree)))
1613 PushActiveSnapshot(GetTransactionSnapshot());
1614 snapshot_set = true;
1618 * Fetch parameters, if any, and store in the portal's memory context.
1624 params = (ParamListInfo) palloc(offsetof(ParamListInfoData, params) +
1625 numParams * sizeof(ParamExternData));
1626 /* we have static list of params, so no hooks needed */
1627 params->paramFetch = NULL;
1628 params->paramFetchArg = NULL;
1629 params->parserSetup = NULL;
1630 params->parserSetupArg = NULL;
1631 params->numParams = numParams;
1633 for (paramno = 0; paramno < numParams; paramno++)
1635 Oid ptype = psrc->param_types[paramno];
1639 StringInfoData pbuf;
1643 plength = pq_getmsgint(input_message, 4);
1644 isNull = (plength == -1);
1648 const char *pvalue = pq_getmsgbytes(input_message, plength);
1651 * Rather than copying data around, we just set up a phony
1652 * StringInfo pointing to the correct portion of the message
1653 * buffer. We assume we can scribble on the message buffer so
1654 * as to maintain the convention that StringInfos have a
1655 * trailing null. This is grotty but is a big win when
1656 * dealing with very large parameter strings.
1658 pbuf.data = (char *) pvalue;
1659 pbuf.maxlen = plength + 1;
1663 csave = pbuf.data[plength];
1664 pbuf.data[plength] = '\0';
1668 pbuf.data = NULL; /* keep compiler quiet */
1672 if (numPFormats > 1)
1673 pformat = pformats[paramno];
1674 else if (numPFormats > 0)
1675 pformat = pformats[0];
1677 pformat = 0; /* default = text */
1679 if (pformat == 0) /* text mode */
1685 getTypeInputInfo(ptype, &typinput, &typioparam);
1688 * We have to do encoding conversion before calling the
1694 pstring = pg_client_to_server(pbuf.data, plength);
1696 pval = OidInputFunctionCall(typinput, pstring, typioparam, -1);
1698 /* Free result of encoding conversion, if any */
1699 if (pstring && pstring != pbuf.data)
1702 else if (pformat == 1) /* binary mode */
1709 * Call the parameter type's binary input converter
1711 getTypeBinaryInputInfo(ptype, &typreceive, &typioparam);
1718 pval = OidReceiveFunctionCall(typreceive, bufptr, typioparam, -1);
1720 /* Trouble if it didn't eat the whole buffer */
1721 if (!isNull && pbuf.cursor != pbuf.len)
1723 (errcode(ERRCODE_INVALID_BINARY_REPRESENTATION),
1724 errmsg("incorrect binary data format in bind parameter %d",
1730 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1731 errmsg("unsupported format code: %d",
1733 pval = 0; /* keep compiler quiet */
1736 /* Restore message buffer contents */
1738 pbuf.data[plength] = csave;
1740 params->params[paramno].value = pval;
1741 params->params[paramno].isnull = isNull;
1744 * We mark the params as CONST. This ensures that any custom plan
1745 * makes full use of the parameter values.
1747 params->params[paramno].pflags = PARAM_FLAG_CONST;
1748 params->params[paramno].ptype = ptype;
1754 /* Done storing stuff in portal's context */
1755 MemoryContextSwitchTo(oldContext);
1757 /* Get the result format codes */
1758 numRFormats = pq_getmsgint(input_message, 2);
1759 if (numRFormats > 0)
1763 rformats = (int16 *) palloc(numRFormats * sizeof(int16));
1764 for (i = 0; i < numRFormats; i++)
1765 rformats[i] = pq_getmsgint(input_message, 2);
1768 pq_getmsgend(input_message);
1771 * Obtain a plan from the CachedPlanSource. Any cruft from (re)planning
1772 * will be generated in MessageContext. The plan refcount will be
1773 * assigned to the Portal, so it will be released at portal destruction.
1775 cplan = GetCachedPlan(psrc, params, false);
1778 * Now we can define the portal.
1780 * DO NOT put any code that could possibly throw an error between the
1781 * above GetCachedPlan call and here.
1783 PortalDefineQuery(portal,
1790 /* Done with the snapshot used for parameter I/O and parsing/planning */
1792 PopActiveSnapshot();
1795 * And we're ready to start portal execution.
1797 PortalStart(portal, params, 0, InvalidSnapshot);
1800 * Apply the result format requests to the portal.
1802 PortalSetResultFormat(portal, numRFormats, rformats);
1805 * Send BindComplete.
1807 if (whereToSendOutput == DestRemote)
1808 pq_putemptymessage('2');
1811 * Emit duration logging if appropriate.
1813 switch (check_log_duration(msec_str, false))
1817 (errmsg("duration: %s ms", msec_str),
1818 errhidestmt(true)));
1822 (errmsg("duration: %s ms bind %s%s%s: %s",
1824 *stmt_name ? stmt_name : "<unnamed>",
1825 *portal_name ? "/" : "",
1826 *portal_name ? portal_name : "",
1827 psrc->query_string),
1829 errdetail_params(params)));
1833 if (save_log_statement_stats)
1834 ShowUsage("BIND MESSAGE STATISTICS");
1836 debug_query_string = NULL;
1840 * exec_execute_message
1842 * Process an "Execute" message for a portal
1845 exec_execute_message(const char *portal_name, long max_rows)
1848 DestReceiver *receiver;
1851 char completionTag[COMPLETION_TAG_BUFSIZE];
1852 const char *sourceText;
1853 const char *prepStmtName;
1854 ParamListInfo portalParams;
1855 bool save_log_statement_stats = log_statement_stats;
1856 bool is_xact_command;
1857 bool execute_is_fetch;
1858 bool was_logged = false;
1861 /* Adjust destination to tell printtup.c what to do */
1862 dest = whereToSendOutput;
1863 if (dest == DestRemote)
1864 dest = DestRemoteExecute;
1866 portal = GetPortalByName(portal_name);
1867 if (!PortalIsValid(portal))
1869 (errcode(ERRCODE_UNDEFINED_CURSOR),
1870 errmsg("portal \"%s\" does not exist", portal_name)));
1873 * If the original query was a null string, just return
1874 * EmptyQueryResponse.
1876 if (portal->commandTag == NULL)
1878 Assert(portal->stmts == NIL);
1883 /* Does the portal contain a transaction command? */
1884 is_xact_command = IsTransactionStmtList(portal->stmts);
1887 * We must copy the sourceText and prepStmtName into MessageContext in
1888 * case the portal is destroyed during finish_xact_command. Can avoid the
1889 * copy if it's not an xact command, though.
1891 if (is_xact_command)
1893 sourceText = pstrdup(portal->sourceText);
1894 if (portal->prepStmtName)
1895 prepStmtName = pstrdup(portal->prepStmtName);
1897 prepStmtName = "<unnamed>";
1900 * An xact command shouldn't have any parameters, which is a good
1901 * thing because they wouldn't be around after finish_xact_command.
1903 portalParams = NULL;
1907 sourceText = portal->sourceText;
1908 if (portal->prepStmtName)
1909 prepStmtName = portal->prepStmtName;
1911 prepStmtName = "<unnamed>";
1912 portalParams = portal->portalParams;
1916 * Report query to various monitoring facilities.
1918 debug_query_string = sourceText;
1920 pgstat_report_activity(STATE_RUNNING, sourceText);
1922 set_ps_display(portal->commandTag, false);
1924 if (save_log_statement_stats)
1927 BeginCommand(portal->commandTag, dest);
1930 * Create dest receiver in MessageContext (we don't want it in transaction
1931 * context, because that may get deleted if portal contains VACUUM).
1933 receiver = CreateDestReceiver(dest);
1934 if (dest == DestRemoteExecute)
1935 SetRemoteDestReceiverParams(receiver, portal);
1938 * Ensure we are in a transaction command (this should normally be the
1939 * case already due to prior BIND).
1941 start_xact_command();
1944 * If we re-issue an Execute protocol request against an existing portal,
1945 * then we are only fetching more rows rather than completely re-executing
1946 * the query from the start. atStart is never reset for a v3 portal, so we
1947 * are safe to use this check.
1949 execute_is_fetch = !portal->atStart;
1951 /* Log immediately if dictated by log_statement */
1952 if (check_log_statement(portal->stmts))
1955 (errmsg("%s %s%s%s: %s",
1957 _("execute fetch from") :
1960 *portal_name ? "/" : "",
1961 *portal_name ? portal_name : "",
1964 errdetail_params(portalParams)));
1969 * If we are in aborted transaction state, the only portals we can
1970 * actually run are those containing COMMIT or ROLLBACK commands.
1972 if (IsAbortedTransactionBlockState() &&
1973 !IsTransactionExitStmtList(portal->stmts))
1975 (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
1976 errmsg("current transaction is aborted, "
1977 "commands ignored until end of transaction block"),
1978 errdetail_abort()));
1980 /* Check for cancel signal before we start execution */
1981 CHECK_FOR_INTERRUPTS();
1984 * Okay to run the portal.
1987 max_rows = FETCH_ALL;
1989 completed = PortalRun(portal,
1991 true, /* always top level */
1996 (*receiver->rDestroy) (receiver);
2000 if (is_xact_command)
2003 * If this was a transaction control statement, commit it. We
2004 * will start a new xact command for the next command (if any).
2006 finish_xact_command();
2011 * We need a CommandCounterIncrement after every query, except
2012 * those that start or end a transaction block.
2014 CommandCounterIncrement();
2017 /* Send appropriate CommandComplete to client */
2018 EndCommand(completionTag, dest);
2022 /* Portal run not complete, so send PortalSuspended */
2023 if (whereToSendOutput == DestRemote)
2024 pq_putemptymessage('s');
2028 * Emit duration logging if appropriate.
2030 switch (check_log_duration(msec_str, was_logged))
2034 (errmsg("duration: %s ms", msec_str),
2035 errhidestmt(true)));
2039 (errmsg("duration: %s ms %s %s%s%s: %s",
2042 _("execute fetch from") :
2045 *portal_name ? "/" : "",
2046 *portal_name ? portal_name : "",
2049 errdetail_params(portalParams)));
2053 if (save_log_statement_stats)
2054 ShowUsage("EXECUTE MESSAGE STATISTICS");
2056 debug_query_string = NULL;
2060 * check_log_statement
2061 * Determine whether command should be logged because of log_statement
2063 * stmt_list can be either raw grammar output or a list of planned
2067 check_log_statement(List *stmt_list)
2069 ListCell *stmt_item;
2071 if (log_statement == LOGSTMT_NONE)
2073 if (log_statement == LOGSTMT_ALL)
2076 /* Else we have to inspect the statement(s) to see whether to log */
2077 foreach(stmt_item, stmt_list)
2079 Node *stmt = (Node *) lfirst(stmt_item);
2081 if (GetCommandLogLevel(stmt) <= log_statement)
2089 * check_log_duration
2090 * Determine whether current command's duration should be logged
2093 * 0 if no logging is needed
2094 * 1 if just the duration should be logged
2095 * 2 if duration and query details should be logged
2097 * If logging is needed, the duration in msec is formatted into msec_str[],
2098 * which must be a 32-byte buffer.
2100 * was_logged should be TRUE if caller already logged query details (this
2101 * essentially prevents 2 from being returned).
2104 check_log_duration(char *msec_str, bool was_logged)
2106 if (log_duration || log_min_duration_statement >= 0)
2113 TimestampDifference(GetCurrentStatementStartTimestamp(),
2114 GetCurrentTimestamp(),
2116 msecs = usecs / 1000;
2119 * This odd-looking test for log_min_duration_statement being exceeded
2120 * is designed to avoid integer overflow with very long durations:
2121 * don't compute secs * 1000 until we've verified it will fit in int.
2123 exceeded = (log_min_duration_statement == 0 ||
2124 (log_min_duration_statement > 0 &&
2125 (secs > log_min_duration_statement / 1000 ||
2126 secs * 1000 + msecs >= log_min_duration_statement)));
2128 if (exceeded || log_duration)
2130 snprintf(msec_str, 32, "%ld.%03d",
2131 secs * 1000 + msecs, usecs % 1000);
2132 if (exceeded && !was_logged)
2145 * Add an errdetail() line showing the query referenced by an EXECUTE, if any.
2146 * The argument is the raw parsetree list.
2149 errdetail_execute(List *raw_parsetree_list)
2151 ListCell *parsetree_item;
2153 foreach(parsetree_item, raw_parsetree_list)
2155 Node *parsetree = (Node *) lfirst(parsetree_item);
2157 if (IsA(parsetree, ExecuteStmt))
2159 ExecuteStmt *stmt = (ExecuteStmt *) parsetree;
2160 PreparedStatement *pstmt;
2162 pstmt = FetchPreparedStatement(stmt->name, false);
2165 errdetail("prepare: %s", pstmt->plansource->query_string);
2177 * Add an errdetail() line showing bind-parameter data, if available.
2180 errdetail_params(ParamListInfo params)
2182 /* We mustn't call user-defined I/O functions when in an aborted xact */
2183 if (params && params->numParams > 0 && !IsAbortedTransactionBlockState())
2185 StringInfoData param_str;
2186 MemoryContext oldcontext;
2189 /* Make sure any trash is generated in MessageContext */
2190 oldcontext = MemoryContextSwitchTo(MessageContext);
2192 initStringInfo(¶m_str);
2194 for (paramno = 0; paramno < params->numParams; paramno++)
2196 ParamExternData *prm = ¶ms->params[paramno];
2202 appendStringInfo(¶m_str, "%s$%d = ",
2203 paramno > 0 ? ", " : "",
2206 if (prm->isnull || !OidIsValid(prm->ptype))
2208 appendStringInfoString(¶m_str, "NULL");
2212 getTypeOutputInfo(prm->ptype, &typoutput, &typisvarlena);
2214 pstring = OidOutputFunctionCall(typoutput, prm->value);
2216 appendStringInfoCharMacro(¶m_str, '\'');
2217 for (p = pstring; *p; p++)
2219 if (*p == '\'') /* double single quotes */
2220 appendStringInfoCharMacro(¶m_str, *p);
2221 appendStringInfoCharMacro(¶m_str, *p);
2223 appendStringInfoCharMacro(¶m_str, '\'');
2228 errdetail("parameters: %s", param_str.data);
2230 pfree(param_str.data);
2232 MemoryContextSwitchTo(oldcontext);
2241 * Add an errdetail() line showing abort reason, if any.
2244 errdetail_abort(void)
2246 if (MyProc->recoveryConflictPending)
2247 errdetail("abort reason: recovery conflict");
2253 * errdetail_recovery_conflict
2255 * Add an errdetail() line showing conflict source.
2258 errdetail_recovery_conflict(void)
2260 switch (RecoveryConflictReason)
2262 case PROCSIG_RECOVERY_CONFLICT_BUFFERPIN:
2263 errdetail("User was holding shared buffer pin for too long.");
2265 case PROCSIG_RECOVERY_CONFLICT_LOCK:
2266 errdetail("User was holding a relation lock for too long.");
2268 case PROCSIG_RECOVERY_CONFLICT_TABLESPACE:
2269 errdetail("User was or might have been using tablespace that must be dropped.");
2271 case PROCSIG_RECOVERY_CONFLICT_SNAPSHOT:
2272 errdetail("User query might have needed to see row versions that must be removed.");
2274 case PROCSIG_RECOVERY_CONFLICT_STARTUP_DEADLOCK:
2275 errdetail("User transaction caused buffer deadlock with recovery.");
2277 case PROCSIG_RECOVERY_CONFLICT_DATABASE:
2278 errdetail("User was connected to a database that must be dropped.");
2289 * exec_describe_statement_message
2291 * Process a "Describe" message for a prepared statement
2294 exec_describe_statement_message(const char *stmt_name)
2296 CachedPlanSource *psrc;
2301 * Start up a transaction command. (Note that this will normally change
2302 * current memory context.) Nothing happens if we are already in one.
2304 start_xact_command();
2306 /* Switch back to message context */
2307 MemoryContextSwitchTo(MessageContext);
2309 /* Find prepared statement */
2310 if (stmt_name[0] != '\0')
2312 PreparedStatement *pstmt;
2314 pstmt = FetchPreparedStatement(stmt_name, true);
2315 psrc = pstmt->plansource;
2319 /* special-case the unnamed statement */
2320 psrc = unnamed_stmt_psrc;
2323 (errcode(ERRCODE_UNDEFINED_PSTATEMENT),
2324 errmsg("unnamed prepared statement does not exist")));
2327 /* Prepared statements shouldn't have changeable result descs */
2328 Assert(psrc->fixed_result);
2331 * If we are in aborted transaction state, we can't run
2332 * SendRowDescriptionMessage(), because that needs catalog accesses.
2333 * Hence, refuse to Describe statements that return data. (We shouldn't
2334 * just refuse all Describes, since that might break the ability of some
2335 * clients to issue COMMIT or ROLLBACK commands, if they use code that
2336 * blindly Describes whatever it does.) We can Describe parameters
2337 * without doing anything dangerous, so we don't restrict that.
2339 if (IsAbortedTransactionBlockState() &&
2342 (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
2343 errmsg("current transaction is aborted, "
2344 "commands ignored until end of transaction block"),
2345 errdetail_abort()));
2347 if (whereToSendOutput != DestRemote)
2348 return; /* can't actually do anything... */
2351 * First describe the parameters...
2353 pq_beginmessage(&buf, 't'); /* parameter description message type */
2354 pq_sendint(&buf, psrc->num_params, 2);
2356 for (i = 0; i < psrc->num_params; i++)
2358 Oid ptype = psrc->param_types[i];
2360 pq_sendint(&buf, (int) ptype, 4);
2362 pq_endmessage(&buf);
2365 * Next send RowDescription or NoData to describe the result...
2367 if (psrc->resultDesc)
2371 /* Get the plan's primary targetlist */
2372 tlist = CachedPlanGetTargetList(psrc);
2374 SendRowDescriptionMessage(psrc->resultDesc, tlist, NULL);
2377 pq_putemptymessage('n'); /* NoData */
2382 * exec_describe_portal_message
2384 * Process a "Describe" message for a portal
2387 exec_describe_portal_message(const char *portal_name)
2392 * Start up a transaction command. (Note that this will normally change
2393 * current memory context.) Nothing happens if we are already in one.
2395 start_xact_command();
2397 /* Switch back to message context */
2398 MemoryContextSwitchTo(MessageContext);
2400 portal = GetPortalByName(portal_name);
2401 if (!PortalIsValid(portal))
2403 (errcode(ERRCODE_UNDEFINED_CURSOR),
2404 errmsg("portal \"%s\" does not exist", portal_name)));
2407 * If we are in aborted transaction state, we can't run
2408 * SendRowDescriptionMessage(), because that needs catalog accesses.
2409 * Hence, refuse to Describe portals that return data. (We shouldn't just
2410 * refuse all Describes, since that might break the ability of some
2411 * clients to issue COMMIT or ROLLBACK commands, if they use code that
2412 * blindly Describes whatever it does.)
2414 if (IsAbortedTransactionBlockState() &&
2417 (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
2418 errmsg("current transaction is aborted, "
2419 "commands ignored until end of transaction block"),
2420 errdetail_abort()));
2422 if (whereToSendOutput != DestRemote)
2423 return; /* can't actually do anything... */
2425 if (portal->tupDesc)
2426 SendRowDescriptionMessage(portal->tupDesc,
2427 FetchPortalTargetList(portal),
2430 pq_putemptymessage('n'); /* NoData */
2435 * Convenience routines for starting/committing a single command.
2438 start_xact_command(void)
2443 (errmsg_internal("StartTransactionCommand")));
2444 StartTransactionCommand();
2446 /* Set statement timeout running, if any */
2447 /* NB: this mustn't be enabled until we are within an xact */
2448 if (StatementTimeout > 0)
2449 enable_timeout_after(STATEMENT_TIMEOUT, StatementTimeout);
2451 disable_timeout(STATEMENT_TIMEOUT, false);
2453 xact_started = true;
2458 finish_xact_command(void)
2462 /* Cancel any active statement timeout before committing */
2463 disable_timeout(STATEMENT_TIMEOUT, false);
2465 /* Now commit the command */
2467 (errmsg_internal("CommitTransactionCommand")));
2469 CommitTransactionCommand();
2471 #ifdef MEMORY_CONTEXT_CHECKING
2472 /* Check all memory contexts that weren't freed during commit */
2473 /* (those that were, were checked before being deleted) */
2474 MemoryContextCheck(TopMemoryContext);
2477 #ifdef SHOW_MEMORY_STATS
2478 /* Print mem stats after each commit for leak tracking */
2479 MemoryContextStats(TopMemoryContext);
2482 xact_started = false;
2488 * Convenience routines for checking whether a statement is one of the
2489 * ones that we allow in transaction-aborted state.
2492 /* Test a bare parsetree */
2494 IsTransactionExitStmt(Node *parsetree)
2496 if (parsetree && IsA(parsetree, TransactionStmt))
2498 TransactionStmt *stmt = (TransactionStmt *) parsetree;
2500 if (stmt->kind == TRANS_STMT_COMMIT ||
2501 stmt->kind == TRANS_STMT_PREPARE ||
2502 stmt->kind == TRANS_STMT_ROLLBACK ||
2503 stmt->kind == TRANS_STMT_ROLLBACK_TO)
2509 /* Test a list that might contain Query nodes or bare parsetrees */
2511 IsTransactionExitStmtList(List *parseTrees)
2513 if (list_length(parseTrees) == 1)
2515 Node *stmt = (Node *) linitial(parseTrees);
2517 if (IsA(stmt, Query))
2519 Query *query = (Query *) stmt;
2521 if (query->commandType == CMD_UTILITY &&
2522 IsTransactionExitStmt(query->utilityStmt))
2525 else if (IsTransactionExitStmt(stmt))
2531 /* Test a list that might contain Query nodes or bare parsetrees */
2533 IsTransactionStmtList(List *parseTrees)
2535 if (list_length(parseTrees) == 1)
2537 Node *stmt = (Node *) linitial(parseTrees);
2539 if (IsA(stmt, Query))
2541 Query *query = (Query *) stmt;
2543 if (query->commandType == CMD_UTILITY &&
2544 IsA(query->utilityStmt, TransactionStmt))
2547 else if (IsA(stmt, TransactionStmt))
2553 /* Release any existing unnamed prepared statement */
2555 drop_unnamed_stmt(void)
2557 /* paranoia to avoid a dangling pointer in case of error */
2558 if (unnamed_stmt_psrc)
2560 CachedPlanSource *psrc = unnamed_stmt_psrc;
2562 unnamed_stmt_psrc = NULL;
2563 DropCachedPlan(psrc);
2568 /* --------------------------------
2569 * signal handler routines used in PostgresMain()
2570 * --------------------------------
2574 * quickdie() occurs when signalled SIGQUIT by the postmaster.
2576 * Some backend has bought the farm,
2577 * so we need to stop what we're doing and exit.
2580 quickdie(SIGNAL_ARGS)
2582 sigaddset(&BlockSig, SIGQUIT); /* prevent nested calls */
2583 PG_SETMASK(&BlockSig);
2586 * Prevent interrupts while exiting; though we just blocked signals that
2587 * would queue new interrupts, one may have been pending. We don't want a
2588 * quickdie() downgraded to a mere query cancel.
2593 * If we're aborting out of client auth, don't risk trying to send
2594 * anything to the client; we will likely violate the protocol, not to
2595 * mention that we may have interrupted the guts of OpenSSL or some
2596 * authentication library.
2598 if (ClientAuthInProgress && whereToSendOutput == DestRemote)
2599 whereToSendOutput = DestNone;
2602 * Ideally this should be ereport(FATAL), but then we'd not get control
2606 (errcode(ERRCODE_CRASH_SHUTDOWN),
2607 errmsg("terminating connection because of crash of another server process"),
2608 errdetail("The postmaster has commanded this server process to roll back"
2609 " the current transaction and exit, because another"
2610 " server process exited abnormally and possibly corrupted"
2612 errhint("In a moment you should be able to reconnect to the"
2613 " database and repeat your command.")));
2616 * We DO NOT want to run proc_exit() callbacks -- we're here because
2617 * shared memory may be corrupted, so we don't want to try to clean up our
2618 * transaction. Just nail the windows shut and get out of town. Now that
2619 * there's an atexit callback to prevent third-party code from breaking
2620 * things by calling exit() directly, we have to reset the callbacks
2621 * explicitly to make this work as intended.
2626 * Note we do exit(2) not exit(0). This is to force the postmaster into a
2627 * system reset cycle if some idiot DBA sends a manual SIGQUIT to a random
2628 * backend. This is necessary precisely because we don't clean up our
2629 * shared memory state. (The "dead man switch" mechanism in pmsignal.c
2630 * should ensure the postmaster sees this as a crash, too, but no harm in
2631 * being doubly sure.)
2637 * Shutdown signal from postmaster: abort transaction and exit
2638 * at soonest convenient time
2643 int save_errno = errno;
2645 /* Don't joggle the elbow of proc_exit */
2646 if (!proc_exit_inprogress)
2648 InterruptPending = true;
2649 ProcDiePending = true;
2652 /* If we're still here, waken anything waiting on the process latch */
2656 * If we're in single user mode, we want to quit immediately - we can't
2657 * rely on latches as they wouldn't work when stdin/stdout is a file.
2658 * Rather ugly, but it's unlikely to be worthwhile to invest much more
2659 * effort just for the benefit of single user mode.
2661 if (DoingCommandRead && whereToSendOutput != DestRemote)
2662 ProcessInterrupts();
2668 * Query-cancel signal from postmaster: abort current transaction
2669 * at soonest convenient time
2672 StatementCancelHandler(SIGNAL_ARGS)
2674 int save_errno = errno;
2677 * Don't joggle the elbow of proc_exit
2679 if (!proc_exit_inprogress)
2681 InterruptPending = true;
2682 QueryCancelPending = true;
2685 /* If we're still here, waken anything waiting on the process latch */
2691 /* signal handler for floating point exception */
2693 FloatExceptionHandler(SIGNAL_ARGS)
2695 /* We're not returning, so no need to save errno */
2697 (errcode(ERRCODE_FLOATING_POINT_EXCEPTION),
2698 errmsg("floating-point exception"),
2699 errdetail("An invalid floating-point operation was signaled. "
2700 "This probably means an out-of-range result or an "
2701 "invalid operation, such as division by zero.")));
2704 /* SIGHUP: set flag to re-read config file at next convenient time */
2706 SigHupHandler(SIGNAL_ARGS)
2708 int save_errno = errno;
2717 * RecoveryConflictInterrupt: out-of-line portion of recovery conflict
2718 * handling following receipt of SIGUSR1. Designed to be similar to die()
2719 * and StatementCancelHandler(). Called only by a normal user backend
2720 * that begins a transaction during recovery.
2723 RecoveryConflictInterrupt(ProcSignalReason reason)
2725 int save_errno = errno;
2728 * Don't joggle the elbow of proc_exit
2730 if (!proc_exit_inprogress)
2732 RecoveryConflictReason = reason;
2735 case PROCSIG_RECOVERY_CONFLICT_STARTUP_DEADLOCK:
2738 * If we aren't waiting for a lock we can never deadlock.
2740 if (!IsWaitingForLock())
2743 /* Intentional drop through to check wait for pin */
2745 case PROCSIG_RECOVERY_CONFLICT_BUFFERPIN:
2748 * If we aren't blocking the Startup process there is nothing
2751 if (!HoldingBufferPinThatDelaysRecovery())
2754 MyProc->recoveryConflictPending = true;
2756 /* Intentional drop through to error handling */
2758 case PROCSIG_RECOVERY_CONFLICT_LOCK:
2759 case PROCSIG_RECOVERY_CONFLICT_TABLESPACE:
2760 case PROCSIG_RECOVERY_CONFLICT_SNAPSHOT:
2763 * If we aren't in a transaction any longer then ignore.
2765 if (!IsTransactionOrTransactionBlock())
2769 * If we can abort just the current subtransaction then we are
2770 * OK to throw an ERROR to resolve the conflict. Otherwise
2771 * drop through to the FATAL case.
2773 * XXX other times that we can throw just an ERROR *may* be
2774 * PROCSIG_RECOVERY_CONFLICT_LOCK if no locks are held in
2775 * parent transactions
2777 * PROCSIG_RECOVERY_CONFLICT_SNAPSHOT if no snapshots are held
2778 * by parent transactions and the transaction is not
2779 * transaction-snapshot mode
2781 * PROCSIG_RECOVERY_CONFLICT_TABLESPACE if no temp files or
2782 * cursors open in parent transactions
2784 if (!IsSubTransaction())
2787 * If we already aborted then we no longer need to cancel.
2788 * We do this here since we do not wish to ignore aborted
2789 * subtransactions, which must cause FATAL, currently.
2791 if (IsAbortedTransactionBlockState())
2794 RecoveryConflictPending = true;
2795 QueryCancelPending = true;
2796 InterruptPending = true;
2800 /* Intentional drop through to session cancel */
2802 case PROCSIG_RECOVERY_CONFLICT_DATABASE:
2803 RecoveryConflictPending = true;
2804 ProcDiePending = true;
2805 InterruptPending = true;
2809 elog(FATAL, "unrecognized conflict mode: %d",
2813 Assert(RecoveryConflictPending && (QueryCancelPending || ProcDiePending));
2816 * All conflicts apart from database cause dynamic errors where the
2817 * command or transaction can be retried at a later point with some
2818 * potential for success. No need to reset this, since non-retryable
2819 * conflict errors are currently FATAL.
2821 if (reason == PROCSIG_RECOVERY_CONFLICT_DATABASE)
2822 RecoveryConflictRetryable = false;
2826 * Set the process latch. This function essentially emulates signal
2827 * handlers like die() and StatementCancelHandler() and it seems prudent
2828 * to behave similarly as they do. Alternatively all plain backend code
2829 * waiting on that latch, expecting to get interrupted by query cancels et
2830 * al., would also need to set set_latch_on_sigusr1.
2838 * ProcessInterrupts: out-of-line portion of CHECK_FOR_INTERRUPTS() macro
2840 * If an interrupt condition is pending, and it's safe to service it,
2841 * then clear the flag and accept the interrupt. Called only when
2842 * InterruptPending is true.
2845 ProcessInterrupts(void)
2847 /* OK to accept any interrupts now? */
2848 if (InterruptHoldoffCount != 0 || CritSectionCount != 0)
2850 InterruptPending = false;
2854 ProcDiePending = false;
2855 QueryCancelPending = false; /* ProcDie trumps QueryCancel */
2857 /* As in quickdie, don't risk sending to client during auth */
2858 if (ClientAuthInProgress && whereToSendOutput == DestRemote)
2859 whereToSendOutput = DestNone;
2860 if (ClientAuthInProgress)
2862 (errcode(ERRCODE_QUERY_CANCELED),
2863 errmsg("canceling authentication due to timeout")));
2864 else if (IsAutoVacuumWorkerProcess())
2866 (errcode(ERRCODE_ADMIN_SHUTDOWN),
2867 errmsg("terminating autovacuum process due to administrator command")));
2868 else if (RecoveryConflictPending && RecoveryConflictRetryable)
2870 pgstat_report_recovery_conflict(RecoveryConflictReason);
2872 (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
2873 errmsg("terminating connection due to conflict with recovery"),
2874 errdetail_recovery_conflict()));
2876 else if (RecoveryConflictPending)
2878 /* Currently there is only one non-retryable recovery conflict */
2879 Assert(RecoveryConflictReason == PROCSIG_RECOVERY_CONFLICT_DATABASE);
2880 pgstat_report_recovery_conflict(RecoveryConflictReason);
2882 (errcode(ERRCODE_DATABASE_DROPPED),
2883 errmsg("terminating connection due to conflict with recovery"),
2884 errdetail_recovery_conflict()));
2888 (errcode(ERRCODE_ADMIN_SHUTDOWN),
2889 errmsg("terminating connection due to administrator command")));
2891 if (ClientConnectionLost)
2893 QueryCancelPending = false; /* lost connection trumps QueryCancel */
2895 /* don't send to client, we already know the connection to be dead. */
2896 whereToSendOutput = DestNone;
2898 (errcode(ERRCODE_CONNECTION_FAILURE),
2899 errmsg("connection to client lost")));
2903 * If a recovery conflict happens while we are waiting for input from the
2904 * client, the client is presumably just sitting idle in a transaction,
2905 * preventing recovery from making progress. Terminate the connection to
2908 if (RecoveryConflictPending && DoingCommandRead)
2910 QueryCancelPending = false; /* this trumps QueryCancel */
2911 RecoveryConflictPending = false;
2913 pgstat_report_recovery_conflict(RecoveryConflictReason);
2915 (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
2916 errmsg("terminating connection due to conflict with recovery"),
2917 errdetail_recovery_conflict(),
2918 errhint("In a moment you should be able to reconnect to the"
2919 " database and repeat your command.")));
2922 if (QueryCancelPending)
2925 * Don't allow query cancel interrupts while reading input from the
2926 * client, because we might lose sync in the FE/BE protocol. (Die
2927 * interrupts are OK, because we won't read any further messages from
2928 * the client in that case.)
2930 if (QueryCancelHoldoffCount != 0)
2933 * Re-arm InterruptPending so that we process the cancel request
2934 * as soon as we're done reading the message.
2936 InterruptPending = true;
2940 QueryCancelPending = false;
2943 * If LOCK_TIMEOUT and STATEMENT_TIMEOUT indicators are both set, we
2944 * prefer to report the former; but be sure to clear both.
2946 if (get_timeout_indicator(LOCK_TIMEOUT, true))
2948 (void) get_timeout_indicator(STATEMENT_TIMEOUT, true);
2951 (errcode(ERRCODE_LOCK_NOT_AVAILABLE),
2952 errmsg("canceling statement due to lock timeout")));
2954 if (get_timeout_indicator(STATEMENT_TIMEOUT, true))
2958 (errcode(ERRCODE_QUERY_CANCELED),
2959 errmsg("canceling statement due to statement timeout")));
2961 if (IsAutoVacuumWorkerProcess())
2965 (errcode(ERRCODE_QUERY_CANCELED),
2966 errmsg("canceling autovacuum task")));
2968 if (RecoveryConflictPending)
2970 RecoveryConflictPending = false;
2972 pgstat_report_recovery_conflict(RecoveryConflictReason);
2974 (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
2975 errmsg("canceling statement due to conflict with recovery"),
2976 errdetail_recovery_conflict()));
2980 * If we are reading a command from the client, just ignore the cancel
2981 * request --- sending an extra error message won't accomplish
2982 * anything. Otherwise, go ahead and throw the error.
2984 if (!DoingCommandRead)
2988 (errcode(ERRCODE_QUERY_CANCELED),
2989 errmsg("canceling statement due to user request")));
2993 if (ParallelMessagePending)
2994 HandleParallelMessages();
2999 * IA64-specific code to fetch the AR.BSP register for stack depth checks.
3001 * We currently support gcc, icc, and HP-UX's native compiler here.
3003 * Note: while icc accepts gcc asm blocks on x86[_64], this is not true on
3004 * ia64 (at least not in icc versions before 12.x). So we have to carry a
3005 * separate implementation for it.
3007 #if defined(__ia64__) || defined(__ia64)
3009 #if defined(__hpux) && !defined(__GNUC__) && !defined(__INTEL_COMPILER)
3010 /* Assume it's HP-UX native compiler */
3011 #include <ia64/sys/inline.h>
3012 #define ia64_get_bsp() ((char *) (_Asm_mov_from_ar(_AREG_BSP, _NO_FENCE)))
3013 #elif defined(__INTEL_COMPILER)
3015 #include <asm/ia64regs.h>
3016 #define ia64_get_bsp() ((char *) __getReg(_IA64_REG_AR_BSP))
3019 static __inline__ char *
3024 /* the ;; is a "stop", seems to be required before fetching BSP */
3025 __asm__ __volatile__(
3037 * set_stack_base: set up reference point for stack depth checking
3039 * Returns the old reference point, if any.
3042 set_stack_base(void)
3045 pg_stack_base_t old;
3047 #if defined(__ia64__) || defined(__ia64)
3048 old.stack_base_ptr = stack_base_ptr;
3049 old.register_stack_base_ptr = register_stack_base_ptr;
3051 old = stack_base_ptr;
3054 /* Set up reference point for stack depth checking */
3055 stack_base_ptr = &stack_base;
3056 #if defined(__ia64__) || defined(__ia64)
3057 register_stack_base_ptr = ia64_get_bsp();
3064 * restore_stack_base: restore reference point for stack depth checking
3066 * This can be used after set_stack_base() to restore the old value. This
3067 * is currently only used in PL/Java. When PL/Java calls a backend function
3068 * from different thread, the thread's stack is at a different location than
3069 * the main thread's stack, so it sets the base pointer before the call, and
3070 * restores it afterwards.
3073 restore_stack_base(pg_stack_base_t base)
3075 #if defined(__ia64__) || defined(__ia64)
3076 stack_base_ptr = base.stack_base_ptr;
3077 register_stack_base_ptr = base.register_stack_base_ptr;
3079 stack_base_ptr = base;
3084 * check_stack_depth/stack_is_too_deep: check for excessively deep recursion
3086 * This should be called someplace in any recursive routine that might possibly
3087 * recurse deep enough to overflow the stack. Most Unixen treat stack
3088 * overflow as an unrecoverable SIGSEGV, so we want to error out ourselves
3089 * before hitting the hardware limit.
3091 * check_stack_depth() just throws an error summarily. stack_is_too_deep()
3092 * can be used by code that wants to handle the error condition itself.
3095 check_stack_depth(void)
3097 if (stack_is_too_deep())
3100 (errcode(ERRCODE_STATEMENT_TOO_COMPLEX),
3101 errmsg("stack depth limit exceeded"),
3102 errhint("Increase the configuration parameter \"max_stack_depth\" (currently %dkB), "
3103 "after ensuring the platform's stack depth limit is adequate.",
3109 stack_is_too_deep(void)
3115 * Compute distance from reference point to my local variables
3117 stack_depth = (long) (stack_base_ptr - &stack_top_loc);
3120 * Take abs value, since stacks grow up on some machines, down on others
3122 if (stack_depth < 0)
3123 stack_depth = -stack_depth;
3128 * The test on stack_base_ptr prevents us from erroring out if called
3129 * during process setup or in a non-backend process. Logically it should
3130 * be done first, but putting it here avoids wasting cycles during normal
3133 if (stack_depth > max_stack_depth_bytes &&
3134 stack_base_ptr != NULL)
3138 * On IA64 there is a separate "register" stack that requires its own
3139 * independent check. For this, we have to measure the change in the
3140 * "BSP" pointer from PostgresMain to here. Logic is just as above,
3141 * except that we know IA64's register stack grows up.
3143 * Note we assume that the same max_stack_depth applies to both stacks.
3145 #if defined(__ia64__) || defined(__ia64)
3146 stack_depth = (long) (ia64_get_bsp() - register_stack_base_ptr);
3148 if (stack_depth > max_stack_depth_bytes &&
3149 register_stack_base_ptr != NULL)
3156 /* GUC check hook for max_stack_depth */
3158 check_max_stack_depth(int *newval, void **extra, GucSource source)
3160 long newval_bytes = *newval * 1024L;
3161 long stack_rlimit = get_stack_depth_rlimit();
3163 if (stack_rlimit > 0 && newval_bytes > stack_rlimit - STACK_DEPTH_SLOP)
3165 GUC_check_errdetail("\"max_stack_depth\" must not exceed %ldkB.",
3166 (stack_rlimit - STACK_DEPTH_SLOP) / 1024L);
3167 GUC_check_errhint("Increase the platform's stack depth limit via \"ulimit -s\" or local equivalent.");
3173 /* GUC assign hook for max_stack_depth */
3175 assign_max_stack_depth(int newval, void *extra)
3177 long newval_bytes = newval * 1024L;
3179 max_stack_depth_bytes = newval_bytes;
3184 * set_debug_options --- apply "-d N" command line option
3186 * -d is not quite the same as setting log_min_messages because it enables
3187 * other output options.
3190 set_debug_options(int debug_flag, GucContext context, GucSource source)
3196 sprintf(debugstr, "debug%d", debug_flag);
3197 SetConfigOption("log_min_messages", debugstr, context, source);
3200 SetConfigOption("log_min_messages", "notice", context, source);
3202 if (debug_flag >= 1 && context == PGC_POSTMASTER)
3204 SetConfigOption("log_connections", "true", context, source);
3205 SetConfigOption("log_disconnections", "true", context, source);
3207 if (debug_flag >= 2)
3208 SetConfigOption("log_statement", "all", context, source);
3209 if (debug_flag >= 3)
3210 SetConfigOption("debug_print_parse", "true", context, source);
3211 if (debug_flag >= 4)
3212 SetConfigOption("debug_print_plan", "true", context, source);
3213 if (debug_flag >= 5)
3214 SetConfigOption("debug_print_rewritten", "true", context, source);
3219 set_plan_disabling_options(const char *arg, GucContext context, GucSource source)
3221 const char *tmp = NULL;
3225 case 's': /* seqscan */
3226 tmp = "enable_seqscan";
3228 case 'i': /* indexscan */
3229 tmp = "enable_indexscan";
3231 case 'o': /* indexonlyscan */
3232 tmp = "enable_indexonlyscan";
3234 case 'b': /* bitmapscan */
3235 tmp = "enable_bitmapscan";
3237 case 't': /* tidscan */
3238 tmp = "enable_tidscan";
3240 case 'n': /* nestloop */
3241 tmp = "enable_nestloop";
3243 case 'm': /* mergejoin */
3244 tmp = "enable_mergejoin";
3246 case 'h': /* hashjoin */
3247 tmp = "enable_hashjoin";
3252 SetConfigOption(tmp, "false", context, source);
3261 get_stats_option_name(const char *arg)
3266 if (optarg[1] == 'a') /* "parser" */
3267 return "log_parser_stats";
3268 else if (optarg[1] == 'l') /* "planner" */
3269 return "log_planner_stats";
3272 case 'e': /* "executor" */
3273 return "log_executor_stats";
3281 /* ----------------------------------------------------------------
3282 * process_postgres_switches
3283 * Parse command line arguments for PostgresMain
3285 * This is called twice, once for the "secure" options coming from the
3286 * postmaster or command line, and once for the "insecure" options coming
3287 * from the client's startup packet. The latter have the same syntax but
3288 * may be restricted in what they can do.
3290 * argv[0] is ignored in either case (it's assumed to be the program name).
3292 * ctx is PGC_POSTMASTER for secure options, PGC_BACKEND for insecure options
3293 * coming from the client, or PGC_SU_BACKEND for insecure options coming from
3294 * a superuser client.
3296 * If a database name is present in the command line arguments, it's
3297 * returned into *dbname (this is allowed only if *dbname is initially NULL).
3298 * ----------------------------------------------------------------
3301 process_postgres_switches(int argc, char *argv[], GucContext ctx,
3302 const char **dbname)
3304 bool secure = (ctx == PGC_POSTMASTER);
3306 GucSource gucsource;
3311 gucsource = PGC_S_ARGV; /* switches came from command line */
3313 /* Ignore the initial --single argument, if present */
3314 if (argc > 1 && strcmp(argv[1], "--single") == 0)
3322 gucsource = PGC_S_CLIENT; /* switches came from client */
3325 #ifdef HAVE_INT_OPTERR
3328 * Turn this off because it's either printed to stderr and not the log
3329 * where we'd want it, or argv[0] is now "--single", which would make for
3330 * a weird error message. We print our own error message below.
3336 * Parse command-line options. CAUTION: keep this in sync with
3337 * postmaster/postmaster.c (the option sets should not conflict) and with
3338 * the common help() function in main/main.c.
3340 while ((flag = getopt(argc, argv, "B:bc:C:D:d:EeFf:h:ijk:lN:nOo:Pp:r:S:sTt:v:W:-:")) != -1)
3345 SetConfigOption("shared_buffers", optarg, ctx, gucsource);
3349 /* Undocumented flag used for binary upgrades */
3351 IsBinaryUpgrade = true;
3355 /* ignored for consistency with the postmaster */
3360 userDoption = strdup(optarg);
3364 set_debug_options(atoi(optarg), ctx, gucsource);
3373 SetConfigOption("datestyle", "euro", ctx, gucsource);
3377 SetConfigOption("fsync", "false", ctx, gucsource);
3381 if (!set_plan_disabling_options(optarg, ctx, gucsource))
3386 SetConfigOption("listen_addresses", optarg, ctx, gucsource);
3390 SetConfigOption("listen_addresses", "*", ctx, gucsource);
3399 SetConfigOption("unix_socket_directories", optarg, ctx, gucsource);
3403 SetConfigOption("ssl", "true", ctx, gucsource);
3407 SetConfigOption("max_connections", optarg, ctx, gucsource);
3411 /* ignored for consistency with postmaster */
3415 SetConfigOption("allow_system_table_mods", "true", ctx, gucsource);
3423 SetConfigOption("ignore_system_indexes", "true", ctx, gucsource);
3427 SetConfigOption("port", optarg, ctx, gucsource);
3431 /* send output (stdout and stderr) to the given file */
3433 strlcpy(OutputFileName, optarg, MAXPGPATH);
3437 SetConfigOption("work_mem", optarg, ctx, gucsource);
3441 SetConfigOption("log_statement_stats", "true", ctx, gucsource);
3445 /* ignored for consistency with the postmaster */
3450 const char *tmp = get_stats_option_name(optarg);
3453 SetConfigOption(tmp, "true", ctx, gucsource);
3462 * -v is no longer used in normal operation, since
3463 * FrontendProtocol is already set before we get here. We keep
3464 * the switch only for possible use in standalone operation,
3465 * in case we ever support using normal FE/BE protocol with a
3466 * standalone backend.
3469 FrontendProtocol = (ProtocolVersion) atoi(optarg);
3473 SetConfigOption("post_auth_delay", optarg, ctx, gucsource);
3482 ParseLongOption(optarg, &name, &value);
3487 (errcode(ERRCODE_SYNTAX_ERROR),
3488 errmsg("--%s requires a value",
3492 (errcode(ERRCODE_SYNTAX_ERROR),
3493 errmsg("-c %s requires a value",
3496 SetConfigOption(name, value, ctx, gucsource);
3513 * Optional database name should be there only if *dbname is NULL.
3515 if (!errs && dbname && *dbname == NULL && argc - optind >= 1)
3516 *dbname = strdup(argv[optind++]);
3518 if (errs || argc != optind)
3521 optind--; /* complain about the previous argument */
3523 /* spell the error message a bit differently depending on context */
3524 if (IsUnderPostmaster)
3526 (errcode(ERRCODE_SYNTAX_ERROR),
3527 errmsg("invalid command-line argument for server process: %s", argv[optind]),
3528 errhint("Try \"%s --help\" for more information.", progname)));
3531 (errcode(ERRCODE_SYNTAX_ERROR),
3532 errmsg("%s: invalid command-line argument: %s",
3533 progname, argv[optind]),
3534 errhint("Try \"%s --help\" for more information.", progname)));
3538 * Reset getopt(3) library so that it will work correctly in subprocesses
3539 * or when this function is called a second time with another array.
3542 #ifdef HAVE_INT_OPTRESET
3543 optreset = 1; /* some systems need this too */
3548 /* ----------------------------------------------------------------
3550 * postgres main loop -- all backends, interactive or otherwise start here
3552 * argc/argv are the command line arguments to be used. (When being forked
3553 * by the postmaster, these are not the original argv array of the process.)
3554 * dbname is the name of the database to connect to, or NULL if the database
3555 * name should be extracted from the command line arguments or defaulted.
3556 * username is the PostgreSQL user name to be used for the session.
3557 * ----------------------------------------------------------------
3560 PostgresMain(int argc, char *argv[],
3562 const char *username)
3565 StringInfoData input_message;
3566 sigjmp_buf local_sigjmp_buf;
3567 volatile bool send_ready_for_query = true;
3569 /* Initialize startup process environment if necessary. */
3570 if (!IsUnderPostmaster)
3571 InitStandaloneProcess(argv[0]);
3573 SetProcessingMode(InitProcessing);
3576 * Set default values for command-line options.
3578 if (!IsUnderPostmaster)
3579 InitializeGUCOptions();
3582 * Parse command-line options.
3584 process_postgres_switches(argc, argv, PGC_POSTMASTER, &dbname);
3586 /* Must have gotten a database name, or have a default (the username) */
3592 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
3593 errmsg("%s: no database nor user name specified",
3597 /* Acquire configuration parameters, unless inherited from postmaster */
3598 if (!IsUnderPostmaster)
3600 if (!SelectConfigFiles(userDoption, progname))
3605 * Set up signal handlers and masks.
3607 * Note that postmaster blocked all signals before forking child process,
3608 * so there is no race condition whereby we might receive a signal before
3609 * we have set up the handler.
3611 * Also note: it's best not to use any signals that are SIG_IGNored in the
3612 * postmaster. If such a signal arrives before we are able to change the
3613 * handler to non-SIG_IGN, it'll get dropped. Instead, make a dummy
3614 * handler in the postmaster to reserve the signal. (Of course, this isn't
3615 * an issue for signals that are locally generated, such as SIGALRM and
3622 pqsignal(SIGHUP, SigHupHandler); /* set flag to read config
3624 pqsignal(SIGINT, StatementCancelHandler); /* cancel current query */
3625 pqsignal(SIGTERM, die); /* cancel current query and exit */
3628 * In a standalone backend, SIGQUIT can be generated from the keyboard
3629 * easily, while SIGTERM cannot, so we make both signals do die()
3630 * rather than quickdie().
3632 if (IsUnderPostmaster)
3633 pqsignal(SIGQUIT, quickdie); /* hard crash time */
3635 pqsignal(SIGQUIT, die); /* cancel current query and exit */
3636 InitializeTimeouts(); /* establishes SIGALRM handler */
3639 * Ignore failure to write to frontend. Note: if frontend closes
3640 * connection, we will notice it and exit cleanly when control next
3641 * returns to outer loop. This seems safer than forcing exit in the
3642 * midst of output during who-knows-what operation...
3644 pqsignal(SIGPIPE, SIG_IGN);
3645 pqsignal(SIGUSR1, procsignal_sigusr1_handler);
3646 pqsignal(SIGUSR2, SIG_IGN);
3647 pqsignal(SIGFPE, FloatExceptionHandler);
3650 * Reset some signals that are accepted by postmaster but not by
3653 pqsignal(SIGCHLD, SIG_DFL); /* system() requires this on some
3659 if (IsUnderPostmaster)
3661 /* We allow SIGQUIT (quickdie) at all times */
3662 sigdelset(&BlockSig, SIGQUIT);
3665 PG_SETMASK(&BlockSig); /* block everything except SIGQUIT */
3667 if (!IsUnderPostmaster)
3670 * Validate we have been given a reasonable-looking DataDir (if under
3671 * postmaster, assume postmaster did this already).
3674 ValidatePgVersion(DataDir);
3676 /* Change into DataDir (if under postmaster, was done already) */
3680 * Create lockfile for data directory.
3682 CreateDataDirLockFile(false);
3684 /* Initialize MaxBackends (if under postmaster, was done already) */
3685 InitializeMaxBackends();
3688 /* Early initialization */
3692 * Create a per-backend PGPROC struct in shared memory, except in the
3693 * EXEC_BACKEND case where this was done in SubPostmasterMain. We must do
3694 * this before we can use LWLocks (and in the EXEC_BACKEND case we already
3695 * had to do some stuff with LWLocks).
3698 if (!IsUnderPostmaster)
3704 /* We need to allow SIGINT, etc during the initial transaction */
3705 PG_SETMASK(&UnBlockSig);
3708 * General initialization.
3710 * NOTE: if you are tempted to add code in this vicinity, consider putting
3711 * it inside InitPostgres() instead. In particular, anything that
3712 * involves database access should be there, not here.
3714 InitPostgres(dbname, InvalidOid, username, InvalidOid, NULL);
3717 * If the PostmasterContext is still around, recycle the space; we don't
3718 * need it anymore after InitPostgres completes. Note this does not trash
3719 * *MyProcPort, because ConnCreate() allocated that space with malloc()
3720 * ... else we'd need to copy the Port data first. Also, subsidiary data
3721 * such as the username isn't lost either; see ProcessStartupPacket().
3723 if (PostmasterContext)
3725 MemoryContextDelete(PostmasterContext);
3726 PostmasterContext = NULL;
3729 SetProcessingMode(NormalProcessing);
3732 * Now all GUC states are fully set up. Report them to client if
3735 BeginReportingGUCOptions();
3738 * Also set up handler to log session end; we have to wait till now to be
3739 * sure Log_disconnections has its final value.
3741 if (IsUnderPostmaster && Log_disconnections)
3742 on_proc_exit(log_disconnections, 0);
3744 /* Perform initialization specific to a WAL sender process. */
3749 * process any libraries that should be preloaded at backend start (this
3750 * likewise can't be done until GUC settings are complete)
3752 process_session_preload_libraries();
3755 * Send this backend's cancellation info to the frontend.
3757 if (whereToSendOutput == DestRemote &&
3758 PG_PROTOCOL_MAJOR(FrontendProtocol) >= 2)
3762 pq_beginmessage(&buf, 'K');
3763 pq_sendint(&buf, (int32) MyProcPid, sizeof(int32));
3764 pq_sendint(&buf, (int32) MyCancelKey, sizeof(int32));
3765 pq_endmessage(&buf);
3766 /* Need not flush since ReadyForQuery will do it. */
3769 /* Welcome banner for standalone case */
3770 if (whereToSendOutput == DestDebug)
3771 printf("\nPostgreSQL stand-alone backend %s\n", PG_VERSION);
3774 * Create the memory context we will use in the main loop.
3776 * MessageContext is reset once per iteration of the main loop, ie, upon
3777 * completion of processing of each command message from the client.
3779 MessageContext = AllocSetContextCreate(TopMemoryContext,
3781 ALLOCSET_DEFAULT_MINSIZE,
3782 ALLOCSET_DEFAULT_INITSIZE,
3783 ALLOCSET_DEFAULT_MAXSIZE);
3786 * Remember stand-alone backend startup time
3788 if (!IsUnderPostmaster)
3789 PgStartTime = GetCurrentTimestamp();
3792 * POSTGRES main processing loop begins here
3794 * If an exception is encountered, processing resumes here so we abort the
3795 * current transaction and start a new one.
3797 * You might wonder why this isn't coded as an infinite loop around a
3798 * PG_TRY construct. The reason is that this is the bottom of the
3799 * exception stack, and so with PG_TRY there would be no exception handler
3800 * in force at all during the CATCH part. By leaving the outermost setjmp
3801 * always active, we have at least some chance of recovering from an error
3802 * during error recovery. (If we get into an infinite loop thereby, it
3803 * will soon be stopped by overflow of elog.c's internal state stack.)
3805 * Note that we use sigsetjmp(..., 1), so that this function's signal mask
3806 * (to wit, UnBlockSig) will be restored when longjmp'ing to here. This
3807 * is essential in case we longjmp'd out of a signal handler on a platform
3808 * where that leaves the signal blocked. It's not redundant with the
3809 * unblock in AbortTransaction() because the latter is only called if we
3810 * were inside a transaction.
3813 if (sigsetjmp(local_sigjmp_buf, 1) != 0)
3816 * NOTE: if you are tempted to add more code in this if-block,
3817 * consider the high probability that it should be in
3818 * AbortTransaction() instead. The only stuff done directly here
3819 * should be stuff that is guaranteed to apply *only* for outer-level
3820 * error recovery, such as adjusting the FE/BE protocol status.
3823 /* Since not using PG_TRY, must reset error stack by hand */
3824 error_context_stack = NULL;
3826 /* Prevent interrupts while cleaning up */
3830 * Forget any pending QueryCancel request, since we're returning to
3831 * the idle loop anyway, and cancel any active timeout requests. (In
3832 * future we might want to allow some timeout requests to survive, but
3833 * at minimum it'd be necessary to do reschedule_timeouts(), in case
3834 * we got here because of a query cancel interrupting the SIGALRM
3835 * interrupt handler.) Note in particular that we must clear the
3836 * statement and lock timeout indicators, to prevent any future plain
3837 * query cancels from being misreported as timeouts in case we're
3838 * forgetting a timeout cancel.
3840 disable_all_timeouts(false);
3841 QueryCancelPending = false; /* second to avoid race condition */
3843 /* Not reading from the client anymore. */
3844 DoingCommandRead = false;
3846 /* Make sure libpq is in a good state */
3849 /* Report the error to the client and/or server log */
3853 * Make sure debug_query_string gets reset before we possibly clobber
3854 * the storage it points at.
3856 debug_query_string = NULL;
3859 * Abort the current transaction in order to recover.
3861 AbortCurrentTransaction();
3864 WalSndErrorCleanup();
3867 * We can't release replication slots inside AbortTransaction() as we
3868 * need to be able to start and abort transactions while having a slot
3869 * acquired. But we never need to hold them across top level errors,
3870 * so releasing here is fine. There's another cleanup in ProcKill()
3871 * ensuring we'll correctly cleanup on FATAL errors as well.
3873 if (MyReplicationSlot != NULL)
3874 ReplicationSlotRelease();
3877 * Now return to normal top-level context and clear ErrorContext for
3880 MemoryContextSwitchTo(TopMemoryContext);
3884 * If we were handling an extended-query-protocol message, initiate
3885 * skip till next Sync. This also causes us not to issue
3886 * ReadyForQuery (until we get Sync).
3888 if (doing_extended_query_message)
3889 ignore_till_sync = true;
3891 /* We don't have a transaction command open anymore */
3892 xact_started = false;
3895 * If an error occurred while we were reading a message from the
3896 * client, we have potentially lost track of where the previous
3897 * message ends and the next one begins. Even though we have
3898 * otherwise recovered from the error, we cannot safely read any more
3899 * messages from the client, so there isn't much we can do with the
3900 * connection anymore.
3902 if (pq_is_reading_msg())
3904 (errcode(ERRCODE_PROTOCOL_VIOLATION),
3905 errmsg("terminating connection because protocol sync was lost")));
3907 /* Now we can allow interrupts again */
3908 RESUME_INTERRUPTS();
3911 /* We can now handle ereport(ERROR) */
3912 PG_exception_stack = &local_sigjmp_buf;
3914 if (!ignore_till_sync)
3915 send_ready_for_query = true; /* initially, or after error */
3918 * Non-error queries loop here.
3924 * At top of loop, reset extended-query-message flag, so that any
3925 * errors encountered in "idle" state don't provoke skip.
3927 doing_extended_query_message = false;
3930 * Release storage left over from prior query cycle, and create a new
3931 * query input buffer in the cleared MessageContext.
3933 MemoryContextSwitchTo(MessageContext);
3934 MemoryContextResetAndDeleteChildren(MessageContext);
3936 initStringInfo(&input_message);
3939 * (1) If we've reached idle state, tell the frontend we're ready for
3942 * Note: this includes fflush()'ing the last of the prior output.
3944 * This is also a good time to send collected statistics to the
3945 * collector, and to update the PS stats display. We avoid doing
3946 * those every time through the message loop because it'd slow down
3947 * processing of batched messages, and because we don't want to report
3948 * uncommitted updates (that confuses autovacuum). The notification
3949 * processor wants a call too, if we are not in a transaction block.
3951 if (send_ready_for_query)
3953 if (IsAbortedTransactionBlockState())
3955 set_ps_display("idle in transaction (aborted)", false);
3956 pgstat_report_activity(STATE_IDLEINTRANSACTION_ABORTED, NULL);
3958 else if (IsTransactionOrTransactionBlock())
3960 set_ps_display("idle in transaction", false);
3961 pgstat_report_activity(STATE_IDLEINTRANSACTION, NULL);
3965 ProcessCompletedNotifies();
3966 pgstat_report_stat(false);
3968 set_ps_display("idle", false);
3969 pgstat_report_activity(STATE_IDLE, NULL);
3972 ReadyForQuery(whereToSendOutput);
3973 send_ready_for_query = false;
3977 * (2) Allow asynchronous signals to be executed immediately if they
3978 * come in while we are waiting for client input. (This must be
3979 * conditional since we don't want, say, reads on behalf of COPY FROM
3980 * STDIN doing the same thing.)
3982 DoingCommandRead = true;
3985 * (3) read a command (loop blocks here)
3987 firstchar = ReadCommand(&input_message);
3990 * (4) disable async signal conditions again.
3992 * Query cancel is supposed to be a no-op when there is no query in
3993 * progress, so if a query cancel arrived while we were idle, just
3994 * reset QueryCancelPending. ProcessInterrupts() has that effect when
3995 * it's called when DoingCommandRead is set, so check for interrupts
3996 * before resetting DoingCommandRead.
3998 CHECK_FOR_INTERRUPTS();
3999 DoingCommandRead = false;
4002 * (5) check for any other interesting events that happened while we
4008 ProcessConfigFile(PGC_SIGHUP);
4012 * (6) process the command. But ignore it if we're skipping till
4015 if (ignore_till_sync && firstchar != EOF)
4020 case 'Q': /* simple query */
4022 const char *query_string;
4024 /* Set statement_timestamp() */
4025 SetCurrentStatementStartTimestamp();
4027 query_string = pq_getmsgstring(&input_message);
4028 pq_getmsgend(&input_message);
4031 exec_replication_command(query_string);
4033 exec_simple_query(query_string);
4035 send_ready_for_query = true;
4039 case 'P': /* parse */
4041 const char *stmt_name;
4042 const char *query_string;
4044 Oid *paramTypes = NULL;
4046 forbidden_in_wal_sender(firstchar);
4048 /* Set statement_timestamp() */
4049 SetCurrentStatementStartTimestamp();
4051 stmt_name = pq_getmsgstring(&input_message);
4052 query_string = pq_getmsgstring(&input_message);
4053 numParams = pq_getmsgint(&input_message, 2);
4058 paramTypes = (Oid *) palloc(numParams * sizeof(Oid));
4059 for (i = 0; i < numParams; i++)
4060 paramTypes[i] = pq_getmsgint(&input_message, 4);
4062 pq_getmsgend(&input_message);
4064 exec_parse_message(query_string, stmt_name,
4065 paramTypes, numParams);
4069 case 'B': /* bind */
4070 forbidden_in_wal_sender(firstchar);
4072 /* Set statement_timestamp() */
4073 SetCurrentStatementStartTimestamp();
4076 * this message is complex enough that it seems best to put
4077 * the field extraction out-of-line
4079 exec_bind_message(&input_message);
4082 case 'E': /* execute */
4084 const char *portal_name;
4087 forbidden_in_wal_sender(firstchar);
4089 /* Set statement_timestamp() */
4090 SetCurrentStatementStartTimestamp();
4092 portal_name = pq_getmsgstring(&input_message);
4093 max_rows = pq_getmsgint(&input_message, 4);
4094 pq_getmsgend(&input_message);
4096 exec_execute_message(portal_name, max_rows);
4100 case 'F': /* fastpath function call */
4101 forbidden_in_wal_sender(firstchar);
4103 /* Set statement_timestamp() */
4104 SetCurrentStatementStartTimestamp();
4106 /* Report query to various monitoring facilities. */
4107 pgstat_report_activity(STATE_FASTPATH, NULL);
4108 set_ps_display("<FASTPATH>", false);
4110 /* start an xact for this function invocation */
4111 start_xact_command();
4114 * Note: we may at this point be inside an aborted
4115 * transaction. We can't throw error for that until we've
4116 * finished reading the function-call message, so
4117 * HandleFunctionRequest() must check for it after doing so.
4118 * Be careful not to do anything that assumes we're inside a
4119 * valid transaction here.
4122 /* switch back to message context */
4123 MemoryContextSwitchTo(MessageContext);
4125 if (HandleFunctionRequest(&input_message) == EOF)
4127 /* lost frontend connection during F message input */
4130 * Reset whereToSendOutput to prevent ereport from
4131 * attempting to send any more messages to client.
4133 if (whereToSendOutput == DestRemote)
4134 whereToSendOutput = DestNone;
4139 /* commit the function-invocation transaction */
4140 finish_xact_command();
4142 send_ready_for_query = true;
4145 case 'C': /* close */
4148 const char *close_target;
4150 forbidden_in_wal_sender(firstchar);
4152 close_type = pq_getmsgbyte(&input_message);
4153 close_target = pq_getmsgstring(&input_message);
4154 pq_getmsgend(&input_message);
4159 if (close_target[0] != '\0')
4160 DropPreparedStatement(close_target, false);
4163 /* special-case the unnamed statement */
4164 drop_unnamed_stmt();
4171 portal = GetPortalByName(close_target);
4172 if (PortalIsValid(portal))
4173 PortalDrop(portal, false);
4178 (errcode(ERRCODE_PROTOCOL_VIOLATION),
4179 errmsg("invalid CLOSE message subtype %d",
4184 if (whereToSendOutput == DestRemote)
4185 pq_putemptymessage('3'); /* CloseComplete */
4189 case 'D': /* describe */
4192 const char *describe_target;
4194 forbidden_in_wal_sender(firstchar);
4196 /* Set statement_timestamp() (needed for xact) */
4197 SetCurrentStatementStartTimestamp();
4199 describe_type = pq_getmsgbyte(&input_message);
4200 describe_target = pq_getmsgstring(&input_message);
4201 pq_getmsgend(&input_message);
4203 switch (describe_type)
4206 exec_describe_statement_message(describe_target);
4209 exec_describe_portal_message(describe_target);
4213 (errcode(ERRCODE_PROTOCOL_VIOLATION),
4214 errmsg("invalid DESCRIBE message subtype %d",
4221 case 'H': /* flush */
4222 pq_getmsgend(&input_message);
4223 if (whereToSendOutput == DestRemote)
4227 case 'S': /* sync */
4228 pq_getmsgend(&input_message);
4229 finish_xact_command();
4230 send_ready_for_query = true;
4234 * 'X' means that the frontend is closing down the socket. EOF
4235 * means unexpected loss of frontend connection. Either way,
4236 * perform normal shutdown.
4242 * Reset whereToSendOutput to prevent ereport from attempting
4243 * to send any more messages to client.
4245 if (whereToSendOutput == DestRemote)
4246 whereToSendOutput = DestNone;
4249 * NOTE: if you are tempted to add more code here, DON'T!
4250 * Whatever you had in mind to do should be set up as an
4251 * on_proc_exit or on_shmem_exit callback, instead. Otherwise
4252 * it will fail to be called during other backend-shutdown
4257 case 'd': /* copy data */
4258 case 'c': /* copy done */
4259 case 'f': /* copy fail */
4262 * Accept but ignore these messages, per protocol spec; we
4263 * probably got here because a COPY failed, and the frontend
4264 * is still sending data.
4270 (errcode(ERRCODE_PROTOCOL_VIOLATION),
4271 errmsg("invalid frontend message type %d",
4274 } /* end of input-reading loop */
4278 * Throw an error if we're a WAL sender process.
4280 * This is used to forbid anything else than simple query protocol messages
4281 * in a WAL sender process. 'firstchar' specifies what kind of a forbidden
4282 * message was received, and is used to construct the error message.
4285 forbidden_in_wal_sender(char firstchar)
4289 if (firstchar == 'F')
4291 (errcode(ERRCODE_PROTOCOL_VIOLATION),
4292 errmsg("fastpath function calls not supported in a replication connection")));
4295 (errcode(ERRCODE_PROTOCOL_VIOLATION),
4296 errmsg("extended query protocol not supported in a replication connection")));
4302 * Obtain platform stack depth limit (in bytes)
4304 * Return -1 if unknown
4307 get_stack_depth_rlimit(void)
4309 #if defined(HAVE_GETRLIMIT) && defined(RLIMIT_STACK)
4310 static long val = 0;
4312 /* This won't change after process launch, so check just once */
4317 if (getrlimit(RLIMIT_STACK, &rlim) < 0)
4319 else if (rlim.rlim_cur == RLIM_INFINITY)
4321 /* rlim_cur is probably of an unsigned type, so check for overflow */
4322 else if (rlim.rlim_cur >= LONG_MAX)
4325 val = rlim.rlim_cur;
4328 #else /* no getrlimit */
4329 #if defined(WIN32) || defined(__CYGWIN__)
4330 /* On Windows we set the backend stack size in src/backend/Makefile */
4331 return WIN32_STACK_RLIMIT;
4332 #else /* not windows ... give up */
4339 static struct rusage Save_r;
4340 static struct timeval Save_t;
4345 getrusage(RUSAGE_SELF, &Save_r);
4346 gettimeofday(&Save_t, NULL);
4350 ShowUsage(const char *title)
4353 struct timeval user,
4355 struct timeval elapse_t;
4358 getrusage(RUSAGE_SELF, &r);
4359 gettimeofday(&elapse_t, NULL);
4360 memcpy((char *) &user, (char *) &r.ru_utime, sizeof(user));
4361 memcpy((char *) &sys, (char *) &r.ru_stime, sizeof(sys));
4362 if (elapse_t.tv_usec < Save_t.tv_usec)
4365 elapse_t.tv_usec += 1000000;
4367 if (r.ru_utime.tv_usec < Save_r.ru_utime.tv_usec)
4369 r.ru_utime.tv_sec--;
4370 r.ru_utime.tv_usec += 1000000;
4372 if (r.ru_stime.tv_usec < Save_r.ru_stime.tv_usec)
4374 r.ru_stime.tv_sec--;
4375 r.ru_stime.tv_usec += 1000000;
4379 * the only stats we don't show here are for memory usage -- i can't
4380 * figure out how to interpret the relevant fields in the rusage struct,
4381 * and they change names across o/s platforms, anyway. if you can figure
4382 * out what the entries mean, you can somehow extract resident set size,
4383 * shared text size, and unshared data and stack sizes.
4385 initStringInfo(&str);
4387 appendStringInfoString(&str, "! system usage stats:\n");
4388 appendStringInfo(&str,
4389 "!\t%ld.%06ld elapsed %ld.%06ld user %ld.%06ld system sec\n",
4390 (long) (elapse_t.tv_sec - Save_t.tv_sec),
4391 (long) (elapse_t.tv_usec - Save_t.tv_usec),
4392 (long) (r.ru_utime.tv_sec - Save_r.ru_utime.tv_sec),
4393 (long) (r.ru_utime.tv_usec - Save_r.ru_utime.tv_usec),
4394 (long) (r.ru_stime.tv_sec - Save_r.ru_stime.tv_sec),
4395 (long) (r.ru_stime.tv_usec - Save_r.ru_stime.tv_usec));
4396 appendStringInfo(&str,
4397 "!\t[%ld.%06ld user %ld.%06ld sys total]\n",
4399 (long) user.tv_usec,
4401 (long) sys.tv_usec);
4402 #if defined(HAVE_GETRUSAGE)
4403 appendStringInfo(&str,
4404 "!\t%ld/%ld [%ld/%ld] filesystem blocks in/out\n",
4405 r.ru_inblock - Save_r.ru_inblock,
4406 /* they only drink coffee at dec */
4407 r.ru_oublock - Save_r.ru_oublock,
4408 r.ru_inblock, r.ru_oublock);
4409 appendStringInfo(&str,
4410 "!\t%ld/%ld [%ld/%ld] page faults/reclaims, %ld [%ld] swaps\n",
4411 r.ru_majflt - Save_r.ru_majflt,
4412 r.ru_minflt - Save_r.ru_minflt,
4413 r.ru_majflt, r.ru_minflt,
4414 r.ru_nswap - Save_r.ru_nswap,
4416 appendStringInfo(&str,
4417 "!\t%ld [%ld] signals rcvd, %ld/%ld [%ld/%ld] messages rcvd/sent\n",
4418 r.ru_nsignals - Save_r.ru_nsignals,
4420 r.ru_msgrcv - Save_r.ru_msgrcv,
4421 r.ru_msgsnd - Save_r.ru_msgsnd,
4422 r.ru_msgrcv, r.ru_msgsnd);
4423 appendStringInfo(&str,
4424 "!\t%ld/%ld [%ld/%ld] voluntary/involuntary context switches\n",
4425 r.ru_nvcsw - Save_r.ru_nvcsw,
4426 r.ru_nivcsw - Save_r.ru_nivcsw,
4427 r.ru_nvcsw, r.ru_nivcsw);
4428 #endif /* HAVE_GETRUSAGE */
4430 /* remove trailing newline */
4431 if (str.data[str.len - 1] == '\n')
4432 str.data[--str.len] = '\0';
4435 (errmsg_internal("%s", title),
4436 errdetail_internal("%s", str.data)));
4442 * on_proc_exit handler to log end of session
4445 log_disconnections(int code, Datum arg)
4447 Port *port = MyProcPort;
4455 TimestampDifference(port->SessionStartTime,
4456 GetCurrentTimestamp(),
4458 msecs = usecs / 1000;
4460 hours = secs / SECS_PER_HOUR;
4461 secs %= SECS_PER_HOUR;
4462 minutes = secs / SECS_PER_MINUTE;
4463 seconds = secs % SECS_PER_MINUTE;
4466 (errmsg("disconnection: session time: %d:%02d:%02d.%03d "
4467 "user=%s database=%s host=%s%s%s",
4468 hours, minutes, seconds, msecs,
4469 port->user_name, port->database_name, port->remote_host,
4470 port->remote_port[0] ? " port=" : "", port->remote_port)));