1 /*-------------------------------------------------------------------------
4 * POSTGRES C Backend Interface
6 * Portions Copyright (c) 1996-2013, 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 *-------------------------------------------------------------------------
27 #include <sys/socket.h>
28 #ifdef HAVE_SYS_SELECT_H
29 #include <sys/select.h>
31 #ifdef HAVE_SYS_RESOURCE_H
33 #include <sys/resource.h>
39 #ifndef HAVE_GETRUSAGE
40 #include "rusagestub.h"
43 #include "access/printtup.h"
44 #include "access/xact.h"
45 #include "catalog/pg_type.h"
46 #include "commands/async.h"
47 #include "commands/prepare.h"
48 #include "libpq/libpq.h"
49 #include "libpq/pqformat.h"
50 #include "libpq/pqsignal.h"
51 #include "miscadmin.h"
52 #include "nodes/print.h"
53 #include "optimizer/planner.h"
56 #include "parser/analyze.h"
57 #include "parser/parser.h"
58 #include "postmaster/autovacuum.h"
59 #include "postmaster/postmaster.h"
60 #include "replication/walsender.h"
61 #include "rewrite/rewriteHandler.h"
62 #include "storage/bufmgr.h"
63 #include "storage/ipc.h"
64 #include "storage/proc.h"
65 #include "storage/procsignal.h"
66 #include "storage/sinval.h"
67 #include "tcop/fastpath.h"
68 #include "tcop/pquery.h"
69 #include "tcop/tcopprot.h"
70 #include "tcop/utility.h"
71 #include "utils/lsyscache.h"
72 #include "utils/memutils.h"
73 #include "utils/ps_status.h"
74 #include "utils/snapmgr.h"
75 #include "utils/timeout.h"
76 #include "utils/timestamp.h"
77 #include "mb/pg_wchar.h"
83 #ifdef HAVE_INT_OPTRESET
84 extern int optreset; /* might not be declared by system headers */
92 const char *debug_query_string; /* client-supplied query string */
94 /* Note: whereToSendOutput is initialized for the bootstrap/standalone case */
95 CommandDest whereToSendOutput = DestDebug;
97 /* flag for logging end of session */
98 bool Log_disconnections = false;
100 int log_statement = LOGSTMT_NONE;
102 /* GUC variable for maximum stack depth (measured in kilobytes) */
103 int max_stack_depth = 100;
105 /* wait N seconds to allow attach from a debugger */
106 int PostAuthDelay = 0;
115 /* max_stack_depth converted to bytes for speed of checking */
116 static long max_stack_depth_bytes = 100 * 1024L;
119 * Stack base pointer -- initialized by PostmasterMain and inherited by
120 * subprocesses. This is not static because old versions of PL/Java modify
121 * it directly. Newer versions use set_stack_base(), but we want to stay
122 * binary-compatible for the time being.
124 char *stack_base_ptr = NULL;
127 * On IA64 we also have to remember the register stack base.
129 #if defined(__ia64__) || defined(__ia64)
130 char *register_stack_base_ptr = NULL;
134 * Flag to mark SIGHUP. Whenever the main loop comes around it
135 * will reread the configuration file. (Better than doing the
136 * reading in the signal handler, ey?)
138 static volatile sig_atomic_t got_SIGHUP = false;
141 * Flag to keep track of whether we have started a transaction.
142 * For extended query protocol this has to be remembered across messages.
144 static bool xact_started = false;
147 * Flag to indicate that we are doing the outer loop's read-from-client,
148 * as opposed to any random read from client that might happen within
149 * commands like COPY FROM STDIN.
151 static bool DoingCommandRead = false;
154 * Flags to implement skip-till-Sync-after-error behavior for messages of
155 * the extended query protocol.
157 static bool doing_extended_query_message = false;
158 static bool ignore_till_sync = false;
161 * If an unnamed prepared statement exists, it's stored here.
162 * We keep it separate from the hashtable kept by commands/prepare.c
163 * in order to reduce overhead for short-lived queries.
165 static CachedPlanSource *unnamed_stmt_psrc = NULL;
167 /* assorted command-line switches */
168 static const char *userDoption = NULL; /* -D switch */
170 static bool EchoQuery = false; /* -E switch */
173 * people who want to use EOF should #define DONTUSENEWLINE in
176 #ifndef TCOP_DONTUSENEWLINE
177 static int UseNewLine = 1; /* Use newlines query delimiters (the default) */
179 static int UseNewLine = 0; /* Use EOF as query delimiters */
180 #endif /* TCOP_DONTUSENEWLINE */
182 /* whether or not, and why, we were canceled by conflict with recovery */
183 static bool RecoveryConflictPending = false;
184 static bool RecoveryConflictRetryable = true;
185 static ProcSignalReason RecoveryConflictReason;
187 /* ----------------------------------------------------------------
188 * decls for routines only used in this file
189 * ----------------------------------------------------------------
191 static int InteractiveBackend(StringInfo inBuf);
192 static int interactive_getc(void);
193 static int SocketBackend(StringInfo inBuf);
194 static int ReadCommand(StringInfo inBuf);
195 static void forbidden_in_wal_sender(char firstchar);
196 static List *pg_rewrite_query(Query *query);
197 static bool check_log_statement(List *stmt_list);
198 static int errdetail_execute(List *raw_parsetree_list);
199 static int errdetail_params(ParamListInfo params);
200 static int errdetail_abort(void);
201 static int errdetail_recovery_conflict(void);
202 static void start_xact_command(void);
203 static void finish_xact_command(void);
204 static bool IsTransactionExitStmt(Node *parsetree);
205 static bool IsTransactionExitStmtList(List *parseTrees);
206 static bool IsTransactionStmtList(List *parseTrees);
207 static void drop_unnamed_stmt(void);
208 static void SigHupHandler(SIGNAL_ARGS);
209 static void log_disconnections(int code, Datum arg);
212 /* ----------------------------------------------------------------
213 * routines to obtain user input
214 * ----------------------------------------------------------------
218 * InteractiveBackend() is called for user interactive connections
220 * the string entered by the user is placed in its parameter inBuf,
221 * and we act like a Q message was received.
223 * EOF is returned if end-of-file input is seen; time to shut down.
228 InteractiveBackend(StringInfo inBuf)
230 int c; /* character read from getc() */
231 bool end = false; /* end-of-input flag */
232 bool backslashSeen = false; /* have we seen a \ ? */
235 * display a prompt and obtain input from the user
240 resetStringInfo(inBuf);
245 * if we are using \n as a delimiter, then read characters until the
248 while ((c = interactive_getc()) != EOF)
254 /* discard backslash from inBuf */
255 inBuf->data[--inBuf->len] = '\0';
256 backslashSeen = false;
261 /* keep the newline character */
262 appendStringInfoChar(inBuf, '\n');
267 backslashSeen = true;
269 backslashSeen = false;
271 appendStringInfoChar(inBuf, (char) c);
280 * otherwise read characters until EOF.
282 while ((c = interactive_getc()) != EOF)
283 appendStringInfoChar(inBuf, (char) c);
285 /* No input before EOF signal means time to quit. */
294 * otherwise we have a user query so process it.
297 /* Add '\0' to make it look the same as message case. */
298 appendStringInfoChar(inBuf, (char) '\0');
301 * if the query echo flag was given, print the query..
304 printf("statement: %s\n", inBuf->data);
311 * interactive_getc -- collect one character from stdin
313 * Even though we are not reading from a "client" process, we still want to
314 * respond to signals, particularly SIGTERM/SIGQUIT. Hence we must use
315 * prepare_for_client_read and client_read_ended.
318 interactive_getc(void)
322 prepare_for_client_read();
329 * SocketBackend() Is called for frontend-backend connections
331 * Returns the message type code, and loads message body data into inBuf.
333 * EOF is returned if the connection is lost.
337 SocketBackend(StringInfo inBuf)
342 * Get message type code from the frontend.
344 qtype = pq_getbyte();
346 if (qtype == EOF) /* frontend disconnected */
348 if (IsTransactionState())
350 (errcode(ERRCODE_CONNECTION_FAILURE),
351 errmsg("unexpected EOF on client connection with an open transaction")));
355 * Can't send DEBUG log messages to client at this point. Since
356 * we're disconnecting right away, we don't need to restore
359 whereToSendOutput = DestNone;
361 (errcode(ERRCODE_CONNECTION_DOES_NOT_EXIST),
362 errmsg("unexpected EOF on client connection")));
368 * Validate message type code before trying to read body; if we have lost
369 * sync, better to say "command unknown" than to run out of memory because
370 * we used garbage as a length word.
372 * This also gives us a place to set the doing_extended_query_message flag
373 * as soon as possible.
377 case 'Q': /* simple query */
378 doing_extended_query_message = false;
379 if (PG_PROTOCOL_MAJOR(FrontendProtocol) < 3)
381 /* old style without length word; convert */
382 if (pq_getstring(inBuf))
384 if (IsTransactionState())
386 (errcode(ERRCODE_CONNECTION_FAILURE),
387 errmsg("unexpected EOF on client connection with an open transaction")));
391 * Can't send DEBUG log messages to client at this
392 * point.Since we're disconnecting right away, we
393 * don't need to restore whereToSendOutput.
395 whereToSendOutput = DestNone;
397 (errcode(ERRCODE_CONNECTION_DOES_NOT_EXIST),
398 errmsg("unexpected EOF on client connection")));
405 case 'F': /* fastpath function call */
406 /* we let fastpath.c cope with old-style input of this */
407 doing_extended_query_message = false;
410 case 'X': /* terminate */
411 doing_extended_query_message = false;
412 ignore_till_sync = false;
416 case 'C': /* close */
417 case 'D': /* describe */
418 case 'E': /* execute */
419 case 'H': /* flush */
420 case 'P': /* parse */
421 doing_extended_query_message = true;
422 /* these are only legal in protocol 3 */
423 if (PG_PROTOCOL_MAJOR(FrontendProtocol) < 3)
425 (errcode(ERRCODE_PROTOCOL_VIOLATION),
426 errmsg("invalid frontend message type %d", qtype)));
430 /* stop any active skip-till-Sync */
431 ignore_till_sync = false;
432 /* mark not-extended, so that a new error doesn't begin skip */
433 doing_extended_query_message = false;
434 /* only legal in protocol 3 */
435 if (PG_PROTOCOL_MAJOR(FrontendProtocol) < 3)
437 (errcode(ERRCODE_PROTOCOL_VIOLATION),
438 errmsg("invalid frontend message type %d", qtype)));
441 case 'd': /* copy data */
442 case 'c': /* copy done */
443 case 'f': /* copy fail */
444 doing_extended_query_message = false;
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)));
455 * Otherwise we got garbage from the frontend. We treat this as
456 * fatal because we have probably lost message boundary sync, and
457 * there's no good way to recover.
460 (errcode(ERRCODE_PROTOCOL_VIOLATION),
461 errmsg("invalid frontend message type %d", qtype)));
466 * In protocol version 3, all frontend messages have a length word next
467 * after the type code; we can read the message contents independently of
470 if (PG_PROTOCOL_MAJOR(FrontendProtocol) >= 3)
472 if (pq_getmessage(inBuf, 0))
473 return EOF; /* suitable message already logged */
480 * ReadCommand reads a command from either the frontend or
481 * standard input, places it in inBuf, and returns the
482 * message type code (first byte of the message).
483 * EOF is returned if end of file.
487 ReadCommand(StringInfo inBuf)
491 if (whereToSendOutput == DestRemote)
492 result = SocketBackend(inBuf);
494 result = InteractiveBackend(inBuf);
499 * prepare_for_client_read -- set up to possibly block on client input
501 * This must be called immediately before any low-level read from the
502 * client connection. It is necessary to do it at a sufficiently low level
503 * that there won't be any other operations except the read kernel call
504 * itself between this call and the subsequent client_read_ended() call.
505 * In particular there mustn't be use of malloc() or other potentially
506 * non-reentrant libc functions. This restriction makes it safe for us
507 * to allow interrupt service routines to execute nontrivial code while
508 * we are waiting for input.
511 prepare_for_client_read(void)
513 if (DoingCommandRead)
515 /* Enable immediate processing of asynchronous signals */
516 EnableNotifyInterrupt();
517 EnableCatchupInterrupt();
519 /* Allow cancel/die interrupts to be processed while waiting */
520 ImmediateInterruptOK = true;
522 /* And don't forget to detect one that already arrived */
523 CHECK_FOR_INTERRUPTS();
528 * client_read_ended -- get out of the client-input state
530 * This is called just after low-level reads. It must preserve errno!
533 client_read_ended(void)
535 if (DoingCommandRead)
537 int save_errno = errno;
539 ImmediateInterruptOK = false;
541 DisableNotifyInterrupt();
542 DisableCatchupInterrupt();
550 * Do raw parsing (only).
552 * A list of parsetrees is returned, since there might be multiple
553 * commands in the given string.
555 * NOTE: for interactive queries, it is important to keep this routine
556 * separate from the analysis & rewrite stages. Analysis and rewriting
557 * cannot be done in an aborted transaction, since they require access to
558 * database tables. So, we rely on the raw parser to determine whether
559 * we've seen a COMMIT or ABORT command; when we are in abort state, other
560 * commands are not processed any further than the raw parse stage.
563 pg_parse_query(const char *query_string)
565 List *raw_parsetree_list;
567 TRACE_POSTGRESQL_QUERY_PARSE_START(query_string);
569 if (log_parser_stats)
572 raw_parsetree_list = raw_parser(query_string);
574 if (log_parser_stats)
575 ShowUsage("PARSER STATISTICS");
577 #ifdef COPY_PARSE_PLAN_TREES
578 /* Optional debugging check: pass raw parsetrees through copyObject() */
580 List *new_list = (List *) copyObject(raw_parsetree_list);
582 /* This checks both copyObject() and the equal() routines... */
583 if (!equal(new_list, raw_parsetree_list))
584 elog(WARNING, "copyObject() failed to produce an equal raw parse tree");
586 raw_parsetree_list = new_list;
590 TRACE_POSTGRESQL_QUERY_PARSE_DONE(query_string);
592 return raw_parsetree_list;
596 * Given a raw parsetree (gram.y output), and optionally information about
597 * types of parameter symbols ($n), perform parse analysis and rule rewriting.
599 * A list of Query nodes is returned, since either the analyzer or the
600 * rewriter might expand one query to several.
602 * NOTE: for reasons mentioned above, this must be separate from raw parsing.
605 pg_analyze_and_rewrite(Node *parsetree, const char *query_string,
606 Oid *paramTypes, int numParams)
609 List *querytree_list;
611 TRACE_POSTGRESQL_QUERY_REWRITE_START(query_string);
614 * (1) Perform parse analysis.
616 if (log_parser_stats)
619 query = parse_analyze(parsetree, query_string, paramTypes, numParams);
621 if (log_parser_stats)
622 ShowUsage("PARSE ANALYSIS STATISTICS");
625 * (2) Rewrite the queries, as necessary
627 querytree_list = pg_rewrite_query(query);
629 TRACE_POSTGRESQL_QUERY_REWRITE_DONE(query_string);
631 return querytree_list;
635 * Do parse analysis and rewriting. This is the same as pg_analyze_and_rewrite
636 * except that external-parameter resolution is determined by parser callback
637 * hooks instead of a fixed list of parameter datatypes.
640 pg_analyze_and_rewrite_params(Node *parsetree,
641 const char *query_string,
642 ParserSetupHook parserSetup,
643 void *parserSetupArg)
647 List *querytree_list;
649 Assert(query_string != NULL); /* required as of 8.4 */
651 TRACE_POSTGRESQL_QUERY_REWRITE_START(query_string);
654 * (1) Perform parse analysis.
656 if (log_parser_stats)
659 pstate = make_parsestate(NULL);
660 pstate->p_sourcetext = query_string;
661 (*parserSetup) (pstate, parserSetupArg);
663 query = transformTopLevelStmt(pstate, parsetree);
665 if (post_parse_analyze_hook)
666 (*post_parse_analyze_hook) (pstate, query);
668 free_parsestate(pstate);
670 if (log_parser_stats)
671 ShowUsage("PARSE ANALYSIS STATISTICS");
674 * (2) Rewrite the queries, as necessary
676 querytree_list = pg_rewrite_query(query);
678 TRACE_POSTGRESQL_QUERY_REWRITE_DONE(query_string);
680 return querytree_list;
684 * Perform rewriting of a query produced by parse analysis.
686 * Note: query must just have come from the parser, because we do not do
687 * AcquireRewriteLocks() on it.
690 pg_rewrite_query(Query *query)
692 List *querytree_list;
694 if (Debug_print_parse)
695 elog_node_display(LOG, "parse tree", query,
698 if (log_parser_stats)
701 if (query->commandType == CMD_UTILITY)
703 /* don't rewrite utilities, just dump 'em into result list */
704 querytree_list = list_make1(query);
708 /* rewrite regular queries */
709 querytree_list = QueryRewrite(query);
712 if (log_parser_stats)
713 ShowUsage("REWRITER STATISTICS");
715 #ifdef COPY_PARSE_PLAN_TREES
716 /* Optional debugging check: pass querytree output through copyObject() */
720 new_list = (List *) copyObject(querytree_list);
721 /* This checks both copyObject() and the equal() routines... */
722 if (!equal(new_list, querytree_list))
723 elog(WARNING, "copyObject() failed to produce equal parse tree");
725 querytree_list = new_list;
729 if (Debug_print_rewritten)
730 elog_node_display(LOG, "rewritten parse tree", querytree_list,
733 return querytree_list;
738 * Generate a plan for a single already-rewritten query.
739 * This is a thin wrapper around planner() and takes the same parameters.
742 pg_plan_query(Query *querytree, int cursorOptions, ParamListInfo boundParams)
746 /* Utility commands have no plans. */
747 if (querytree->commandType == CMD_UTILITY)
750 /* Planner must have a snapshot in case it calls user-defined functions. */
751 Assert(ActiveSnapshotSet());
753 TRACE_POSTGRESQL_QUERY_PLAN_START();
755 if (log_planner_stats)
758 /* call the optimizer */
759 plan = planner(querytree, cursorOptions, boundParams);
761 if (log_planner_stats)
762 ShowUsage("PLANNER STATISTICS");
764 #ifdef COPY_PARSE_PLAN_TREES
765 /* Optional debugging check: pass plan output through copyObject() */
767 PlannedStmt *new_plan = (PlannedStmt *) copyObject(plan);
770 * equal() currently does not have routines to compare Plan nodes, so
771 * don't try to test equality here. Perhaps fix someday?
774 /* This checks both copyObject() and the equal() routines... */
775 if (!equal(new_plan, plan))
776 elog(WARNING, "copyObject() failed to produce an equal plan tree");
784 * Print plan if debugging.
786 if (Debug_print_plan)
787 elog_node_display(LOG, "plan", plan, Debug_pretty_print);
789 TRACE_POSTGRESQL_QUERY_PLAN_DONE();
795 * Generate plans for a list of already-rewritten queries.
797 * Normal optimizable statements generate PlannedStmt entries in the result
798 * list. Utility statements are simply represented by their statement nodes.
801 pg_plan_queries(List *querytrees, int cursorOptions, ParamListInfo boundParams)
803 List *stmt_list = NIL;
804 ListCell *query_list;
806 foreach(query_list, querytrees)
808 Query *query = (Query *) lfirst(query_list);
811 if (query->commandType == CMD_UTILITY)
813 /* Utility commands have no plans. */
814 stmt = query->utilityStmt;
818 stmt = (Node *) pg_plan_query(query, cursorOptions, boundParams);
821 stmt_list = lappend(stmt_list, stmt);
831 * Execute a "simple Query" protocol message.
834 exec_simple_query(const char *query_string)
836 CommandDest dest = whereToSendOutput;
837 MemoryContext oldcontext;
838 List *parsetree_list;
839 ListCell *parsetree_item;
840 bool save_log_statement_stats = log_statement_stats;
841 bool was_logged = false;
847 * Report query to various monitoring facilities.
849 debug_query_string = query_string;
851 pgstat_report_activity(STATE_RUNNING, query_string);
853 TRACE_POSTGRESQL_QUERY_START(query_string);
856 * We use save_log_statement_stats so ShowUsage doesn't report incorrect
857 * results because ResetUsage wasn't called.
859 if (save_log_statement_stats)
863 * Start up a transaction command. All queries generated by the
864 * query_string will be in this same command block, *unless* we find a
865 * BEGIN/COMMIT/ABORT statement; we have to force a new xact command after
866 * one of those, else bad things will happen in xact.c. (Note that this
867 * will normally change current memory context.)
869 start_xact_command();
872 * Zap any pre-existing unnamed statement. (While not strictly necessary,
873 * it seems best to define simple-Query mode as if it used the unnamed
874 * statement and portal; this ensures we recover any storage used by prior
875 * unnamed operations.)
880 * Switch to appropriate context for constructing parsetrees.
882 oldcontext = MemoryContextSwitchTo(MessageContext);
885 * Do basic parsing of the query or queries (this should be safe even if
886 * we are in aborted transaction state!)
888 parsetree_list = pg_parse_query(query_string);
890 /* Log immediately if dictated by log_statement */
891 if (check_log_statement(parsetree_list))
894 (errmsg("statement: %s", query_string),
896 errdetail_execute(parsetree_list)));
901 * Switch back to transaction context to enter the loop.
903 MemoryContextSwitchTo(oldcontext);
906 * We'll tell PortalRun it's a top-level command iff there's exactly one
907 * raw parsetree. If more than one, it's effectively a transaction block
908 * and we want PreventTransactionChain to reject unsafe commands. (Note:
909 * we're assuming that query rewrite cannot add commands that are
910 * significant to PreventTransactionChain.)
912 isTopLevel = (list_length(parsetree_list) == 1);
915 * Run through the raw parsetree(s) and process each one.
917 foreach(parsetree_item, parsetree_list)
919 Node *parsetree = (Node *) lfirst(parsetree_item);
920 bool snapshot_set = false;
921 const char *commandTag;
922 char completionTag[COMPLETION_TAG_BUFSIZE];
923 List *querytree_list,
926 DestReceiver *receiver;
930 * Get the command name for use in status display (it also becomes the
931 * default completion tag, down inside PortalRun). Set ps_status and
932 * do any special start-of-SQL-command processing needed by the
935 commandTag = CreateCommandTag(parsetree);
937 set_ps_display(commandTag, false);
939 BeginCommand(commandTag, dest);
942 * If we are in an aborted transaction, reject all commands except
943 * COMMIT/ABORT. It is important that this test occur before we try
944 * to do parse analysis, rewrite, or planning, since all those phases
945 * try to do database accesses, which may fail in abort state. (It
946 * might be safe to allow some additional utility commands in this
947 * state, but not many...)
949 if (IsAbortedTransactionBlockState() &&
950 !IsTransactionExitStmt(parsetree))
952 (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
953 errmsg("current transaction is aborted, "
954 "commands ignored until end of transaction block"),
957 /* Make sure we are in a transaction command */
958 start_xact_command();
960 /* If we got a cancel signal in parsing or prior command, quit */
961 CHECK_FOR_INTERRUPTS();
964 * Set up a snapshot if parse analysis/planning will need one.
966 if (analyze_requires_snapshot(parsetree))
968 PushActiveSnapshot(GetTransactionSnapshot());
973 * OK to analyze, rewrite, and plan this query.
975 * Switch to appropriate context for constructing querytrees (again,
976 * these must outlive the execution context).
978 oldcontext = MemoryContextSwitchTo(MessageContext);
980 querytree_list = pg_analyze_and_rewrite(parsetree, query_string,
983 plantree_list = pg_plan_queries(querytree_list, 0, NULL);
985 /* Done with the snapshot used for parsing/planning */
989 /* If we got a cancel signal in analysis or planning, quit */
990 CHECK_FOR_INTERRUPTS();
993 * Create unnamed portal to run the query or queries in. If there
994 * already is one, silently drop it.
996 portal = CreatePortal("", true, true);
997 /* Don't display the portal in pg_cursors */
998 portal->visible = false;
1001 * We don't have to copy anything into the portal, because everything
1002 * we are passing here is in MessageContext, which will outlive the
1005 PortalDefineQuery(portal,
1013 * Start the portal. No parameters here.
1015 PortalStart(portal, NULL, 0, InvalidSnapshot);
1018 * Select the appropriate output format: text unless we are doing a
1019 * FETCH from a binary cursor. (Pretty grotty to have to do this here
1020 * --- but it avoids grottiness in other places. Ah, the joys of
1021 * backward compatibility...)
1023 format = 0; /* TEXT is default */
1024 if (IsA(parsetree, FetchStmt))
1026 FetchStmt *stmt = (FetchStmt *) parsetree;
1030 Portal fportal = GetPortalByName(stmt->portalname);
1032 if (PortalIsValid(fportal) &&
1033 (fportal->cursorOptions & CURSOR_OPT_BINARY))
1034 format = 1; /* BINARY */
1037 PortalSetResultFormat(portal, 1, &format);
1040 * Now we can create the destination receiver object.
1042 receiver = CreateDestReceiver(dest);
1043 if (dest == DestRemote)
1044 SetRemoteDestReceiverParams(receiver, portal);
1047 * Switch back to transaction context for execution.
1049 MemoryContextSwitchTo(oldcontext);
1052 * Run the portal to completion, and then drop it (and the receiver).
1054 (void) PortalRun(portal,
1061 (*receiver->rDestroy) (receiver);
1063 PortalDrop(portal, false);
1065 if (IsA(parsetree, TransactionStmt))
1068 * If this was a transaction control statement, commit it. We will
1069 * start a new xact command for the next command (if any).
1071 finish_xact_command();
1073 else if (lnext(parsetree_item) == NULL)
1076 * If this is the last parsetree of the query string, close down
1077 * transaction statement before reporting command-complete. This
1078 * is so that any end-of-transaction errors are reported before
1079 * the command-complete message is issued, to avoid confusing
1080 * clients who will expect either a command-complete message or an
1081 * error, not one and then the other. But for compatibility with
1082 * historical Postgres behavior, we do not force a transaction
1083 * boundary between queries appearing in a single query string.
1085 finish_xact_command();
1090 * We need a CommandCounterIncrement after every query, except
1091 * those that start or end a transaction block.
1093 CommandCounterIncrement();
1097 * Tell client that we're done with this query. Note we emit exactly
1098 * one EndCommand report for each raw parsetree, thus one for each SQL
1099 * command the client sent, regardless of rewriting. (But a command
1100 * aborted by error will not send an EndCommand report at all.)
1102 EndCommand(completionTag, dest);
1103 } /* end loop over parsetrees */
1106 * Close down transaction statement, if one is open.
1108 finish_xact_command();
1111 * If there were no parsetrees, return EmptyQueryResponse message.
1113 if (!parsetree_list)
1117 * Emit duration logging if appropriate.
1119 switch (check_log_duration(msec_str, was_logged))
1123 (errmsg("duration: %s ms", msec_str),
1124 errhidestmt(true)));
1128 (errmsg("duration: %s ms statement: %s",
1129 msec_str, query_string),
1131 errdetail_execute(parsetree_list)));
1135 if (save_log_statement_stats)
1136 ShowUsage("QUERY STATISTICS");
1138 TRACE_POSTGRESQL_QUERY_DONE(query_string);
1140 debug_query_string = NULL;
1144 * exec_parse_message
1146 * Execute a "Parse" protocol message.
1149 exec_parse_message(const char *query_string, /* string to execute */
1150 const char *stmt_name, /* name for prepared stmt */
1151 Oid *paramTypes, /* parameter types */
1152 int numParams) /* number of parameters */
1154 MemoryContext unnamed_stmt_context = NULL;
1155 MemoryContext oldcontext;
1156 List *parsetree_list;
1157 Node *raw_parse_tree;
1158 const char *commandTag;
1159 List *querytree_list;
1160 CachedPlanSource *psrc;
1162 bool save_log_statement_stats = log_statement_stats;
1166 * Report query to various monitoring facilities.
1168 debug_query_string = query_string;
1170 pgstat_report_activity(STATE_RUNNING, query_string);
1172 set_ps_display("PARSE", false);
1174 if (save_log_statement_stats)
1178 (errmsg("parse %s: %s",
1179 *stmt_name ? stmt_name : "<unnamed>",
1183 * Start up a transaction command so we can run parse analysis etc. (Note
1184 * that this will normally change current memory context.) Nothing happens
1185 * if we are already in one.
1187 start_xact_command();
1190 * Switch to appropriate context for constructing parsetrees.
1192 * We have two strategies depending on whether the prepared statement is
1193 * named or not. For a named prepared statement, we do parsing in
1194 * MessageContext and copy the finished trees into the prepared
1195 * statement's plancache entry; then the reset of MessageContext releases
1196 * temporary space used by parsing and rewriting. For an unnamed prepared
1197 * statement, we assume the statement isn't going to hang around long, so
1198 * getting rid of temp space quickly is probably not worth the costs of
1199 * copying parse trees. So in this case, we create the plancache entry's
1200 * query_context here, and do all the parsing work therein.
1202 is_named = (stmt_name[0] != '\0');
1205 /* Named prepared statement --- parse in MessageContext */
1206 oldcontext = MemoryContextSwitchTo(MessageContext);
1210 /* Unnamed prepared statement --- release any prior unnamed stmt */
1211 drop_unnamed_stmt();
1212 /* Create context for parsing */
1213 unnamed_stmt_context =
1214 AllocSetContextCreate(MessageContext,
1215 "unnamed prepared statement",
1216 ALLOCSET_DEFAULT_MINSIZE,
1217 ALLOCSET_DEFAULT_INITSIZE,
1218 ALLOCSET_DEFAULT_MAXSIZE);
1219 oldcontext = MemoryContextSwitchTo(unnamed_stmt_context);
1223 * Do basic parsing of the query or queries (this should be safe even if
1224 * we are in aborted transaction state!)
1226 parsetree_list = pg_parse_query(query_string);
1229 * We only allow a single user statement in a prepared statement. This is
1230 * mainly to keep the protocol simple --- otherwise we'd need to worry
1231 * about multiple result tupdescs and things like that.
1233 if (list_length(parsetree_list) > 1)
1235 (errcode(ERRCODE_SYNTAX_ERROR),
1236 errmsg("cannot insert multiple commands into a prepared statement")));
1238 if (parsetree_list != NIL)
1241 bool snapshot_set = false;
1244 raw_parse_tree = (Node *) linitial(parsetree_list);
1247 * Get the command name for possible use in status display.
1249 commandTag = CreateCommandTag(raw_parse_tree);
1252 * If we are in an aborted transaction, reject all commands except
1253 * COMMIT/ROLLBACK. It is important that this test occur before we
1254 * try to do parse analysis, rewrite, or planning, since all those
1255 * phases try to do database accesses, which may fail in abort state.
1256 * (It might be safe to allow some additional utility commands in this
1257 * state, but not many...)
1259 if (IsAbortedTransactionBlockState() &&
1260 !IsTransactionExitStmt(raw_parse_tree))
1262 (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
1263 errmsg("current transaction is aborted, "
1264 "commands ignored until end of transaction block"),
1265 errdetail_abort()));
1268 * Create the CachedPlanSource before we do parse analysis, since it
1269 * needs to see the unmodified raw parse tree.
1271 psrc = CreateCachedPlan(raw_parse_tree, query_string, commandTag);
1274 * Set up a snapshot if parse analysis will need one.
1276 if (analyze_requires_snapshot(raw_parse_tree))
1278 PushActiveSnapshot(GetTransactionSnapshot());
1279 snapshot_set = true;
1283 * Analyze and rewrite the query. Note that the originally specified
1284 * parameter set is not required to be complete, so we have to use
1285 * parse_analyze_varparams().
1287 if (log_parser_stats)
1290 query = parse_analyze_varparams(raw_parse_tree,
1296 * Check all parameter types got determined.
1298 for (i = 0; i < numParams; i++)
1300 Oid ptype = paramTypes[i];
1302 if (ptype == InvalidOid || ptype == UNKNOWNOID)
1304 (errcode(ERRCODE_INDETERMINATE_DATATYPE),
1305 errmsg("could not determine data type of parameter $%d",
1309 if (log_parser_stats)
1310 ShowUsage("PARSE ANALYSIS STATISTICS");
1312 querytree_list = pg_rewrite_query(query);
1314 /* Done with the snapshot used for parsing */
1316 PopActiveSnapshot();
1320 /* Empty input string. This is legal. */
1321 raw_parse_tree = NULL;
1323 psrc = CreateCachedPlan(raw_parse_tree, query_string, commandTag);
1324 querytree_list = NIL;
1328 * CachedPlanSource must be a direct child of MessageContext before we
1329 * reparent unnamed_stmt_context under it, else we have a disconnected
1330 * circular subgraph. Klugy, but less so than flipping contexts even more
1333 if (unnamed_stmt_context)
1334 MemoryContextSetParent(psrc->context, MessageContext);
1336 /* Finish filling in the CachedPlanSource */
1337 CompleteCachedPlan(psrc,
1339 unnamed_stmt_context,
1344 0, /* default cursor options */
1345 true); /* fixed result */
1347 /* If we got a cancel signal during analysis, quit */
1348 CHECK_FOR_INTERRUPTS();
1353 * Store the query as a prepared statement.
1355 StorePreparedStatement(stmt_name, psrc, false);
1360 * We just save the CachedPlanSource into unnamed_stmt_psrc.
1362 SaveCachedPlan(psrc);
1363 unnamed_stmt_psrc = psrc;
1366 MemoryContextSwitchTo(oldcontext);
1369 * We do NOT close the open transaction command here; that only happens
1370 * when the client sends Sync. Instead, do CommandCounterIncrement just
1371 * in case something happened during parse/plan.
1373 CommandCounterIncrement();
1376 * Send ParseComplete.
1378 if (whereToSendOutput == DestRemote)
1379 pq_putemptymessage('1');
1382 * Emit duration logging if appropriate.
1384 switch (check_log_duration(msec_str, false))
1388 (errmsg("duration: %s ms", msec_str),
1389 errhidestmt(true)));
1393 (errmsg("duration: %s ms parse %s: %s",
1395 *stmt_name ? stmt_name : "<unnamed>",
1397 errhidestmt(true)));
1401 if (save_log_statement_stats)
1402 ShowUsage("PARSE MESSAGE STATISTICS");
1404 debug_query_string = NULL;
1410 * Process a "Bind" message to create a portal from a prepared statement
1413 exec_bind_message(StringInfo input_message)
1415 const char *portal_name;
1416 const char *stmt_name;
1418 int16 *pformats = NULL;
1421 int16 *rformats = NULL;
1422 CachedPlanSource *psrc;
1426 char *saved_stmt_name;
1427 ParamListInfo params;
1428 MemoryContext oldContext;
1429 bool save_log_statement_stats = log_statement_stats;
1430 bool snapshot_set = false;
1433 /* Get the fixed part of the message */
1434 portal_name = pq_getmsgstring(input_message);
1435 stmt_name = pq_getmsgstring(input_message);
1438 (errmsg("bind %s to %s",
1439 *portal_name ? portal_name : "<unnamed>",
1440 *stmt_name ? stmt_name : "<unnamed>")));
1442 /* Find prepared statement */
1443 if (stmt_name[0] != '\0')
1445 PreparedStatement *pstmt;
1447 pstmt = FetchPreparedStatement(stmt_name, true);
1448 psrc = pstmt->plansource;
1452 /* special-case the unnamed statement */
1453 psrc = unnamed_stmt_psrc;
1456 (errcode(ERRCODE_UNDEFINED_PSTATEMENT),
1457 errmsg("unnamed prepared statement does not exist")));
1461 * Report query to various monitoring facilities.
1463 debug_query_string = psrc->query_string;
1465 pgstat_report_activity(STATE_RUNNING, psrc->query_string);
1467 set_ps_display("BIND", false);
1469 if (save_log_statement_stats)
1473 * Start up a transaction command so we can call functions etc. (Note that
1474 * this will normally change current memory context.) Nothing happens if
1475 * we are already in one.
1477 start_xact_command();
1479 /* Switch back to message context */
1480 MemoryContextSwitchTo(MessageContext);
1482 /* Get the parameter format codes */
1483 numPFormats = pq_getmsgint(input_message, 2);
1484 if (numPFormats > 0)
1488 pformats = (int16 *) palloc(numPFormats * sizeof(int16));
1489 for (i = 0; i < numPFormats; i++)
1490 pformats[i] = pq_getmsgint(input_message, 2);
1493 /* Get the parameter value count */
1494 numParams = pq_getmsgint(input_message, 2);
1496 if (numPFormats > 1 && numPFormats != numParams)
1498 (errcode(ERRCODE_PROTOCOL_VIOLATION),
1499 errmsg("bind message has %d parameter formats but %d parameters",
1500 numPFormats, numParams)));
1502 if (numParams != psrc->num_params)
1504 (errcode(ERRCODE_PROTOCOL_VIOLATION),
1505 errmsg("bind message supplies %d parameters, but prepared statement \"%s\" requires %d",
1506 numParams, stmt_name, psrc->num_params)));
1509 * If we are in aborted transaction state, the only portals we can
1510 * actually run are those containing COMMIT or ROLLBACK commands. We
1511 * disallow binding anything else to avoid problems with infrastructure
1512 * that expects to run inside a valid transaction. We also disallow
1513 * binding any parameters, since we can't risk calling user-defined I/O
1516 if (IsAbortedTransactionBlockState() &&
1517 (!IsTransactionExitStmt(psrc->raw_parse_tree) ||
1520 (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
1521 errmsg("current transaction is aborted, "
1522 "commands ignored until end of transaction block"),
1523 errdetail_abort()));
1526 * Create the portal. Allow silent replacement of an existing portal only
1527 * if the unnamed portal is specified.
1529 if (portal_name[0] == '\0')
1530 portal = CreatePortal(portal_name, true, true);
1532 portal = CreatePortal(portal_name, false, false);
1535 * Prepare to copy stuff into the portal's memory context. We do all this
1536 * copying first, because it could possibly fail (out-of-memory) and we
1537 * don't want a failure to occur between GetCachedPlan and
1538 * PortalDefineQuery; that would result in leaking our plancache refcount.
1540 oldContext = MemoryContextSwitchTo(PortalGetHeapMemory(portal));
1542 /* Copy the plan's query string into the portal */
1543 query_string = pstrdup(psrc->query_string);
1545 /* Likewise make a copy of the statement name, unless it's unnamed */
1547 saved_stmt_name = pstrdup(stmt_name);
1549 saved_stmt_name = NULL;
1552 * Set a snapshot if we have parameters to fetch (since the input
1553 * functions might need it) or the query isn't a utility command (and
1554 * hence could require redoing parse analysis and planning). We keep the
1555 * snapshot active till we're done, so that plancache.c doesn't have to
1558 if (numParams > 0 || analyze_requires_snapshot(psrc->raw_parse_tree))
1560 PushActiveSnapshot(GetTransactionSnapshot());
1561 snapshot_set = true;
1565 * Fetch parameters, if any, and store in the portal's memory context.
1571 /* sizeof(ParamListInfoData) includes the first array element */
1572 params = (ParamListInfo) palloc(sizeof(ParamListInfoData) +
1573 (numParams - 1) * sizeof(ParamExternData));
1574 /* we have static list of params, so no hooks needed */
1575 params->paramFetch = NULL;
1576 params->paramFetchArg = NULL;
1577 params->parserSetup = NULL;
1578 params->parserSetupArg = NULL;
1579 params->numParams = numParams;
1581 for (paramno = 0; paramno < numParams; paramno++)
1583 Oid ptype = psrc->param_types[paramno];
1587 StringInfoData pbuf;
1591 plength = pq_getmsgint(input_message, 4);
1592 isNull = (plength == -1);
1596 const char *pvalue = pq_getmsgbytes(input_message, plength);
1599 * Rather than copying data around, we just set up a phony
1600 * StringInfo pointing to the correct portion of the message
1601 * buffer. We assume we can scribble on the message buffer so
1602 * as to maintain the convention that StringInfos have a
1603 * trailing null. This is grotty but is a big win when
1604 * dealing with very large parameter strings.
1606 pbuf.data = (char *) pvalue;
1607 pbuf.maxlen = plength + 1;
1611 csave = pbuf.data[plength];
1612 pbuf.data[plength] = '\0';
1616 pbuf.data = NULL; /* keep compiler quiet */
1620 if (numPFormats > 1)
1621 pformat = pformats[paramno];
1622 else if (numPFormats > 0)
1623 pformat = pformats[0];
1625 pformat = 0; /* default = text */
1627 if (pformat == 0) /* text mode */
1633 getTypeInputInfo(ptype, &typinput, &typioparam);
1636 * We have to do encoding conversion before calling the
1642 pstring = pg_client_to_server(pbuf.data, plength);
1644 pval = OidInputFunctionCall(typinput, pstring, typioparam, -1);
1646 /* Free result of encoding conversion, if any */
1647 if (pstring && pstring != pbuf.data)
1650 else if (pformat == 1) /* binary mode */
1657 * Call the parameter type's binary input converter
1659 getTypeBinaryInputInfo(ptype, &typreceive, &typioparam);
1666 pval = OidReceiveFunctionCall(typreceive, bufptr, typioparam, -1);
1668 /* Trouble if it didn't eat the whole buffer */
1669 if (!isNull && pbuf.cursor != pbuf.len)
1671 (errcode(ERRCODE_INVALID_BINARY_REPRESENTATION),
1672 errmsg("incorrect binary data format in bind parameter %d",
1678 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1679 errmsg("unsupported format code: %d",
1681 pval = 0; /* keep compiler quiet */
1684 /* Restore message buffer contents */
1686 pbuf.data[plength] = csave;
1688 params->params[paramno].value = pval;
1689 params->params[paramno].isnull = isNull;
1692 * We mark the params as CONST. This ensures that any custom plan
1693 * makes full use of the parameter values.
1695 params->params[paramno].pflags = PARAM_FLAG_CONST;
1696 params->params[paramno].ptype = ptype;
1702 /* Done storing stuff in portal's context */
1703 MemoryContextSwitchTo(oldContext);
1705 /* Get the result format codes */
1706 numRFormats = pq_getmsgint(input_message, 2);
1707 if (numRFormats > 0)
1711 rformats = (int16 *) palloc(numRFormats * sizeof(int16));
1712 for (i = 0; i < numRFormats; i++)
1713 rformats[i] = pq_getmsgint(input_message, 2);
1716 pq_getmsgend(input_message);
1719 * Obtain a plan from the CachedPlanSource. Any cruft from (re)planning
1720 * will be generated in MessageContext. The plan refcount will be
1721 * assigned to the Portal, so it will be released at portal destruction.
1723 cplan = GetCachedPlan(psrc, params, false);
1726 * Now we can define the portal.
1728 * DO NOT put any code that could possibly throw an error between the
1729 * above GetCachedPlan call and here.
1731 PortalDefineQuery(portal,
1738 /* Done with the snapshot used for parameter I/O and parsing/planning */
1740 PopActiveSnapshot();
1743 * And we're ready to start portal execution.
1745 PortalStart(portal, params, 0, InvalidSnapshot);
1748 * Apply the result format requests to the portal.
1750 PortalSetResultFormat(portal, numRFormats, rformats);
1753 * Send BindComplete.
1755 if (whereToSendOutput == DestRemote)
1756 pq_putemptymessage('2');
1759 * Emit duration logging if appropriate.
1761 switch (check_log_duration(msec_str, false))
1765 (errmsg("duration: %s ms", msec_str),
1766 errhidestmt(true)));
1770 (errmsg("duration: %s ms bind %s%s%s: %s",
1772 *stmt_name ? stmt_name : "<unnamed>",
1773 *portal_name ? "/" : "",
1774 *portal_name ? portal_name : "",
1775 psrc->query_string),
1777 errdetail_params(params)));
1781 if (save_log_statement_stats)
1782 ShowUsage("BIND MESSAGE STATISTICS");
1784 debug_query_string = NULL;
1788 * exec_execute_message
1790 * Process an "Execute" message for a portal
1793 exec_execute_message(const char *portal_name, long max_rows)
1796 DestReceiver *receiver;
1799 char completionTag[COMPLETION_TAG_BUFSIZE];
1800 const char *sourceText;
1801 const char *prepStmtName;
1802 ParamListInfo portalParams;
1803 bool save_log_statement_stats = log_statement_stats;
1804 bool is_xact_command;
1805 bool execute_is_fetch;
1806 bool was_logged = false;
1809 /* Adjust destination to tell printtup.c what to do */
1810 dest = whereToSendOutput;
1811 if (dest == DestRemote)
1812 dest = DestRemoteExecute;
1814 portal = GetPortalByName(portal_name);
1815 if (!PortalIsValid(portal))
1817 (errcode(ERRCODE_UNDEFINED_CURSOR),
1818 errmsg("portal \"%s\" does not exist", portal_name)));
1821 * If the original query was a null string, just return
1822 * EmptyQueryResponse.
1824 if (portal->commandTag == NULL)
1826 Assert(portal->stmts == NIL);
1831 /* Does the portal contain a transaction command? */
1832 is_xact_command = IsTransactionStmtList(portal->stmts);
1835 * We must copy the sourceText and prepStmtName into MessageContext in
1836 * case the portal is destroyed during finish_xact_command. Can avoid the
1837 * copy if it's not an xact command, though.
1839 if (is_xact_command)
1841 sourceText = pstrdup(portal->sourceText);
1842 if (portal->prepStmtName)
1843 prepStmtName = pstrdup(portal->prepStmtName);
1845 prepStmtName = "<unnamed>";
1848 * An xact command shouldn't have any parameters, which is a good
1849 * thing because they wouldn't be around after finish_xact_command.
1851 portalParams = NULL;
1855 sourceText = portal->sourceText;
1856 if (portal->prepStmtName)
1857 prepStmtName = portal->prepStmtName;
1859 prepStmtName = "<unnamed>";
1860 portalParams = portal->portalParams;
1864 * Report query to various monitoring facilities.
1866 debug_query_string = sourceText;
1868 pgstat_report_activity(STATE_RUNNING, sourceText);
1870 set_ps_display(portal->commandTag, false);
1872 if (save_log_statement_stats)
1875 BeginCommand(portal->commandTag, dest);
1878 * Create dest receiver in MessageContext (we don't want it in transaction
1879 * context, because that may get deleted if portal contains VACUUM).
1881 receiver = CreateDestReceiver(dest);
1882 if (dest == DestRemoteExecute)
1883 SetRemoteDestReceiverParams(receiver, portal);
1886 * Ensure we are in a transaction command (this should normally be the
1887 * case already due to prior BIND).
1889 start_xact_command();
1892 * If we re-issue an Execute protocol request against an existing portal,
1893 * then we are only fetching more rows rather than completely re-executing
1894 * the query from the start. atStart is never reset for a v3 portal, so we
1895 * are safe to use this check.
1897 execute_is_fetch = !portal->atStart;
1899 /* Log immediately if dictated by log_statement */
1900 if (check_log_statement(portal->stmts))
1903 (errmsg("%s %s%s%s: %s",
1905 _("execute fetch from") :
1908 *portal_name ? "/" : "",
1909 *portal_name ? portal_name : "",
1912 errdetail_params(portalParams)));
1917 * If we are in aborted transaction state, the only portals we can
1918 * actually run are those containing COMMIT or ROLLBACK commands.
1920 if (IsAbortedTransactionBlockState() &&
1921 !IsTransactionExitStmtList(portal->stmts))
1923 (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
1924 errmsg("current transaction is aborted, "
1925 "commands ignored until end of transaction block"),
1926 errdetail_abort()));
1928 /* Check for cancel signal before we start execution */
1929 CHECK_FOR_INTERRUPTS();
1932 * Okay to run the portal.
1935 max_rows = FETCH_ALL;
1937 completed = PortalRun(portal,
1939 true, /* always top level */
1944 (*receiver->rDestroy) (receiver);
1948 if (is_xact_command)
1951 * If this was a transaction control statement, commit it. We
1952 * will start a new xact command for the next command (if any).
1954 finish_xact_command();
1959 * We need a CommandCounterIncrement after every query, except
1960 * those that start or end a transaction block.
1962 CommandCounterIncrement();
1965 /* Send appropriate CommandComplete to client */
1966 EndCommand(completionTag, dest);
1970 /* Portal run not complete, so send PortalSuspended */
1971 if (whereToSendOutput == DestRemote)
1972 pq_putemptymessage('s');
1976 * Emit duration logging if appropriate.
1978 switch (check_log_duration(msec_str, was_logged))
1982 (errmsg("duration: %s ms", msec_str),
1983 errhidestmt(true)));
1987 (errmsg("duration: %s ms %s %s%s%s: %s",
1990 _("execute fetch from") :
1993 *portal_name ? "/" : "",
1994 *portal_name ? portal_name : "",
1997 errdetail_params(portalParams)));
2001 if (save_log_statement_stats)
2002 ShowUsage("EXECUTE MESSAGE STATISTICS");
2004 debug_query_string = NULL;
2008 * check_log_statement
2009 * Determine whether command should be logged because of log_statement
2011 * parsetree_list can be either raw grammar output or a list of planned
2015 check_log_statement(List *stmt_list)
2017 ListCell *stmt_item;
2019 if (log_statement == LOGSTMT_NONE)
2021 if (log_statement == LOGSTMT_ALL)
2024 /* Else we have to inspect the statement(s) to see whether to log */
2025 foreach(stmt_item, stmt_list)
2027 Node *stmt = (Node *) lfirst(stmt_item);
2029 if (GetCommandLogLevel(stmt) <= log_statement)
2037 * check_log_duration
2038 * Determine whether current command's duration should be logged
2041 * 0 if no logging is needed
2042 * 1 if just the duration should be logged
2043 * 2 if duration and query details should be logged
2045 * If logging is needed, the duration in msec is formatted into msec_str[],
2046 * which must be a 32-byte buffer.
2048 * was_logged should be TRUE if caller already logged query details (this
2049 * essentially prevents 2 from being returned).
2052 check_log_duration(char *msec_str, bool was_logged)
2054 if (log_duration || log_min_duration_statement >= 0)
2061 TimestampDifference(GetCurrentStatementStartTimestamp(),
2062 GetCurrentTimestamp(),
2064 msecs = usecs / 1000;
2067 * This odd-looking test for log_min_duration_statement being exceeded
2068 * is designed to avoid integer overflow with very long durations:
2069 * don't compute secs * 1000 until we've verified it will fit in int.
2071 exceeded = (log_min_duration_statement == 0 ||
2072 (log_min_duration_statement > 0 &&
2073 (secs > log_min_duration_statement / 1000 ||
2074 secs * 1000 + msecs >= log_min_duration_statement)));
2076 if (exceeded || log_duration)
2078 snprintf(msec_str, 32, "%ld.%03d",
2079 secs * 1000 + msecs, usecs % 1000);
2080 if (exceeded && !was_logged)
2093 * Add an errdetail() line showing the query referenced by an EXECUTE, if any.
2094 * The argument is the raw parsetree list.
2097 errdetail_execute(List *raw_parsetree_list)
2099 ListCell *parsetree_item;
2101 foreach(parsetree_item, raw_parsetree_list)
2103 Node *parsetree = (Node *) lfirst(parsetree_item);
2105 if (IsA(parsetree, ExecuteStmt))
2107 ExecuteStmt *stmt = (ExecuteStmt *) parsetree;
2108 PreparedStatement *pstmt;
2110 pstmt = FetchPreparedStatement(stmt->name, false);
2113 errdetail("prepare: %s", pstmt->plansource->query_string);
2125 * Add an errdetail() line showing bind-parameter data, if available.
2128 errdetail_params(ParamListInfo params)
2130 /* We mustn't call user-defined I/O functions when in an aborted xact */
2131 if (params && params->numParams > 0 && !IsAbortedTransactionBlockState())
2133 StringInfoData param_str;
2134 MemoryContext oldcontext;
2137 /* Make sure any trash is generated in MessageContext */
2138 oldcontext = MemoryContextSwitchTo(MessageContext);
2140 initStringInfo(¶m_str);
2142 for (paramno = 0; paramno < params->numParams; paramno++)
2144 ParamExternData *prm = ¶ms->params[paramno];
2150 appendStringInfo(¶m_str, "%s$%d = ",
2151 paramno > 0 ? ", " : "",
2154 if (prm->isnull || !OidIsValid(prm->ptype))
2156 appendStringInfoString(¶m_str, "NULL");
2160 getTypeOutputInfo(prm->ptype, &typoutput, &typisvarlena);
2162 pstring = OidOutputFunctionCall(typoutput, prm->value);
2164 appendStringInfoCharMacro(¶m_str, '\'');
2165 for (p = pstring; *p; p++)
2167 if (*p == '\'') /* double single quotes */
2168 appendStringInfoCharMacro(¶m_str, *p);
2169 appendStringInfoCharMacro(¶m_str, *p);
2171 appendStringInfoCharMacro(¶m_str, '\'');
2176 errdetail("parameters: %s", param_str.data);
2178 pfree(param_str.data);
2180 MemoryContextSwitchTo(oldcontext);
2189 * Add an errdetail() line showing abort reason, if any.
2192 errdetail_abort(void)
2194 if (MyProc->recoveryConflictPending)
2195 errdetail("abort reason: recovery conflict");
2201 * errdetail_recovery_conflict
2203 * Add an errdetail() line showing conflict source.
2206 errdetail_recovery_conflict(void)
2208 switch (RecoveryConflictReason)
2210 case PROCSIG_RECOVERY_CONFLICT_BUFFERPIN:
2211 errdetail("User was holding shared buffer pin for too long.");
2213 case PROCSIG_RECOVERY_CONFLICT_LOCK:
2214 errdetail("User was holding a relation lock for too long.");
2216 case PROCSIG_RECOVERY_CONFLICT_TABLESPACE:
2217 errdetail("User was or might have been using tablespace that must be dropped.");
2219 case PROCSIG_RECOVERY_CONFLICT_SNAPSHOT:
2220 errdetail("User query might have needed to see row versions that must be removed.");
2222 case PROCSIG_RECOVERY_CONFLICT_STARTUP_DEADLOCK:
2223 errdetail("User transaction caused buffer deadlock with recovery.");
2225 case PROCSIG_RECOVERY_CONFLICT_DATABASE:
2226 errdetail("User was connected to a database that must be dropped.");
2237 * exec_describe_statement_message
2239 * Process a "Describe" message for a prepared statement
2242 exec_describe_statement_message(const char *stmt_name)
2244 CachedPlanSource *psrc;
2249 * Start up a transaction command. (Note that this will normally change
2250 * current memory context.) Nothing happens if we are already in one.
2252 start_xact_command();
2254 /* Switch back to message context */
2255 MemoryContextSwitchTo(MessageContext);
2257 /* Find prepared statement */
2258 if (stmt_name[0] != '\0')
2260 PreparedStatement *pstmt;
2262 pstmt = FetchPreparedStatement(stmt_name, true);
2263 psrc = pstmt->plansource;
2267 /* special-case the unnamed statement */
2268 psrc = unnamed_stmt_psrc;
2271 (errcode(ERRCODE_UNDEFINED_PSTATEMENT),
2272 errmsg("unnamed prepared statement does not exist")));
2275 /* Prepared statements shouldn't have changeable result descs */
2276 Assert(psrc->fixed_result);
2279 * If we are in aborted transaction state, we can't run
2280 * SendRowDescriptionMessage(), because that needs catalog accesses.
2281 * Hence, refuse to Describe statements that return data. (We shouldn't
2282 * just refuse all Describes, since that might break the ability of some
2283 * clients to issue COMMIT or ROLLBACK commands, if they use code that
2284 * blindly Describes whatever it does.) We can Describe parameters
2285 * without doing anything dangerous, so we don't restrict that.
2287 if (IsAbortedTransactionBlockState() &&
2290 (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
2291 errmsg("current transaction is aborted, "
2292 "commands ignored until end of transaction block"),
2293 errdetail_abort()));
2295 if (whereToSendOutput != DestRemote)
2296 return; /* can't actually do anything... */
2299 * First describe the parameters...
2301 pq_beginmessage(&buf, 't'); /* parameter description message type */
2302 pq_sendint(&buf, psrc->num_params, 2);
2304 for (i = 0; i < psrc->num_params; i++)
2306 Oid ptype = psrc->param_types[i];
2308 pq_sendint(&buf, (int) ptype, 4);
2310 pq_endmessage(&buf);
2313 * Next send RowDescription or NoData to describe the result...
2315 if (psrc->resultDesc)
2319 /* Get the plan's primary targetlist */
2320 tlist = CachedPlanGetTargetList(psrc);
2322 SendRowDescriptionMessage(psrc->resultDesc, tlist, NULL);
2325 pq_putemptymessage('n'); /* NoData */
2330 * exec_describe_portal_message
2332 * Process a "Describe" message for a portal
2335 exec_describe_portal_message(const char *portal_name)
2340 * Start up a transaction command. (Note that this will normally change
2341 * current memory context.) Nothing happens if we are already in one.
2343 start_xact_command();
2345 /* Switch back to message context */
2346 MemoryContextSwitchTo(MessageContext);
2348 portal = GetPortalByName(portal_name);
2349 if (!PortalIsValid(portal))
2351 (errcode(ERRCODE_UNDEFINED_CURSOR),
2352 errmsg("portal \"%s\" does not exist", portal_name)));
2355 * If we are in aborted transaction state, we can't run
2356 * SendRowDescriptionMessage(), because that needs catalog accesses.
2357 * Hence, refuse to Describe portals that return data. (We shouldn't just
2358 * refuse all Describes, since that might break the ability of some
2359 * clients to issue COMMIT or ROLLBACK commands, if they use code that
2360 * blindly Describes whatever it does.)
2362 if (IsAbortedTransactionBlockState() &&
2365 (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
2366 errmsg("current transaction is aborted, "
2367 "commands ignored until end of transaction block"),
2368 errdetail_abort()));
2370 if (whereToSendOutput != DestRemote)
2371 return; /* can't actually do anything... */
2373 if (portal->tupDesc)
2374 SendRowDescriptionMessage(portal->tupDesc,
2375 FetchPortalTargetList(portal),
2378 pq_putemptymessage('n'); /* NoData */
2383 * Convenience routines for starting/committing a single command.
2386 start_xact_command(void)
2391 (errmsg_internal("StartTransactionCommand")));
2392 StartTransactionCommand();
2394 /* Set statement timeout running, if any */
2395 /* NB: this mustn't be enabled until we are within an xact */
2396 if (StatementTimeout > 0)
2397 enable_timeout_after(STATEMENT_TIMEOUT, StatementTimeout);
2399 disable_timeout(STATEMENT_TIMEOUT, false);
2401 xact_started = true;
2406 finish_xact_command(void)
2410 /* Cancel any active statement timeout before committing */
2411 disable_timeout(STATEMENT_TIMEOUT, false);
2413 /* Now commit the command */
2415 (errmsg_internal("CommitTransactionCommand")));
2417 CommitTransactionCommand();
2419 #ifdef MEMORY_CONTEXT_CHECKING
2420 /* Check all memory contexts that weren't freed during commit */
2421 /* (those that were, were checked before being deleted) */
2422 MemoryContextCheck(TopMemoryContext);
2425 #ifdef SHOW_MEMORY_STATS
2426 /* Print mem stats after each commit for leak tracking */
2427 MemoryContextStats(TopMemoryContext);
2430 xact_started = false;
2436 * Convenience routines for checking whether a statement is one of the
2437 * ones that we allow in transaction-aborted state.
2440 /* Test a bare parsetree */
2442 IsTransactionExitStmt(Node *parsetree)
2444 if (parsetree && IsA(parsetree, TransactionStmt))
2446 TransactionStmt *stmt = (TransactionStmt *) parsetree;
2448 if (stmt->kind == TRANS_STMT_COMMIT ||
2449 stmt->kind == TRANS_STMT_PREPARE ||
2450 stmt->kind == TRANS_STMT_ROLLBACK ||
2451 stmt->kind == TRANS_STMT_ROLLBACK_TO)
2457 /* Test a list that might contain Query nodes or bare parsetrees */
2459 IsTransactionExitStmtList(List *parseTrees)
2461 if (list_length(parseTrees) == 1)
2463 Node *stmt = (Node *) linitial(parseTrees);
2465 if (IsA(stmt, Query))
2467 Query *query = (Query *) stmt;
2469 if (query->commandType == CMD_UTILITY &&
2470 IsTransactionExitStmt(query->utilityStmt))
2473 else if (IsTransactionExitStmt(stmt))
2479 /* Test a list that might contain Query nodes or bare parsetrees */
2481 IsTransactionStmtList(List *parseTrees)
2483 if (list_length(parseTrees) == 1)
2485 Node *stmt = (Node *) linitial(parseTrees);
2487 if (IsA(stmt, Query))
2489 Query *query = (Query *) stmt;
2491 if (query->commandType == CMD_UTILITY &&
2492 IsA(query->utilityStmt, TransactionStmt))
2495 else if (IsA(stmt, TransactionStmt))
2501 /* Release any existing unnamed prepared statement */
2503 drop_unnamed_stmt(void)
2505 /* paranoia to avoid a dangling pointer in case of error */
2506 if (unnamed_stmt_psrc)
2508 CachedPlanSource *psrc = unnamed_stmt_psrc;
2510 unnamed_stmt_psrc = NULL;
2511 DropCachedPlan(psrc);
2516 /* --------------------------------
2517 * signal handler routines used in PostgresMain()
2518 * --------------------------------
2522 * quickdie() occurs when signalled SIGQUIT by the postmaster.
2524 * Some backend has bought the farm,
2525 * so we need to stop what we're doing and exit.
2528 quickdie(SIGNAL_ARGS)
2530 sigaddset(&BlockSig, SIGQUIT); /* prevent nested calls */
2531 PG_SETMASK(&BlockSig);
2534 * Prevent interrupts while exiting; though we just blocked signals that
2535 * would queue new interrupts, one may have been pending. We don't want a
2536 * quickdie() downgraded to a mere query cancel.
2541 * If we're aborting out of client auth, don't risk trying to send
2542 * anything to the client; we will likely violate the protocol, not to
2543 * mention that we may have interrupted the guts of OpenSSL or some
2544 * authentication library.
2546 if (ClientAuthInProgress && whereToSendOutput == DestRemote)
2547 whereToSendOutput = DestNone;
2550 * Ideally this should be ereport(FATAL), but then we'd not get control
2554 (errcode(ERRCODE_CRASH_SHUTDOWN),
2555 errmsg("terminating connection because of crash of another server process"),
2556 errdetail("The postmaster has commanded this server process to roll back"
2557 " the current transaction and exit, because another"
2558 " server process exited abnormally and possibly corrupted"
2560 errhint("In a moment you should be able to reconnect to the"
2561 " database and repeat your command.")));
2564 * We DO NOT want to run proc_exit() callbacks -- we're here because
2565 * shared memory may be corrupted, so we don't want to try to clean up our
2566 * transaction. Just nail the windows shut and get out of town. Now that
2567 * there's an atexit callback to prevent third-party code from breaking
2568 * things by calling exit() directly, we have to reset the callbacks
2569 * explicitly to make this work as intended.
2574 * Note we do exit(2) not exit(0). This is to force the postmaster into a
2575 * system reset cycle if some idiot DBA sends a manual SIGQUIT to a random
2576 * backend. This is necessary precisely because we don't clean up our
2577 * shared memory state. (The "dead man switch" mechanism in pmsignal.c
2578 * should ensure the postmaster sees this as a crash, too, but no harm in
2579 * being doubly sure.)
2585 * Shutdown signal from postmaster: abort transaction and exit
2586 * at soonest convenient time
2591 int save_errno = errno;
2593 /* Don't joggle the elbow of proc_exit */
2594 if (!proc_exit_inprogress)
2596 InterruptPending = true;
2597 ProcDiePending = true;
2600 * If it's safe to interrupt, and we're waiting for input or a lock,
2601 * service the interrupt immediately
2603 if (ImmediateInterruptOK && InterruptHoldoffCount == 0 &&
2604 CritSectionCount == 0)
2606 /* bump holdoff count to make ProcessInterrupts() a no-op */
2607 /* until we are done getting ready for it */
2608 InterruptHoldoffCount++;
2609 LockErrorCleanup(); /* prevent CheckDeadLock from running */
2610 DisableNotifyInterrupt();
2611 DisableCatchupInterrupt();
2612 InterruptHoldoffCount--;
2613 ProcessInterrupts();
2617 /* If we're still here, waken anything waiting on the process latch */
2619 SetLatch(&MyProc->procLatch);
2625 * Query-cancel signal from postmaster: abort current transaction
2626 * at soonest convenient time
2629 StatementCancelHandler(SIGNAL_ARGS)
2631 int save_errno = errno;
2634 * Don't joggle the elbow of proc_exit
2636 if (!proc_exit_inprogress)
2638 InterruptPending = true;
2639 QueryCancelPending = true;
2642 * If it's safe to interrupt, and we're waiting for input or a lock,
2643 * service the interrupt immediately
2645 if (ImmediateInterruptOK && InterruptHoldoffCount == 0 &&
2646 CritSectionCount == 0)
2648 /* bump holdoff count to make ProcessInterrupts() a no-op */
2649 /* until we are done getting ready for it */
2650 InterruptHoldoffCount++;
2651 LockErrorCleanup(); /* prevent CheckDeadLock from running */
2652 DisableNotifyInterrupt();
2653 DisableCatchupInterrupt();
2654 InterruptHoldoffCount--;
2655 ProcessInterrupts();
2659 /* If we're still here, waken anything waiting on the process latch */
2661 SetLatch(&MyProc->procLatch);
2666 /* signal handler for floating point exception */
2668 FloatExceptionHandler(SIGNAL_ARGS)
2670 /* We're not returning, so no need to save errno */
2672 (errcode(ERRCODE_FLOATING_POINT_EXCEPTION),
2673 errmsg("floating-point exception"),
2674 errdetail("An invalid floating-point operation was signaled. "
2675 "This probably means an out-of-range result or an "
2676 "invalid operation, such as division by zero.")));
2679 /* SIGHUP: set flag to re-read config file at next convenient time */
2681 SigHupHandler(SIGNAL_ARGS)
2683 int save_errno = errno;
2687 SetLatch(&MyProc->procLatch);
2693 * RecoveryConflictInterrupt: out-of-line portion of recovery conflict
2694 * handling following receipt of SIGUSR1. Designed to be similar to die()
2695 * and StatementCancelHandler(). Called only by a normal user backend
2696 * that begins a transaction during recovery.
2699 RecoveryConflictInterrupt(ProcSignalReason reason)
2701 int save_errno = errno;
2704 * Don't joggle the elbow of proc_exit
2706 if (!proc_exit_inprogress)
2708 RecoveryConflictReason = reason;
2711 case PROCSIG_RECOVERY_CONFLICT_STARTUP_DEADLOCK:
2714 * If we aren't waiting for a lock we can never deadlock.
2716 if (!IsWaitingForLock())
2719 /* Intentional drop through to check wait for pin */
2721 case PROCSIG_RECOVERY_CONFLICT_BUFFERPIN:
2724 * If we aren't blocking the Startup process there is nothing
2727 if (!HoldingBufferPinThatDelaysRecovery())
2730 MyProc->recoveryConflictPending = true;
2732 /* Intentional drop through to error handling */
2734 case PROCSIG_RECOVERY_CONFLICT_LOCK:
2735 case PROCSIG_RECOVERY_CONFLICT_TABLESPACE:
2736 case PROCSIG_RECOVERY_CONFLICT_SNAPSHOT:
2739 * If we aren't in a transaction any longer then ignore.
2741 if (!IsTransactionOrTransactionBlock())
2745 * If we can abort just the current subtransaction then we are
2746 * OK to throw an ERROR to resolve the conflict. Otherwise
2747 * drop through to the FATAL case.
2749 * XXX other times that we can throw just an ERROR *may* be
2750 * PROCSIG_RECOVERY_CONFLICT_LOCK if no locks are held in
2751 * parent transactions
2753 * PROCSIG_RECOVERY_CONFLICT_SNAPSHOT if no snapshots are held
2754 * by parent transactions and the transaction is not
2755 * transaction-snapshot mode
2757 * PROCSIG_RECOVERY_CONFLICT_TABLESPACE if no temp files or
2758 * cursors open in parent transactions
2760 if (!IsSubTransaction())
2763 * If we already aborted then we no longer need to cancel.
2764 * We do this here since we do not wish to ignore aborted
2765 * subtransactions, which must cause FATAL, currently.
2767 if (IsAbortedTransactionBlockState())
2770 RecoveryConflictPending = true;
2771 QueryCancelPending = true;
2772 InterruptPending = true;
2776 /* Intentional drop through to session cancel */
2778 case PROCSIG_RECOVERY_CONFLICT_DATABASE:
2779 RecoveryConflictPending = true;
2780 ProcDiePending = true;
2781 InterruptPending = true;
2785 elog(FATAL, "unrecognized conflict mode: %d",
2789 Assert(RecoveryConflictPending && (QueryCancelPending || ProcDiePending));
2792 * All conflicts apart from database cause dynamic errors where the
2793 * command or transaction can be retried at a later point with some
2794 * potential for success. No need to reset this, since non-retryable
2795 * conflict errors are currently FATAL.
2797 if (reason == PROCSIG_RECOVERY_CONFLICT_DATABASE)
2798 RecoveryConflictRetryable = false;
2801 * If it's safe to interrupt, and we're waiting for input or a lock,
2802 * service the interrupt immediately
2804 if (ImmediateInterruptOK && InterruptHoldoffCount == 0 &&
2805 CritSectionCount == 0)
2807 /* bump holdoff count to make ProcessInterrupts() a no-op */
2808 /* until we are done getting ready for it */
2809 InterruptHoldoffCount++;
2810 LockErrorCleanup(); /* prevent CheckDeadLock from running */
2811 DisableNotifyInterrupt();
2812 DisableCatchupInterrupt();
2813 InterruptHoldoffCount--;
2814 ProcessInterrupts();
2822 * ProcessInterrupts: out-of-line portion of CHECK_FOR_INTERRUPTS() macro
2824 * If an interrupt condition is pending, and it's safe to service it,
2825 * then clear the flag and accept the interrupt. Called only when
2826 * InterruptPending is true.
2829 ProcessInterrupts(void)
2831 /* OK to accept interrupt now? */
2832 if (InterruptHoldoffCount != 0 || CritSectionCount != 0)
2834 InterruptPending = false;
2837 ProcDiePending = false;
2838 QueryCancelPending = false; /* ProcDie trumps QueryCancel */
2839 ImmediateInterruptOK = false; /* not idle anymore */
2840 DisableNotifyInterrupt();
2841 DisableCatchupInterrupt();
2842 /* As in quickdie, don't risk sending to client during auth */
2843 if (ClientAuthInProgress && whereToSendOutput == DestRemote)
2844 whereToSendOutput = DestNone;
2845 if (IsAutoVacuumWorkerProcess())
2847 (errcode(ERRCODE_ADMIN_SHUTDOWN),
2848 errmsg("terminating autovacuum process due to administrator command")));
2849 else if (RecoveryConflictPending && RecoveryConflictRetryable)
2851 pgstat_report_recovery_conflict(RecoveryConflictReason);
2853 (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
2854 errmsg("terminating connection due to conflict with recovery"),
2855 errdetail_recovery_conflict()));
2857 else if (RecoveryConflictPending)
2859 /* Currently there is only one non-retryable recovery conflict */
2860 Assert(RecoveryConflictReason == PROCSIG_RECOVERY_CONFLICT_DATABASE);
2861 pgstat_report_recovery_conflict(RecoveryConflictReason);
2863 (errcode(ERRCODE_DATABASE_DROPPED),
2864 errmsg("terminating connection due to conflict with recovery"),
2865 errdetail_recovery_conflict()));
2869 (errcode(ERRCODE_ADMIN_SHUTDOWN),
2870 errmsg("terminating connection due to administrator command")));
2872 if (ClientConnectionLost)
2874 QueryCancelPending = false; /* lost connection trumps QueryCancel */
2875 ImmediateInterruptOK = false; /* not idle anymore */
2876 DisableNotifyInterrupt();
2877 DisableCatchupInterrupt();
2878 /* don't send to client, we already know the connection to be dead. */
2879 whereToSendOutput = DestNone;
2881 (errcode(ERRCODE_CONNECTION_FAILURE),
2882 errmsg("connection to client lost")));
2884 if (QueryCancelPending)
2886 QueryCancelPending = false;
2887 if (ClientAuthInProgress)
2889 ImmediateInterruptOK = false; /* not idle anymore */
2890 DisableNotifyInterrupt();
2891 DisableCatchupInterrupt();
2892 /* As in quickdie, don't risk sending to client during auth */
2893 if (whereToSendOutput == DestRemote)
2894 whereToSendOutput = DestNone;
2896 (errcode(ERRCODE_QUERY_CANCELED),
2897 errmsg("canceling authentication due to timeout")));
2901 * If LOCK_TIMEOUT and STATEMENT_TIMEOUT indicators are both set, we
2902 * prefer to report the former; but be sure to clear both.
2904 if (get_timeout_indicator(LOCK_TIMEOUT, true))
2906 ImmediateInterruptOK = false; /* not idle anymore */
2907 (void) get_timeout_indicator(STATEMENT_TIMEOUT, true);
2908 DisableNotifyInterrupt();
2909 DisableCatchupInterrupt();
2911 (errcode(ERRCODE_LOCK_NOT_AVAILABLE),
2912 errmsg("canceling statement due to lock timeout")));
2914 if (get_timeout_indicator(STATEMENT_TIMEOUT, true))
2916 ImmediateInterruptOK = false; /* not idle anymore */
2917 DisableNotifyInterrupt();
2918 DisableCatchupInterrupt();
2920 (errcode(ERRCODE_QUERY_CANCELED),
2921 errmsg("canceling statement due to statement timeout")));
2923 if (IsAutoVacuumWorkerProcess())
2925 ImmediateInterruptOK = false; /* not idle anymore */
2926 DisableNotifyInterrupt();
2927 DisableCatchupInterrupt();
2929 (errcode(ERRCODE_QUERY_CANCELED),
2930 errmsg("canceling autovacuum task")));
2932 if (RecoveryConflictPending)
2934 ImmediateInterruptOK = false; /* not idle anymore */
2935 RecoveryConflictPending = false;
2936 DisableNotifyInterrupt();
2937 DisableCatchupInterrupt();
2938 pgstat_report_recovery_conflict(RecoveryConflictReason);
2939 if (DoingCommandRead)
2941 (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
2942 errmsg("terminating connection due to conflict with recovery"),
2943 errdetail_recovery_conflict(),
2944 errhint("In a moment you should be able to reconnect to the"
2945 " database and repeat your command.")));
2948 (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
2949 errmsg("canceling statement due to conflict with recovery"),
2950 errdetail_recovery_conflict()));
2954 * If we are reading a command from the client, just ignore the cancel
2955 * request --- sending an extra error message won't accomplish
2956 * anything. Otherwise, go ahead and throw the error.
2958 if (!DoingCommandRead)
2960 ImmediateInterruptOK = false; /* not idle anymore */
2961 DisableNotifyInterrupt();
2962 DisableCatchupInterrupt();
2964 (errcode(ERRCODE_QUERY_CANCELED),
2965 errmsg("canceling statement due to user request")));
2968 /* If we get here, do nothing (probably, QueryCancelPending was reset) */
2973 * IA64-specific code to fetch the AR.BSP register for stack depth checks.
2975 * We currently support gcc, icc, and HP-UX inline assembly here.
2977 #if defined(__ia64__) || defined(__ia64)
2979 #if defined(__hpux) && !defined(__GNUC__) && !defined __INTEL_COMPILER
2980 #include <ia64/sys/inline.h>
2981 #define ia64_get_bsp() ((char *) (_Asm_mov_from_ar(_AREG_BSP, _NO_FENCE)))
2984 #ifdef __INTEL_COMPILER
2985 #include <asm/ia64regs.h>
2988 static __inline__ char *
2993 #ifndef __INTEL_COMPILER
2994 /* the ;; is a "stop", seems to be required before fetching BSP */
2995 __asm__ __volatile__(
3000 ret = (char *) __getReg(_IA64_REG_AR_BSP);
3009 * set_stack_base: set up reference point for stack depth checking
3011 * Returns the old reference point, if any.
3014 set_stack_base(void)
3017 pg_stack_base_t old;
3019 #if defined(__ia64__) || defined(__ia64)
3020 old.stack_base_ptr = stack_base_ptr;
3021 old.register_stack_base_ptr = register_stack_base_ptr;
3023 old = stack_base_ptr;
3026 /* Set up reference point for stack depth checking */
3027 stack_base_ptr = &stack_base;
3028 #if defined(__ia64__) || defined(__ia64)
3029 register_stack_base_ptr = ia64_get_bsp();
3036 * restore_stack_base: restore reference point for stack depth checking
3038 * This can be used after set_stack_base() to restore the old value. This
3039 * is currently only used in PL/Java. When PL/Java calls a backend function
3040 * from different thread, the thread's stack is at a different location than
3041 * the main thread's stack, so it sets the base pointer before the call, and
3042 * restores it afterwards.
3045 restore_stack_base(pg_stack_base_t base)
3047 #if defined(__ia64__) || defined(__ia64)
3048 stack_base_ptr = base.stack_base_ptr;
3049 register_stack_base_ptr = base.register_stack_base_ptr;
3051 stack_base_ptr = base;
3056 * check_stack_depth: check for excessively deep recursion
3058 * This should be called someplace in any recursive routine that might possibly
3059 * recurse deep enough to overflow the stack. Most Unixen treat stack
3060 * overflow as an unrecoverable SIGSEGV, so we want to error out ourselves
3061 * before hitting the hardware limit.
3064 check_stack_depth(void)
3070 * Compute distance from reference point to my local variables
3072 stack_depth = (long) (stack_base_ptr - &stack_top_loc);
3075 * Take abs value, since stacks grow up on some machines, down on others
3077 if (stack_depth < 0)
3078 stack_depth = -stack_depth;
3083 * The test on stack_base_ptr prevents us from erroring out if called
3084 * during process setup or in a non-backend process. Logically it should
3085 * be done first, but putting it here avoids wasting cycles during normal
3088 if (stack_depth > max_stack_depth_bytes &&
3089 stack_base_ptr != NULL)
3092 (errcode(ERRCODE_STATEMENT_TOO_COMPLEX),
3093 errmsg("stack depth limit exceeded"),
3094 errhint("Increase the configuration parameter \"max_stack_depth\" (currently %dkB), "
3095 "after ensuring the platform's stack depth limit is adequate.",
3100 * On IA64 there is a separate "register" stack that requires its own
3101 * independent check. For this, we have to measure the change in the
3102 * "BSP" pointer from PostgresMain to here. Logic is just as above,
3103 * except that we know IA64's register stack grows up.
3105 * Note we assume that the same max_stack_depth applies to both stacks.
3107 #if defined(__ia64__) || defined(__ia64)
3108 stack_depth = (long) (ia64_get_bsp() - register_stack_base_ptr);
3110 if (stack_depth > max_stack_depth_bytes &&
3111 register_stack_base_ptr != NULL)
3114 (errcode(ERRCODE_STATEMENT_TOO_COMPLEX),
3115 errmsg("stack depth limit exceeded"),
3116 errhint("Increase the configuration parameter \"max_stack_depth\" (currently %dkB), "
3117 "after ensuring the platform's stack depth limit is adequate.",
3123 /* GUC check hook for max_stack_depth */
3125 check_max_stack_depth(int *newval, void **extra, GucSource source)
3127 long newval_bytes = *newval * 1024L;
3128 long stack_rlimit = get_stack_depth_rlimit();
3130 if (stack_rlimit > 0 && newval_bytes > stack_rlimit - STACK_DEPTH_SLOP)
3132 GUC_check_errdetail("\"max_stack_depth\" must not exceed %ldkB.",
3133 (stack_rlimit - STACK_DEPTH_SLOP) / 1024L);
3134 GUC_check_errhint("Increase the platform's stack depth limit via \"ulimit -s\" or local equivalent.");
3140 /* GUC assign hook for max_stack_depth */
3142 assign_max_stack_depth(int newval, void *extra)
3144 long newval_bytes = newval * 1024L;
3146 max_stack_depth_bytes = newval_bytes;
3151 * set_debug_options --- apply "-d N" command line option
3153 * -d is not quite the same as setting log_min_messages because it enables
3154 * other output options.
3157 set_debug_options(int debug_flag, GucContext context, GucSource source)
3163 sprintf(debugstr, "debug%d", debug_flag);
3164 SetConfigOption("log_min_messages", debugstr, context, source);
3167 SetConfigOption("log_min_messages", "notice", context, source);
3169 if (debug_flag >= 1 && context == PGC_POSTMASTER)
3171 SetConfigOption("log_connections", "true", context, source);
3172 SetConfigOption("log_disconnections", "true", context, source);
3174 if (debug_flag >= 2)
3175 SetConfigOption("log_statement", "all", context, source);
3176 if (debug_flag >= 3)
3177 SetConfigOption("debug_print_parse", "true", context, source);
3178 if (debug_flag >= 4)
3179 SetConfigOption("debug_print_plan", "true", context, source);
3180 if (debug_flag >= 5)
3181 SetConfigOption("debug_print_rewritten", "true", context, source);
3186 set_plan_disabling_options(const char *arg, GucContext context, GucSource source)
3188 const char *tmp = NULL;
3192 case 's': /* seqscan */
3193 tmp = "enable_seqscan";
3195 case 'i': /* indexscan */
3196 tmp = "enable_indexscan";
3198 case 'o': /* indexonlyscan */
3199 tmp = "enable_indexonlyscan";
3201 case 'b': /* bitmapscan */
3202 tmp = "enable_bitmapscan";
3204 case 't': /* tidscan */
3205 tmp = "enable_tidscan";
3207 case 'n': /* nestloop */
3208 tmp = "enable_nestloop";
3210 case 'm': /* mergejoin */
3211 tmp = "enable_mergejoin";
3213 case 'h': /* hashjoin */
3214 tmp = "enable_hashjoin";
3219 SetConfigOption(tmp, "false", context, source);
3228 get_stats_option_name(const char *arg)
3233 if (optarg[1] == 'a') /* "parser" */
3234 return "log_parser_stats";
3235 else if (optarg[1] == 'l') /* "planner" */
3236 return "log_planner_stats";
3239 case 'e': /* "executor" */
3240 return "log_executor_stats";
3248 /* ----------------------------------------------------------------
3249 * process_postgres_switches
3250 * Parse command line arguments for PostgresMain
3252 * This is called twice, once for the "secure" options coming from the
3253 * postmaster or command line, and once for the "insecure" options coming
3254 * from the client's startup packet. The latter have the same syntax but
3255 * may be restricted in what they can do.
3257 * argv[0] is ignored in either case (it's assumed to be the program name).
3259 * ctx is PGC_POSTMASTER for secure options, PGC_BACKEND for insecure options
3260 * coming from the client, or PGC_SUSET for insecure options coming from
3261 * a superuser client.
3263 * If a database name is present in the command line arguments, it's
3264 * returned into *dbname (this is allowed only if *dbname is initially NULL).
3265 * ----------------------------------------------------------------
3268 process_postgres_switches(int argc, char *argv[], GucContext ctx,
3269 const char **dbname)
3271 bool secure = (ctx == PGC_POSTMASTER);
3273 GucSource gucsource;
3278 gucsource = PGC_S_ARGV; /* switches came from command line */
3280 /* Ignore the initial --single argument, if present */
3281 if (argc > 1 && strcmp(argv[1], "--single") == 0)
3289 gucsource = PGC_S_CLIENT; /* switches came from client */
3292 #ifdef HAVE_INT_OPTERR
3295 * Turn this off because it's either printed to stderr and not the log
3296 * where we'd want it, or argv[0] is now "--single", which would make for
3297 * a weird error message. We print our own error message below.
3303 * Parse command-line options. CAUTION: keep this in sync with
3304 * postmaster/postmaster.c (the option sets should not conflict) and with
3305 * the common help() function in main/main.c.
3307 while ((flag = getopt(argc, argv, "A:B:bc:C:D:d:EeFf:h:ijk:lN:nOo:Pp:r:S:sTt:v:W:-:")) != -1)
3312 SetConfigOption("debug_assertions", optarg, ctx, gucsource);
3316 SetConfigOption("shared_buffers", optarg, ctx, gucsource);
3320 /* Undocumented flag used for binary upgrades */
3322 IsBinaryUpgrade = true;
3326 /* ignored for consistency with the postmaster */
3331 userDoption = strdup(optarg);
3335 set_debug_options(atoi(optarg), ctx, gucsource);
3344 SetConfigOption("datestyle", "euro", ctx, gucsource);
3348 SetConfigOption("fsync", "false", ctx, gucsource);
3352 if (!set_plan_disabling_options(optarg, ctx, gucsource))
3357 SetConfigOption("listen_addresses", optarg, ctx, gucsource);
3361 SetConfigOption("listen_addresses", "*", ctx, gucsource);
3370 SetConfigOption("unix_socket_directories", optarg, ctx, gucsource);
3374 SetConfigOption("ssl", "true", ctx, gucsource);
3378 SetConfigOption("max_connections", optarg, ctx, gucsource);
3382 /* ignored for consistency with postmaster */
3386 SetConfigOption("allow_system_table_mods", "true", ctx, gucsource);
3394 SetConfigOption("ignore_system_indexes", "true", ctx, gucsource);
3398 SetConfigOption("port", optarg, ctx, gucsource);
3402 /* send output (stdout and stderr) to the given file */
3404 strlcpy(OutputFileName, optarg, MAXPGPATH);
3408 SetConfigOption("work_mem", optarg, ctx, gucsource);
3412 SetConfigOption("log_statement_stats", "true", ctx, gucsource);
3416 /* ignored for consistency with the postmaster */
3421 const char *tmp = get_stats_option_name(optarg);
3424 SetConfigOption(tmp, "true", ctx, gucsource);
3433 * -v is no longer used in normal operation, since
3434 * FrontendProtocol is already set before we get here. We keep
3435 * the switch only for possible use in standalone operation,
3436 * in case we ever support using normal FE/BE protocol with a
3437 * standalone backend.
3440 FrontendProtocol = (ProtocolVersion) atoi(optarg);
3444 SetConfigOption("post_auth_delay", optarg, ctx, gucsource);
3453 ParseLongOption(optarg, &name, &value);
3458 (errcode(ERRCODE_SYNTAX_ERROR),
3459 errmsg("--%s requires a value",
3463 (errcode(ERRCODE_SYNTAX_ERROR),
3464 errmsg("-c %s requires a value",
3467 SetConfigOption(name, value, ctx, gucsource);
3484 * Optional database name should be there only if *dbname is NULL.
3486 if (!errs && dbname && *dbname == NULL && argc - optind >= 1)
3487 *dbname = strdup(argv[optind++]);
3489 if (errs || argc != optind)
3492 optind--; /* complain about the previous argument */
3494 /* spell the error message a bit differently depending on context */
3495 if (IsUnderPostmaster)
3497 (errcode(ERRCODE_SYNTAX_ERROR),
3498 errmsg("invalid command-line argument for server process: %s", argv[optind]),
3499 errhint("Try \"%s --help\" for more information.", progname)));
3502 (errcode(ERRCODE_SYNTAX_ERROR),
3503 errmsg("%s: invalid command-line argument: %s",
3504 progname, argv[optind]),
3505 errhint("Try \"%s --help\" for more information.", progname)));
3509 * Reset getopt(3) library so that it will work correctly in subprocesses
3510 * or when this function is called a second time with another array.
3513 #ifdef HAVE_INT_OPTRESET
3514 optreset = 1; /* some systems need this too */
3519 /* ----------------------------------------------------------------
3521 * postgres main loop -- all backends, interactive or otherwise start here
3523 * argc/argv are the command line arguments to be used. (When being forked
3524 * by the postmaster, these are not the original argv array of the process.)
3525 * dbname is the name of the database to connect to, or NULL if the database
3526 * name should be extracted from the command line arguments or defaulted.
3527 * username is the PostgreSQL user name to be used for the session.
3528 * ----------------------------------------------------------------
3531 PostgresMain(int argc, char *argv[],
3533 const char *username)
3536 StringInfoData input_message;
3537 sigjmp_buf local_sigjmp_buf;
3538 volatile bool send_ready_for_query = true;
3541 * Initialize globals (already done if under postmaster, but not if
3544 if (!IsUnderPostmaster)
3546 MyProcPid = getpid();
3548 MyStartTime = time(NULL);
3552 * Fire up essential subsystems: error and memory management
3554 * If we are running under the postmaster, this is done already.
3556 if (!IsUnderPostmaster)
3557 MemoryContextInit();
3559 SetProcessingMode(InitProcessing);
3561 /* Compute paths, if we didn't inherit them from postmaster */
3562 if (my_exec_path[0] == '\0')
3564 if (find_my_exec(argv[0], my_exec_path) < 0)
3565 elog(FATAL, "%s: could not locate my own executable path",
3569 if (pkglib_path[0] == '\0')
3570 get_pkglib_path(my_exec_path, pkglib_path);
3573 * Set default values for command-line options.
3575 if (!IsUnderPostmaster)
3576 InitializeGUCOptions();
3579 * Parse command-line options.
3581 process_postgres_switches(argc, argv, PGC_POSTMASTER, &dbname);
3583 /* Must have gotten a database name, or have a default (the username) */
3589 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
3590 errmsg("%s: no database nor user name specified",
3594 /* Acquire configuration parameters, unless inherited from postmaster */
3595 if (!IsUnderPostmaster)
3597 if (!SelectConfigFiles(userDoption, progname))
3602 * You might expect to see a setsid() call here, but it's not needed,
3603 * because if we are under a postmaster then BackendInitialize() did it.
3607 * Set up signal handlers and masks.
3609 * Note that postmaster blocked all signals before forking child process,
3610 * so there is no race condition whereby we might receive a signal before
3611 * we have set up the handler.
3613 * Also note: it's best not to use any signals that are SIG_IGNored in the
3614 * postmaster. If such a signal arrives before we are able to change the
3615 * handler to non-SIG_IGN, it'll get dropped. Instead, make a dummy
3616 * handler in the postmaster to reserve the signal. (Of course, this isn't
3617 * an issue for signals that are locally generated, such as SIGALRM and
3624 pqsignal(SIGHUP, SigHupHandler); /* set flag to read config
3626 pqsignal(SIGINT, StatementCancelHandler); /* cancel current query */
3627 pqsignal(SIGTERM, die); /* cancel current query and exit */
3630 * In a standalone backend, SIGQUIT can be generated from the keyboard
3631 * easily, while SIGTERM cannot, so we make both signals do die()
3632 * rather than quickdie().
3634 if (IsUnderPostmaster)
3635 pqsignal(SIGQUIT, quickdie); /* hard crash time */
3637 pqsignal(SIGQUIT, die); /* cancel current query and exit */
3638 InitializeTimeouts(); /* establishes SIGALRM handler */
3641 * Ignore failure to write to frontend. Note: if frontend closes
3642 * connection, we will notice it and exit cleanly when control next
3643 * returns to outer loop. This seems safer than forcing exit in the
3644 * midst of output during who-knows-what operation...
3646 pqsignal(SIGPIPE, SIG_IGN);
3647 pqsignal(SIGUSR1, procsignal_sigusr1_handler);
3648 pqsignal(SIGUSR2, SIG_IGN);
3649 pqsignal(SIGFPE, FloatExceptionHandler);
3652 * Reset some signals that are accepted by postmaster but not by
3655 pqsignal(SIGCHLD, SIG_DFL); /* system() requires this on some
3661 if (IsUnderPostmaster)
3663 /* We allow SIGQUIT (quickdie) at all times */
3664 sigdelset(&BlockSig, SIGQUIT);
3667 PG_SETMASK(&BlockSig); /* block everything except SIGQUIT */
3669 if (!IsUnderPostmaster)
3672 * Validate we have been given a reasonable-looking DataDir (if under
3673 * postmaster, assume postmaster did this already).
3676 ValidatePgVersion(DataDir);
3678 /* Change into DataDir (if under postmaster, was done already) */
3682 * Create lockfile for data directory.
3684 CreateDataDirLockFile(false);
3686 /* Initialize MaxBackends (if under postmaster, was done already) */
3687 InitializeMaxBackends();
3690 /* Early initialization */
3694 * Create a per-backend PGPROC struct in shared memory, except in the
3695 * EXEC_BACKEND case where this was done in SubPostmasterMain. We must do
3696 * this before we can use LWLocks (and in the EXEC_BACKEND case we already
3697 * had to do some stuff with LWLocks).
3700 if (!IsUnderPostmaster)
3706 /* We need to allow SIGINT, etc during the initial transaction */
3707 PG_SETMASK(&UnBlockSig);
3710 * General initialization.
3712 * NOTE: if you are tempted to add code in this vicinity, consider putting
3713 * it inside InitPostgres() instead. In particular, anything that
3714 * involves database access should be there, not here.
3716 InitPostgres(dbname, InvalidOid, username, NULL);
3719 * If the PostmasterContext is still around, recycle the space; we don't
3720 * need it anymore after InitPostgres completes. Note this does not trash
3721 * *MyProcPort, because ConnCreate() allocated that space with malloc()
3722 * ... else we'd need to copy the Port data first. Also, subsidiary data
3723 * such as the username isn't lost either; see ProcessStartupPacket().
3725 if (PostmasterContext)
3727 MemoryContextDelete(PostmasterContext);
3728 PostmasterContext = NULL;
3731 SetProcessingMode(NormalProcessing);
3734 * Now all GUC states are fully set up. Report them to client if
3737 BeginReportingGUCOptions();
3740 * Also set up handler to log session end; we have to wait till now to be
3741 * sure Log_disconnections has its final value.
3743 if (IsUnderPostmaster && Log_disconnections)
3744 on_proc_exit(log_disconnections, 0);
3746 /* Perform initialization specific to a WAL sender process. */
3751 * process any libraries that should be preloaded at backend start (this
3752 * likewise can't be done until GUC settings are complete)
3754 process_session_preload_libraries();
3757 * Send this backend's cancellation info to the frontend.
3759 if (whereToSendOutput == DestRemote &&
3760 PG_PROTOCOL_MAJOR(FrontendProtocol) >= 2)
3764 pq_beginmessage(&buf, 'K');
3765 pq_sendint(&buf, (int32) MyProcPid, sizeof(int32));
3766 pq_sendint(&buf, (int32) MyCancelKey, sizeof(int32));
3767 pq_endmessage(&buf);
3768 /* Need not flush since ReadyForQuery will do it. */
3771 /* Welcome banner for standalone case */
3772 if (whereToSendOutput == DestDebug)
3773 printf("\nPostgreSQL stand-alone backend %s\n", PG_VERSION);
3776 * Create the memory context we will use in the main loop.
3778 * MessageContext is reset once per iteration of the main loop, ie, upon
3779 * completion of processing of each command message from the client.
3781 MessageContext = AllocSetContextCreate(TopMemoryContext,
3783 ALLOCSET_DEFAULT_MINSIZE,
3784 ALLOCSET_DEFAULT_INITSIZE,
3785 ALLOCSET_DEFAULT_MAXSIZE);
3788 * Remember stand-alone backend startup time
3790 if (!IsUnderPostmaster)
3791 PgStartTime = GetCurrentTimestamp();
3794 * POSTGRES main processing loop begins here
3796 * If an exception is encountered, processing resumes here so we abort the
3797 * current transaction and start a new one.
3799 * You might wonder why this isn't coded as an infinite loop around a
3800 * PG_TRY construct. The reason is that this is the bottom of the
3801 * exception stack, and so with PG_TRY there would be no exception handler
3802 * in force at all during the CATCH part. By leaving the outermost setjmp
3803 * always active, we have at least some chance of recovering from an error
3804 * during error recovery. (If we get into an infinite loop thereby, it
3805 * will soon be stopped by overflow of elog.c's internal state stack.)
3807 * Note that we use sigsetjmp(..., 1), so that this function's signal mask
3808 * (to wit, UnBlockSig) will be restored when longjmp'ing to here. This
3809 * is essential in case we longjmp'd out of a signal handler on a platform
3810 * where that leaves the signal blocked. It's not redundant with the
3811 * unblock in AbortTransaction() because the latter is only called if we
3812 * were inside a transaction.
3815 if (sigsetjmp(local_sigjmp_buf, 1) != 0)
3818 * NOTE: if you are tempted to add more code in this if-block,
3819 * consider the high probability that it should be in
3820 * AbortTransaction() instead. The only stuff done directly here
3821 * should be stuff that is guaranteed to apply *only* for outer-level
3822 * error recovery, such as adjusting the FE/BE protocol status.
3825 /* Since not using PG_TRY, must reset error stack by hand */
3826 error_context_stack = NULL;
3828 /* Prevent interrupts while cleaning up */
3832 * Forget any pending QueryCancel request, since we're returning to
3833 * the idle loop anyway, and cancel any active timeout requests. (In
3834 * future we might want to allow some timeout requests to survive, but
3835 * at minimum it'd be necessary to do reschedule_timeouts(), in case
3836 * we got here because of a query cancel interrupting the SIGALRM
3837 * interrupt handler.) Note in particular that we must clear the
3838 * statement and lock timeout indicators, to prevent any future plain
3839 * query cancels from being misreported as timeouts in case we're
3840 * forgetting a timeout cancel.
3842 disable_all_timeouts(false);
3843 QueryCancelPending = false; /* second to avoid race condition */
3846 * Turn off these interrupts too. This is only needed here and not in
3847 * other exception-catching places since these interrupts are only
3848 * enabled while we wait for client input.
3850 DoingCommandRead = false;
3851 DisableNotifyInterrupt();
3852 DisableCatchupInterrupt();
3854 /* Make sure libpq is in a good state */
3857 /* Report the error to the client and/or server log */
3861 * Make sure debug_query_string gets reset before we possibly clobber
3862 * the storage it points at.
3864 debug_query_string = NULL;
3867 * Abort the current transaction in order to recover.
3869 AbortCurrentTransaction();
3872 WalSndErrorCleanup();
3875 * Now return to normal top-level context and clear ErrorContext for
3878 MemoryContextSwitchTo(TopMemoryContext);
3882 * If we were handling an extended-query-protocol message, initiate
3883 * skip till next Sync. This also causes us not to issue
3884 * ReadyForQuery (until we get Sync).
3886 if (doing_extended_query_message)
3887 ignore_till_sync = true;
3889 /* We don't have a transaction command open anymore */
3890 xact_started = false;
3892 /* Now we can allow interrupts again */
3893 RESUME_INTERRUPTS();
3896 /* We can now handle ereport(ERROR) */
3897 PG_exception_stack = &local_sigjmp_buf;
3899 if (!ignore_till_sync)
3900 send_ready_for_query = true; /* initially, or after error */
3903 * Non-error queries loop here.
3909 * At top of loop, reset extended-query-message flag, so that any
3910 * errors encountered in "idle" state don't provoke skip.
3912 doing_extended_query_message = false;
3915 * Release storage left over from prior query cycle, and create a new
3916 * query input buffer in the cleared MessageContext.
3918 MemoryContextSwitchTo(MessageContext);
3919 MemoryContextResetAndDeleteChildren(MessageContext);
3921 initStringInfo(&input_message);
3924 * (1) If we've reached idle state, tell the frontend we're ready for
3927 * Note: this includes fflush()'ing the last of the prior output.
3929 * This is also a good time to send collected statistics to the
3930 * collector, and to update the PS stats display. We avoid doing
3931 * those every time through the message loop because it'd slow down
3932 * processing of batched messages, and because we don't want to report
3933 * uncommitted updates (that confuses autovacuum). The notification
3934 * processor wants a call too, if we are not in a transaction block.
3936 if (send_ready_for_query)
3938 if (IsAbortedTransactionBlockState())
3940 set_ps_display("idle in transaction (aborted)", false);
3941 pgstat_report_activity(STATE_IDLEINTRANSACTION_ABORTED, NULL);
3943 else if (IsTransactionOrTransactionBlock())
3945 set_ps_display("idle in transaction", false);
3946 pgstat_report_activity(STATE_IDLEINTRANSACTION, NULL);
3950 ProcessCompletedNotifies();
3951 pgstat_report_stat(false);
3953 set_ps_display("idle", false);
3954 pgstat_report_activity(STATE_IDLE, NULL);
3957 ReadyForQuery(whereToSendOutput);
3958 send_ready_for_query = false;
3962 * (2) Allow asynchronous signals to be executed immediately if they
3963 * come in while we are waiting for client input. (This must be
3964 * conditional since we don't want, say, reads on behalf of COPY FROM
3965 * STDIN doing the same thing.)
3967 DoingCommandRead = true;
3970 * (3) read a command (loop blocks here)
3972 firstchar = ReadCommand(&input_message);
3975 * (4) disable async signal conditions again.
3977 DoingCommandRead = false;
3980 * (5) check for any other interesting events that happened while we
3986 ProcessConfigFile(PGC_SIGHUP);
3990 * (6) process the command. But ignore it if we're skipping till
3993 if (ignore_till_sync && firstchar != EOF)
3998 case 'Q': /* simple query */
4000 const char *query_string;
4002 /* Set statement_timestamp() */
4003 SetCurrentStatementStartTimestamp();
4005 query_string = pq_getmsgstring(&input_message);
4006 pq_getmsgend(&input_message);
4009 exec_replication_command(query_string);
4011 exec_simple_query(query_string);
4013 send_ready_for_query = true;
4017 case 'P': /* parse */
4019 const char *stmt_name;
4020 const char *query_string;
4022 Oid *paramTypes = NULL;
4024 forbidden_in_wal_sender(firstchar);
4026 /* Set statement_timestamp() */
4027 SetCurrentStatementStartTimestamp();
4029 stmt_name = pq_getmsgstring(&input_message);
4030 query_string = pq_getmsgstring(&input_message);
4031 numParams = pq_getmsgint(&input_message, 2);
4036 paramTypes = (Oid *) palloc(numParams * sizeof(Oid));
4037 for (i = 0; i < numParams; i++)
4038 paramTypes[i] = pq_getmsgint(&input_message, 4);
4040 pq_getmsgend(&input_message);
4042 exec_parse_message(query_string, stmt_name,
4043 paramTypes, numParams);
4047 case 'B': /* bind */
4048 forbidden_in_wal_sender(firstchar);
4050 /* Set statement_timestamp() */
4051 SetCurrentStatementStartTimestamp();
4054 * this message is complex enough that it seems best to put
4055 * the field extraction out-of-line
4057 exec_bind_message(&input_message);
4060 case 'E': /* execute */
4062 const char *portal_name;
4065 forbidden_in_wal_sender(firstchar);
4067 /* Set statement_timestamp() */
4068 SetCurrentStatementStartTimestamp();
4070 portal_name = pq_getmsgstring(&input_message);
4071 max_rows = pq_getmsgint(&input_message, 4);
4072 pq_getmsgend(&input_message);
4074 exec_execute_message(portal_name, max_rows);
4078 case 'F': /* fastpath function call */
4079 forbidden_in_wal_sender(firstchar);
4081 /* Set statement_timestamp() */
4082 SetCurrentStatementStartTimestamp();
4084 /* Report query to various monitoring facilities. */
4085 pgstat_report_activity(STATE_FASTPATH, NULL);
4086 set_ps_display("<FASTPATH>", false);
4088 /* start an xact for this function invocation */
4089 start_xact_command();
4092 * Note: we may at this point be inside an aborted
4093 * transaction. We can't throw error for that until we've
4094 * finished reading the function-call message, so
4095 * HandleFunctionRequest() must check for it after doing so.
4096 * Be careful not to do anything that assumes we're inside a
4097 * valid transaction here.
4100 /* switch back to message context */
4101 MemoryContextSwitchTo(MessageContext);
4103 if (HandleFunctionRequest(&input_message) == EOF)
4105 /* lost frontend connection during F message input */
4108 * Reset whereToSendOutput to prevent ereport from
4109 * attempting to send any more messages to client.
4111 if (whereToSendOutput == DestRemote)
4112 whereToSendOutput = DestNone;
4117 /* commit the function-invocation transaction */
4118 finish_xact_command();
4120 send_ready_for_query = true;
4123 case 'C': /* close */
4126 const char *close_target;
4128 forbidden_in_wal_sender(firstchar);
4130 close_type = pq_getmsgbyte(&input_message);
4131 close_target = pq_getmsgstring(&input_message);
4132 pq_getmsgend(&input_message);
4137 if (close_target[0] != '\0')
4138 DropPreparedStatement(close_target, false);
4141 /* special-case the unnamed statement */
4142 drop_unnamed_stmt();
4149 portal = GetPortalByName(close_target);
4150 if (PortalIsValid(portal))
4151 PortalDrop(portal, false);
4156 (errcode(ERRCODE_PROTOCOL_VIOLATION),
4157 errmsg("invalid CLOSE message subtype %d",
4162 if (whereToSendOutput == DestRemote)
4163 pq_putemptymessage('3'); /* CloseComplete */
4167 case 'D': /* describe */
4170 const char *describe_target;
4172 forbidden_in_wal_sender(firstchar);
4174 /* Set statement_timestamp() (needed for xact) */
4175 SetCurrentStatementStartTimestamp();
4177 describe_type = pq_getmsgbyte(&input_message);
4178 describe_target = pq_getmsgstring(&input_message);
4179 pq_getmsgend(&input_message);
4181 switch (describe_type)
4184 exec_describe_statement_message(describe_target);
4187 exec_describe_portal_message(describe_target);
4191 (errcode(ERRCODE_PROTOCOL_VIOLATION),
4192 errmsg("invalid DESCRIBE message subtype %d",
4199 case 'H': /* flush */
4200 pq_getmsgend(&input_message);
4201 if (whereToSendOutput == DestRemote)
4205 case 'S': /* sync */
4206 pq_getmsgend(&input_message);
4207 finish_xact_command();
4208 send_ready_for_query = true;
4212 * 'X' means that the frontend is closing down the socket. EOF
4213 * means unexpected loss of frontend connection. Either way,
4214 * perform normal shutdown.
4220 * Reset whereToSendOutput to prevent ereport from attempting
4221 * to send any more messages to client.
4223 if (whereToSendOutput == DestRemote)
4224 whereToSendOutput = DestNone;
4227 * NOTE: if you are tempted to add more code here, DON'T!
4228 * Whatever you had in mind to do should be set up as an
4229 * on_proc_exit or on_shmem_exit callback, instead. Otherwise
4230 * it will fail to be called during other backend-shutdown
4235 case 'd': /* copy data */
4236 case 'c': /* copy done */
4237 case 'f': /* copy fail */
4240 * Accept but ignore these messages, per protocol spec; we
4241 * probably got here because a COPY failed, and the frontend
4242 * is still sending data.
4248 (errcode(ERRCODE_PROTOCOL_VIOLATION),
4249 errmsg("invalid frontend message type %d",
4252 } /* end of input-reading loop */
4256 * Throw an error if we're a WAL sender process.
4258 * This is used to forbid anything else than simple query protocol messages
4259 * in a WAL sender process. 'firstchar' specifies what kind of a forbidden
4260 * message was received, and is used to construct the error message.
4263 forbidden_in_wal_sender(char firstchar)
4267 if (firstchar == 'F')
4269 (errcode(ERRCODE_PROTOCOL_VIOLATION),
4270 errmsg("fastpath function calls not supported in a replication connection")));
4273 (errcode(ERRCODE_PROTOCOL_VIOLATION),
4274 errmsg("extended query protocol not supported in a replication connection")));
4280 * Obtain platform stack depth limit (in bytes)
4282 * Return -1 if unknown
4285 get_stack_depth_rlimit(void)
4287 #if defined(HAVE_GETRLIMIT) && defined(RLIMIT_STACK)
4288 static long val = 0;
4290 /* This won't change after process launch, so check just once */
4295 if (getrlimit(RLIMIT_STACK, &rlim) < 0)
4297 else if (rlim.rlim_cur == RLIM_INFINITY)
4299 /* rlim_cur is probably of an unsigned type, so check for overflow */
4300 else if (rlim.rlim_cur >= LONG_MAX)
4303 val = rlim.rlim_cur;
4306 #else /* no getrlimit */
4307 #if defined(WIN32) || defined(__CYGWIN__)
4308 /* On Windows we set the backend stack size in src/backend/Makefile */
4309 return WIN32_STACK_RLIMIT;
4310 #else /* not windows ... give up */
4317 static struct rusage Save_r;
4318 static struct timeval Save_t;
4323 getrusage(RUSAGE_SELF, &Save_r);
4324 gettimeofday(&Save_t, NULL);
4328 ShowUsage(const char *title)
4331 struct timeval user,
4333 struct timeval elapse_t;
4336 getrusage(RUSAGE_SELF, &r);
4337 gettimeofday(&elapse_t, NULL);
4338 memcpy((char *) &user, (char *) &r.ru_utime, sizeof(user));
4339 memcpy((char *) &sys, (char *) &r.ru_stime, sizeof(sys));
4340 if (elapse_t.tv_usec < Save_t.tv_usec)
4343 elapse_t.tv_usec += 1000000;
4345 if (r.ru_utime.tv_usec < Save_r.ru_utime.tv_usec)
4347 r.ru_utime.tv_sec--;
4348 r.ru_utime.tv_usec += 1000000;
4350 if (r.ru_stime.tv_usec < Save_r.ru_stime.tv_usec)
4352 r.ru_stime.tv_sec--;
4353 r.ru_stime.tv_usec += 1000000;
4357 * the only stats we don't show here are for memory usage -- i can't
4358 * figure out how to interpret the relevant fields in the rusage struct,
4359 * and they change names across o/s platforms, anyway. if you can figure
4360 * out what the entries mean, you can somehow extract resident set size,
4361 * shared text size, and unshared data and stack sizes.
4363 initStringInfo(&str);
4365 appendStringInfoString(&str, "! system usage stats:\n");
4366 appendStringInfo(&str,
4367 "!\t%ld.%06ld elapsed %ld.%06ld user %ld.%06ld system sec\n",
4368 (long) (elapse_t.tv_sec - Save_t.tv_sec),
4369 (long) (elapse_t.tv_usec - Save_t.tv_usec),
4370 (long) (r.ru_utime.tv_sec - Save_r.ru_utime.tv_sec),
4371 (long) (r.ru_utime.tv_usec - Save_r.ru_utime.tv_usec),
4372 (long) (r.ru_stime.tv_sec - Save_r.ru_stime.tv_sec),
4373 (long) (r.ru_stime.tv_usec - Save_r.ru_stime.tv_usec));
4374 appendStringInfo(&str,
4375 "!\t[%ld.%06ld user %ld.%06ld sys total]\n",
4377 (long) user.tv_usec,
4379 (long) sys.tv_usec);
4380 #if defined(HAVE_GETRUSAGE)
4381 appendStringInfo(&str,
4382 "!\t%ld/%ld [%ld/%ld] filesystem blocks in/out\n",
4383 r.ru_inblock - Save_r.ru_inblock,
4384 /* they only drink coffee at dec */
4385 r.ru_oublock - Save_r.ru_oublock,
4386 r.ru_inblock, r.ru_oublock);
4387 appendStringInfo(&str,
4388 "!\t%ld/%ld [%ld/%ld] page faults/reclaims, %ld [%ld] swaps\n",
4389 r.ru_majflt - Save_r.ru_majflt,
4390 r.ru_minflt - Save_r.ru_minflt,
4391 r.ru_majflt, r.ru_minflt,
4392 r.ru_nswap - Save_r.ru_nswap,
4394 appendStringInfo(&str,
4395 "!\t%ld [%ld] signals rcvd, %ld/%ld [%ld/%ld] messages rcvd/sent\n",
4396 r.ru_nsignals - Save_r.ru_nsignals,
4398 r.ru_msgrcv - Save_r.ru_msgrcv,
4399 r.ru_msgsnd - Save_r.ru_msgsnd,
4400 r.ru_msgrcv, r.ru_msgsnd);
4401 appendStringInfo(&str,
4402 "!\t%ld/%ld [%ld/%ld] voluntary/involuntary context switches\n",
4403 r.ru_nvcsw - Save_r.ru_nvcsw,
4404 r.ru_nivcsw - Save_r.ru_nivcsw,
4405 r.ru_nvcsw, r.ru_nivcsw);
4406 #endif /* HAVE_GETRUSAGE */
4408 /* remove trailing newline */
4409 if (str.data[str.len - 1] == '\n')
4410 str.data[--str.len] = '\0';
4413 (errmsg_internal("%s", title),
4414 errdetail_internal("%s", str.data)));
4420 * on_proc_exit handler to log end of session
4423 log_disconnections(int code, Datum arg)
4425 Port *port = MyProcPort;
4433 TimestampDifference(port->SessionStartTime,
4434 GetCurrentTimestamp(),
4436 msecs = usecs / 1000;
4438 hours = secs / SECS_PER_HOUR;
4439 secs %= SECS_PER_HOUR;
4440 minutes = secs / SECS_PER_MINUTE;
4441 seconds = secs % SECS_PER_MINUTE;
4444 (errmsg("disconnection: session time: %d:%02d:%02d.%03d "
4445 "user=%s database=%s host=%s%s%s",
4446 hours, minutes, seconds, msecs,
4447 port->user_name, port->database_name, port->remote_host,
4448 port->remote_port[0] ? " port=" : "", port->remote_port)));