1 /*-------------------------------------------------------------------------
4 * POSTGRES C Backend Interface
6 * Portions Copyright (c) 1996-2010, 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 "mb/pg_wchar.h"
81 /* If not HAVE_GETOPT, we are using src/port/getopt.c, which has optreset */
82 #if defined(HAVE_INT_OPTRESET) || !defined(HAVE_GETOPT)
83 extern int optreset; /* might not be declared by system headers */
91 const char *debug_query_string; /* client-supplied query string */
93 /* Note: whereToSendOutput is initialized for the bootstrap/standalone case */
94 CommandDest whereToSendOutput = DestDebug;
96 /* flag for logging end of session */
97 bool Log_disconnections = false;
99 int log_statement = LOGSTMT_NONE;
101 /* GUC variable for maximum stack depth (measured in kilobytes) */
102 int max_stack_depth = 100;
104 /* wait N seconds to allow attach from a debugger */
105 int PostAuthDelay = 0;
114 /* max_stack_depth converted to bytes for speed of checking */
115 static long max_stack_depth_bytes = 100 * 1024L;
118 * Stack base pointer -- initialized by PostgresMain. This is not static
119 * so that PL/Java can modify it.
121 char *stack_base_ptr = NULL;
124 * On IA64 we also have to remember the register stack base.
126 #if defined(__ia64__) || defined(__ia64)
127 char *register_stack_base_ptr = NULL;
131 * Flag to mark SIGHUP. Whenever the main loop comes around it
132 * will reread the configuration file. (Better than doing the
133 * reading in the signal handler, ey?)
135 static volatile sig_atomic_t got_SIGHUP = false;
138 * Flag to keep track of whether we have started a transaction.
139 * For extended query protocol this has to be remembered across messages.
141 static bool xact_started = false;
144 * Flag to indicate that we are doing the outer loop's read-from-client,
145 * as opposed to any random read from client that might happen within
146 * commands like COPY FROM STDIN.
148 static bool DoingCommandRead = false;
151 * Flags to implement skip-till-Sync-after-error behavior for messages of
152 * the extended query protocol.
154 static bool doing_extended_query_message = false;
155 static bool ignore_till_sync = false;
158 * If an unnamed prepared statement exists, it's stored here.
159 * We keep it separate from the hashtable kept by commands/prepare.c
160 * in order to reduce overhead for short-lived queries.
162 static CachedPlanSource *unnamed_stmt_psrc = NULL;
164 /* workspace for building a new unnamed statement in */
165 static MemoryContext unnamed_stmt_context = NULL;
168 /* assorted command-line switches */
169 static const char *userDoption = NULL; /* -D switch */
171 static bool EchoQuery = false; /* -E switch */
174 * people who want to use EOF should #define DONTUSENEWLINE in
177 #ifndef TCOP_DONTUSENEWLINE
178 static int UseNewLine = 1; /* Use newlines query delimiters (the default) */
180 static int UseNewLine = 0; /* Use EOF as query delimiters */
181 #endif /* TCOP_DONTUSENEWLINE */
183 /* whether or not, and why, we were cancelled by conflict with recovery */
184 static bool RecoveryConflictPending = false;
185 static bool RecoveryConflictRetryable = true;
186 static ProcSignalReason RecoveryConflictReason;
188 /* ----------------------------------------------------------------
189 * decls for routines only used in this file
190 * ----------------------------------------------------------------
192 static int InteractiveBackend(StringInfo inBuf);
193 static int interactive_getc(void);
194 static int SocketBackend(StringInfo inBuf);
195 static int ReadCommand(StringInfo inBuf);
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 */
349 (errcode(ERRCODE_PROTOCOL_VIOLATION),
350 errmsg("unexpected EOF on client connection")));
355 * Validate message type code before trying to read body; if we have lost
356 * sync, better to say "command unknown" than to run out of memory because
357 * we used garbage as a length word.
359 * This also gives us a place to set the doing_extended_query_message flag
360 * as soon as possible.
364 case 'Q': /* simple query */
365 doing_extended_query_message = false;
366 if (PG_PROTOCOL_MAJOR(FrontendProtocol) < 3)
368 /* old style without length word; convert */
369 if (pq_getstring(inBuf))
372 (errcode(ERRCODE_PROTOCOL_VIOLATION),
373 errmsg("unexpected EOF on client connection")));
379 case 'F': /* fastpath function call */
380 /* we let fastpath.c cope with old-style input of this */
381 doing_extended_query_message = false;
384 case 'X': /* terminate */
385 doing_extended_query_message = false;
386 ignore_till_sync = false;
390 case 'C': /* close */
391 case 'D': /* describe */
392 case 'E': /* execute */
393 case 'H': /* flush */
394 case 'P': /* parse */
395 doing_extended_query_message = true;
396 /* these are only legal in protocol 3 */
397 if (PG_PROTOCOL_MAJOR(FrontendProtocol) < 3)
399 (errcode(ERRCODE_PROTOCOL_VIOLATION),
400 errmsg("invalid frontend message type %d", qtype)));
404 /* stop any active skip-till-Sync */
405 ignore_till_sync = false;
406 /* mark not-extended, so that a new error doesn't begin skip */
407 doing_extended_query_message = false;
408 /* only legal in protocol 3 */
409 if (PG_PROTOCOL_MAJOR(FrontendProtocol) < 3)
411 (errcode(ERRCODE_PROTOCOL_VIOLATION),
412 errmsg("invalid frontend message type %d", qtype)));
415 case 'd': /* copy data */
416 case 'c': /* copy done */
417 case 'f': /* copy fail */
418 doing_extended_query_message = false;
419 /* these are only legal in protocol 3 */
420 if (PG_PROTOCOL_MAJOR(FrontendProtocol) < 3)
422 (errcode(ERRCODE_PROTOCOL_VIOLATION),
423 errmsg("invalid frontend message type %d", qtype)));
429 * Otherwise we got garbage from the frontend. We treat this as
430 * fatal because we have probably lost message boundary sync, and
431 * there's no good way to recover.
434 (errcode(ERRCODE_PROTOCOL_VIOLATION),
435 errmsg("invalid frontend message type %d", qtype)));
440 * In protocol version 3, all frontend messages have a length word next
441 * after the type code; we can read the message contents independently of
444 if (PG_PROTOCOL_MAJOR(FrontendProtocol) >= 3)
446 if (pq_getmessage(inBuf, 0))
447 return EOF; /* suitable message already logged */
454 * ReadCommand reads a command from either the frontend or
455 * standard input, places it in inBuf, and returns the
456 * message type code (first byte of the message).
457 * EOF is returned if end of file.
461 ReadCommand(StringInfo inBuf)
465 if (whereToSendOutput == DestRemote)
466 result = SocketBackend(inBuf);
468 result = InteractiveBackend(inBuf);
473 * prepare_for_client_read -- set up to possibly block on client input
475 * This must be called immediately before any low-level read from the
476 * client connection. It is necessary to do it at a sufficiently low level
477 * that there won't be any other operations except the read kernel call
478 * itself between this call and the subsequent client_read_ended() call.
479 * In particular there mustn't be use of malloc() or other potentially
480 * non-reentrant libc functions. This restriction makes it safe for us
481 * to allow interrupt service routines to execute nontrivial code while
482 * we are waiting for input.
485 prepare_for_client_read(void)
487 if (DoingCommandRead)
489 /* Enable immediate processing of asynchronous signals */
490 EnableNotifyInterrupt();
491 EnableCatchupInterrupt();
493 /* Allow cancel/die interrupts to be processed while waiting */
494 ImmediateInterruptOK = true;
496 /* And don't forget to detect one that already arrived */
497 CHECK_FOR_INTERRUPTS();
502 * client_read_ended -- get out of the client-input state
505 client_read_ended(void)
507 if (DoingCommandRead)
509 ImmediateInterruptOK = false;
511 DisableNotifyInterrupt();
512 DisableCatchupInterrupt();
518 * Parse a query string and pass it through the rewriter.
520 * A list of Query nodes is returned, since the string might contain
521 * multiple queries and/or the rewriter might expand one query to several.
523 * NOTE: this routine is no longer used for processing interactive queries,
524 * but it is still needed for parsing of SQL function bodies.
527 pg_parse_and_rewrite(const char *query_string, /* string to execute */
528 Oid *paramTypes, /* parameter types */
529 int numParams) /* number of parameters */
531 List *raw_parsetree_list;
532 List *querytree_list;
536 * (1) parse the request string into a list of raw parse trees.
538 raw_parsetree_list = pg_parse_query(query_string);
541 * (2) Do parse analysis and rule rewrite.
543 querytree_list = NIL;
544 foreach(list_item, raw_parsetree_list)
546 Node *parsetree = (Node *) lfirst(list_item);
548 querytree_list = list_concat(querytree_list,
549 pg_analyze_and_rewrite(parsetree,
555 return querytree_list;
559 * Do raw parsing (only).
561 * A list of parsetrees is returned, since there might be multiple
562 * commands in the given string.
564 * NOTE: for interactive queries, it is important to keep this routine
565 * separate from the analysis & rewrite stages. Analysis and rewriting
566 * cannot be done in an aborted transaction, since they require access to
567 * database tables. So, we rely on the raw parser to determine whether
568 * we've seen a COMMIT or ABORT command; when we are in abort state, other
569 * commands are not processed any further than the raw parse stage.
572 pg_parse_query(const char *query_string)
574 List *raw_parsetree_list;
576 TRACE_POSTGRESQL_QUERY_PARSE_START(query_string);
578 if (log_parser_stats)
581 raw_parsetree_list = raw_parser(query_string);
583 if (log_parser_stats)
584 ShowUsage("PARSER STATISTICS");
586 #ifdef COPY_PARSE_PLAN_TREES
587 /* Optional debugging check: pass raw parsetrees through copyObject() */
589 List *new_list = (List *) copyObject(raw_parsetree_list);
591 /* This checks both copyObject() and the equal() routines... */
592 if (!equal(new_list, raw_parsetree_list))
593 elog(WARNING, "copyObject() failed to produce an equal raw parse tree");
595 raw_parsetree_list = new_list;
599 TRACE_POSTGRESQL_QUERY_PARSE_DONE(query_string);
601 return raw_parsetree_list;
605 * Given a raw parsetree (gram.y output), and optionally information about
606 * types of parameter symbols ($n), perform parse analysis and rule rewriting.
608 * A list of Query nodes is returned, since either the analyzer or the
609 * rewriter might expand one query to several.
611 * NOTE: for reasons mentioned above, this must be separate from raw parsing.
614 pg_analyze_and_rewrite(Node *parsetree, const char *query_string,
615 Oid *paramTypes, int numParams)
618 List *querytree_list;
620 TRACE_POSTGRESQL_QUERY_REWRITE_START(query_string);
623 * (1) Perform parse analysis.
625 if (log_parser_stats)
628 query = parse_analyze(parsetree, query_string, paramTypes, numParams);
630 if (log_parser_stats)
631 ShowUsage("PARSE ANALYSIS STATISTICS");
634 * (2) Rewrite the queries, as necessary
636 querytree_list = pg_rewrite_query(query);
638 TRACE_POSTGRESQL_QUERY_REWRITE_DONE(query_string);
640 return querytree_list;
644 * Do parse analysis and rewriting. This is the same as pg_analyze_and_rewrite
645 * except that external-parameter resolution is determined by parser callback
646 * hooks instead of a fixed list of parameter datatypes.
649 pg_analyze_and_rewrite_params(Node *parsetree,
650 const char *query_string,
651 ParserSetupHook parserSetup,
652 void *parserSetupArg)
656 List *querytree_list;
658 Assert(query_string != NULL); /* required as of 8.4 */
660 TRACE_POSTGRESQL_QUERY_REWRITE_START(query_string);
663 * (1) Perform parse analysis.
665 if (log_parser_stats)
668 pstate = make_parsestate(NULL);
669 pstate->p_sourcetext = query_string;
670 (*parserSetup) (pstate, parserSetupArg);
672 query = transformStmt(pstate, parsetree);
674 free_parsestate(pstate);
676 if (log_parser_stats)
677 ShowUsage("PARSE ANALYSIS STATISTICS");
680 * (2) Rewrite the queries, as necessary
682 querytree_list = pg_rewrite_query(query);
684 TRACE_POSTGRESQL_QUERY_REWRITE_DONE(query_string);
686 return querytree_list;
690 * Perform rewriting of a query produced by parse analysis.
692 * Note: query must just have come from the parser, because we do not do
693 * AcquireRewriteLocks() on it.
696 pg_rewrite_query(Query *query)
698 List *querytree_list;
700 if (Debug_print_parse)
701 elog_node_display(LOG, "parse tree", query,
704 if (log_parser_stats)
707 if (query->commandType == CMD_UTILITY)
709 /* don't rewrite utilities, just dump 'em into result list */
710 querytree_list = list_make1(query);
714 /* rewrite regular queries */
715 querytree_list = QueryRewrite(query);
718 if (log_parser_stats)
719 ShowUsage("REWRITER STATISTICS");
721 #ifdef COPY_PARSE_PLAN_TREES
722 /* Optional debugging check: pass querytree output through copyObject() */
726 new_list = (List *) copyObject(querytree_list);
727 /* This checks both copyObject() and the equal() routines... */
728 if (!equal(new_list, querytree_list))
729 elog(WARNING, "copyObject() failed to produce equal parse tree");
731 querytree_list = new_list;
735 if (Debug_print_rewritten)
736 elog_node_display(LOG, "rewritten parse tree", querytree_list,
739 return querytree_list;
744 * Generate a plan for a single already-rewritten query.
745 * This is a thin wrapper around planner() and takes the same parameters.
748 pg_plan_query(Query *querytree, int cursorOptions, ParamListInfo boundParams)
752 /* Utility commands have no plans. */
753 if (querytree->commandType == CMD_UTILITY)
756 /* Planner must have a snapshot in case it calls user-defined functions. */
757 Assert(ActiveSnapshotSet());
759 TRACE_POSTGRESQL_QUERY_PLAN_START();
761 if (log_planner_stats)
764 /* call the optimizer */
765 plan = planner(querytree, cursorOptions, boundParams);
767 if (log_planner_stats)
768 ShowUsage("PLANNER STATISTICS");
770 #ifdef COPY_PARSE_PLAN_TREES
771 /* Optional debugging check: pass plan output through copyObject() */
773 PlannedStmt *new_plan = (PlannedStmt *) copyObject(plan);
776 * equal() currently does not have routines to compare Plan nodes, so
777 * don't try to test equality here. Perhaps fix someday?
780 /* This checks both copyObject() and the equal() routines... */
781 if (!equal(new_plan, plan))
782 elog(WARNING, "copyObject() failed to produce an equal plan tree");
790 * Print plan if debugging.
792 if (Debug_print_plan)
793 elog_node_display(LOG, "plan", plan, Debug_pretty_print);
795 TRACE_POSTGRESQL_QUERY_PLAN_DONE();
801 * Generate plans for a list of already-rewritten queries.
803 * Normal optimizable statements generate PlannedStmt entries in the result
804 * list. Utility statements are simply represented by their statement nodes.
807 pg_plan_queries(List *querytrees, int cursorOptions, ParamListInfo boundParams)
809 List *stmt_list = NIL;
810 ListCell *query_list;
812 foreach(query_list, querytrees)
814 Query *query = (Query *) lfirst(query_list);
817 if (query->commandType == CMD_UTILITY)
819 /* Utility commands have no plans. */
820 stmt = query->utilityStmt;
824 stmt = (Node *) pg_plan_query(query, cursorOptions, boundParams);
827 stmt_list = lappend(stmt_list, stmt);
837 * Execute a "simple Query" protocol message.
840 exec_simple_query(const char *query_string)
842 CommandDest dest = whereToSendOutput;
843 MemoryContext oldcontext;
844 List *parsetree_list;
845 ListCell *parsetree_item;
846 bool save_log_statement_stats = log_statement_stats;
847 bool was_logged = false;
853 * Report query to various monitoring facilities.
855 debug_query_string = query_string;
857 pgstat_report_activity(query_string);
859 TRACE_POSTGRESQL_QUERY_START(query_string);
862 * We use save_log_statement_stats so ShowUsage doesn't report incorrect
863 * results because ResetUsage wasn't called.
865 if (save_log_statement_stats)
869 * Start up a transaction command. All queries generated by the
870 * query_string will be in this same command block, *unless* we find a
871 * BEGIN/COMMIT/ABORT statement; we have to force a new xact command after
872 * one of those, else bad things will happen in xact.c. (Note that this
873 * will normally change current memory context.)
875 start_xact_command();
878 * Zap any pre-existing unnamed statement. (While not strictly necessary,
879 * it seems best to define simple-Query mode as if it used the unnamed
880 * statement and portal; this ensures we recover any storage used by prior
881 * unnamed operations.)
886 * Switch to appropriate context for constructing parsetrees.
888 oldcontext = MemoryContextSwitchTo(MessageContext);
891 * Do basic parsing of the query or queries (this should be safe even if
892 * we are in aborted transaction state!)
894 parsetree_list = pg_parse_query(query_string);
896 /* Log immediately if dictated by log_statement */
897 if (check_log_statement(parsetree_list))
900 (errmsg("statement: %s", query_string),
902 errdetail_execute(parsetree_list)));
907 * Switch back to transaction context to enter the loop.
909 MemoryContextSwitchTo(oldcontext);
912 * We'll tell PortalRun it's a top-level command iff there's exactly one
913 * raw parsetree. If more than one, it's effectively a transaction block
914 * and we want PreventTransactionChain to reject unsafe commands. (Note:
915 * we're assuming that query rewrite cannot add commands that are
916 * significant to PreventTransactionChain.)
918 isTopLevel = (list_length(parsetree_list) == 1);
921 * Run through the raw parsetree(s) and process each one.
923 foreach(parsetree_item, parsetree_list)
925 Node *parsetree = (Node *) lfirst(parsetree_item);
926 bool snapshot_set = false;
927 const char *commandTag;
928 char completionTag[COMPLETION_TAG_BUFSIZE];
929 List *querytree_list,
932 DestReceiver *receiver;
936 * Get the command name for use in status display (it also becomes the
937 * default completion tag, down inside PortalRun). Set ps_status and
938 * do any special start-of-SQL-command processing needed by the
941 commandTag = CreateCommandTag(parsetree);
943 set_ps_display(commandTag, false);
945 BeginCommand(commandTag, dest);
948 * If we are in an aborted transaction, reject all commands except
949 * COMMIT/ABORT. It is important that this test occur before we try
950 * to do parse analysis, rewrite, or planning, since all those phases
951 * try to do database accesses, which may fail in abort state. (It
952 * might be safe to allow some additional utility commands in this
953 * state, but not many...)
955 if (IsAbortedTransactionBlockState() &&
956 !IsTransactionExitStmt(parsetree))
958 (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
959 errmsg("current transaction is aborted, "
960 "commands ignored until end of transaction block"),
963 /* Make sure we are in a transaction command */
964 start_xact_command();
966 /* If we got a cancel signal in parsing or prior command, quit */
967 CHECK_FOR_INTERRUPTS();
970 * Set up a snapshot if parse analysis/planning will need one.
972 if (analyze_requires_snapshot(parsetree))
974 PushActiveSnapshot(GetTransactionSnapshot());
979 * OK to analyze, rewrite, and plan this query.
981 * Switch to appropriate context for constructing querytrees (again,
982 * these must outlive the execution context).
984 oldcontext = MemoryContextSwitchTo(MessageContext);
986 querytree_list = pg_analyze_and_rewrite(parsetree, query_string,
989 plantree_list = pg_plan_queries(querytree_list, 0, NULL);
991 /* Done with the snapshot used for parsing/planning */
995 /* If we got a cancel signal in analysis or planning, quit */
996 CHECK_FOR_INTERRUPTS();
999 * Create unnamed portal to run the query or queries in. If there
1000 * already is one, silently drop it.
1002 portal = CreatePortal("", true, true);
1003 /* Don't display the portal in pg_cursors */
1004 portal->visible = false;
1007 * We don't have to copy anything into the portal, because everything
1008 * we are passing here is in MessageContext, which will outlive the
1011 PortalDefineQuery(portal,
1019 * Start the portal. No parameters here.
1021 PortalStart(portal, NULL, InvalidSnapshot);
1024 * Select the appropriate output format: text unless we are doing a
1025 * FETCH from a binary cursor. (Pretty grotty to have to do this here
1026 * --- but it avoids grottiness in other places. Ah, the joys of
1027 * backward compatibility...)
1029 format = 0; /* TEXT is default */
1030 if (IsA(parsetree, FetchStmt))
1032 FetchStmt *stmt = (FetchStmt *) parsetree;
1036 Portal fportal = GetPortalByName(stmt->portalname);
1038 if (PortalIsValid(fportal) &&
1039 (fportal->cursorOptions & CURSOR_OPT_BINARY))
1040 format = 1; /* BINARY */
1043 PortalSetResultFormat(portal, 1, &format);
1046 * Now we can create the destination receiver object.
1048 receiver = CreateDestReceiver(dest);
1049 if (dest == DestRemote)
1050 SetRemoteDestReceiverParams(receiver, portal);
1053 * Switch back to transaction context for execution.
1055 MemoryContextSwitchTo(oldcontext);
1058 * Run the portal to completion, and then drop it (and the receiver).
1060 (void) PortalRun(portal,
1067 (*receiver->rDestroy) (receiver);
1069 PortalDrop(portal, false);
1071 if (IsA(parsetree, TransactionStmt))
1074 * If this was a transaction control statement, commit it. We will
1075 * start a new xact command for the next command (if any).
1077 finish_xact_command();
1079 else if (lnext(parsetree_item) == NULL)
1082 * If this is the last parsetree of the query string, close down
1083 * transaction statement before reporting command-complete. This
1084 * is so that any end-of-transaction errors are reported before
1085 * the command-complete message is issued, to avoid confusing
1086 * clients who will expect either a command-complete message or an
1087 * error, not one and then the other. But for compatibility with
1088 * historical Postgres behavior, we do not force a transaction
1089 * boundary between queries appearing in a single query string.
1091 finish_xact_command();
1096 * We need a CommandCounterIncrement after every query, except
1097 * those that start or end a transaction block.
1099 CommandCounterIncrement();
1103 * Tell client that we're done with this query. Note we emit exactly
1104 * one EndCommand report for each raw parsetree, thus one for each SQL
1105 * command the client sent, regardless of rewriting. (But a command
1106 * aborted by error will not send an EndCommand report at all.)
1108 EndCommand(completionTag, dest);
1109 } /* end loop over parsetrees */
1112 * Close down transaction statement, if one is open.
1114 finish_xact_command();
1117 * If there were no parsetrees, return EmptyQueryResponse message.
1119 if (!parsetree_list)
1123 * Emit duration logging if appropriate.
1125 switch (check_log_duration(msec_str, was_logged))
1129 (errmsg("duration: %s ms", msec_str),
1130 errhidestmt(true)));
1134 (errmsg("duration: %s ms statement: %s",
1135 msec_str, query_string),
1137 errdetail_execute(parsetree_list)));
1141 if (save_log_statement_stats)
1142 ShowUsage("QUERY STATISTICS");
1144 TRACE_POSTGRESQL_QUERY_DONE(query_string);
1146 debug_query_string = NULL;
1150 * exec_parse_message
1152 * Execute a "Parse" protocol message.
1155 exec_parse_message(const char *query_string, /* string to execute */
1156 const char *stmt_name, /* name for prepared stmt */
1157 Oid *paramTypes, /* parameter types */
1158 int numParams) /* number of parameters */
1160 MemoryContext oldcontext;
1161 List *parsetree_list;
1162 Node *raw_parse_tree;
1163 const char *commandTag;
1164 List *querytree_list,
1168 bool save_log_statement_stats = log_statement_stats;
1172 * Report query to various monitoring facilities.
1174 debug_query_string = query_string;
1176 pgstat_report_activity(query_string);
1178 set_ps_display("PARSE", false);
1180 if (save_log_statement_stats)
1184 (errmsg("parse %s: %s",
1185 *stmt_name ? stmt_name : "<unnamed>",
1189 * Start up a transaction command so we can run parse analysis etc. (Note
1190 * that this will normally change current memory context.) Nothing happens
1191 * if we are already in one.
1193 start_xact_command();
1196 * Switch to appropriate context for constructing parsetrees.
1198 * We have two strategies depending on whether the prepared statement is
1199 * named or not. For a named prepared statement, we do parsing in
1200 * MessageContext and copy the finished trees into the prepared
1201 * statement's plancache entry; then the reset of MessageContext releases
1202 * temporary space used by parsing and planning. For an unnamed prepared
1203 * statement, we assume the statement isn't going to hang around long, so
1204 * getting rid of temp space quickly is probably not worth the costs of
1205 * copying parse/plan trees. So in this case, we create the plancache
1206 * entry's context here, and do all the parsing work therein.
1208 is_named = (stmt_name[0] != '\0');
1211 /* Named prepared statement --- parse in MessageContext */
1212 oldcontext = MemoryContextSwitchTo(MessageContext);
1216 /* Unnamed prepared statement --- release any prior unnamed stmt */
1217 drop_unnamed_stmt();
1218 /* Create context for parsing/planning */
1219 unnamed_stmt_context =
1220 AllocSetContextCreate(CacheMemoryContext,
1221 "unnamed prepared statement",
1222 ALLOCSET_DEFAULT_MINSIZE,
1223 ALLOCSET_DEFAULT_INITSIZE,
1224 ALLOCSET_DEFAULT_MAXSIZE);
1225 oldcontext = MemoryContextSwitchTo(unnamed_stmt_context);
1229 * Do basic parsing of the query or queries (this should be safe even if
1230 * we are in aborted transaction state!)
1232 parsetree_list = pg_parse_query(query_string);
1235 * We only allow a single user statement in a prepared statement. This is
1236 * mainly to keep the protocol simple --- otherwise we'd need to worry
1237 * about multiple result tupdescs and things like that.
1239 if (list_length(parsetree_list) > 1)
1241 (errcode(ERRCODE_SYNTAX_ERROR),
1242 errmsg("cannot insert multiple commands into a prepared statement")));
1244 if (parsetree_list != NIL)
1247 bool snapshot_set = false;
1250 raw_parse_tree = (Node *) linitial(parsetree_list);
1253 * Get the command name for possible use in status display.
1255 commandTag = CreateCommandTag(raw_parse_tree);
1258 * If we are in an aborted transaction, reject all commands except
1259 * COMMIT/ROLLBACK. It is important that this test occur before we
1260 * try to do parse analysis, rewrite, or planning, since all those
1261 * phases try to do database accesses, which may fail in abort state.
1262 * (It might be safe to allow some additional utility commands in this
1263 * state, but not many...)
1265 if (IsAbortedTransactionBlockState() &&
1266 !IsTransactionExitStmt(raw_parse_tree))
1268 (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
1269 errmsg("current transaction is aborted, "
1270 "commands ignored until end of transaction block"),
1271 errdetail_abort()));
1274 * Set up a snapshot if parse analysis/planning will need one.
1276 if (analyze_requires_snapshot(raw_parse_tree))
1278 PushActiveSnapshot(GetTransactionSnapshot());
1279 snapshot_set = true;
1283 * OK to analyze, rewrite, and plan this query. Note that the
1284 * originally specified parameter set is not required to be complete,
1285 * so we have to use parse_analyze_varparams().
1287 * XXX must use copyObject here since parse analysis scribbles on its
1288 * input, and we need the unmodified raw parse tree for possible
1291 if (log_parser_stats)
1294 query = parse_analyze_varparams(copyObject(raw_parse_tree),
1300 * Check all parameter types got determined.
1302 for (i = 0; i < numParams; i++)
1304 Oid ptype = paramTypes[i];
1306 if (ptype == InvalidOid || ptype == UNKNOWNOID)
1308 (errcode(ERRCODE_INDETERMINATE_DATATYPE),
1309 errmsg("could not determine data type of parameter $%d",
1313 if (log_parser_stats)
1314 ShowUsage("PARSE ANALYSIS STATISTICS");
1316 querytree_list = pg_rewrite_query(query);
1319 * If this is the unnamed statement and it has parameters, defer query
1320 * planning until Bind. Otherwise do it now.
1322 if (!is_named && numParams > 0)
1324 stmt_list = querytree_list;
1325 fully_planned = false;
1329 stmt_list = pg_plan_queries(querytree_list, 0, NULL);
1330 fully_planned = true;
1333 /* Done with the snapshot used for parsing/planning */
1335 PopActiveSnapshot();
1339 /* Empty input string. This is legal. */
1340 raw_parse_tree = NULL;
1343 fully_planned = true;
1346 /* If we got a cancel signal in analysis or planning, quit */
1347 CHECK_FOR_INTERRUPTS();
1350 * Store the query as a prepared statement. See above comments.
1354 StorePreparedStatement(stmt_name,
1360 0, /* default cursor options */
1367 * paramTypes and query_string need to be copied into
1368 * unnamed_stmt_context. The rest is there already
1374 newParamTypes = (Oid *) palloc(numParams * sizeof(Oid));
1375 memcpy(newParamTypes, paramTypes, numParams * sizeof(Oid));
1378 newParamTypes = NULL;
1380 unnamed_stmt_psrc = FastCreateCachedPlan(raw_parse_tree,
1381 pstrdup(query_string),
1385 0, /* cursor options */
1389 unnamed_stmt_context);
1390 /* context now belongs to the plancache entry */
1391 unnamed_stmt_context = NULL;
1394 MemoryContextSwitchTo(oldcontext);
1397 * We do NOT close the open transaction command here; that only happens
1398 * when the client sends Sync. Instead, do CommandCounterIncrement just
1399 * in case something happened during parse/plan.
1401 CommandCounterIncrement();
1404 * Send ParseComplete.
1406 if (whereToSendOutput == DestRemote)
1407 pq_putemptymessage('1');
1410 * Emit duration logging if appropriate.
1412 switch (check_log_duration(msec_str, false))
1416 (errmsg("duration: %s ms", msec_str),
1417 errhidestmt(true)));
1421 (errmsg("duration: %s ms parse %s: %s",
1423 *stmt_name ? stmt_name : "<unnamed>",
1425 errhidestmt(true)));
1429 if (save_log_statement_stats)
1430 ShowUsage("PARSE MESSAGE STATISTICS");
1432 debug_query_string = NULL;
1438 * Process a "Bind" message to create a portal from a prepared statement
1441 exec_bind_message(StringInfo input_message)
1443 const char *portal_name;
1444 const char *stmt_name;
1446 int16 *pformats = NULL;
1449 int16 *rformats = NULL;
1450 CachedPlanSource *psrc;
1454 char *saved_stmt_name;
1455 ParamListInfo params;
1457 MemoryContext oldContext;
1458 bool save_log_statement_stats = log_statement_stats;
1459 bool snapshot_set = false;
1462 /* Get the fixed part of the message */
1463 portal_name = pq_getmsgstring(input_message);
1464 stmt_name = pq_getmsgstring(input_message);
1467 (errmsg("bind %s to %s",
1468 *portal_name ? portal_name : "<unnamed>",
1469 *stmt_name ? stmt_name : "<unnamed>")));
1471 /* Find prepared statement */
1472 if (stmt_name[0] != '\0')
1474 PreparedStatement *pstmt;
1476 pstmt = FetchPreparedStatement(stmt_name, true);
1477 psrc = pstmt->plansource;
1481 /* Unnamed statements are re-prepared for every bind */
1482 psrc = unnamed_stmt_psrc;
1485 (errcode(ERRCODE_UNDEFINED_PSTATEMENT),
1486 errmsg("unnamed prepared statement does not exist")));
1490 * Report query to various monitoring facilities.
1492 debug_query_string = psrc->query_string;
1494 pgstat_report_activity(psrc->query_string);
1496 set_ps_display("BIND", false);
1498 if (save_log_statement_stats)
1502 * Start up a transaction command so we can call functions etc. (Note that
1503 * this will normally change current memory context.) Nothing happens if
1504 * we are already in one.
1506 start_xact_command();
1508 /* Switch back to message context */
1509 MemoryContextSwitchTo(MessageContext);
1511 /* Get the parameter format codes */
1512 numPFormats = pq_getmsgint(input_message, 2);
1513 if (numPFormats > 0)
1517 pformats = (int16 *) palloc(numPFormats * sizeof(int16));
1518 for (i = 0; i < numPFormats; i++)
1519 pformats[i] = pq_getmsgint(input_message, 2);
1522 /* Get the parameter value count */
1523 numParams = pq_getmsgint(input_message, 2);
1525 if (numPFormats > 1 && numPFormats != numParams)
1527 (errcode(ERRCODE_PROTOCOL_VIOLATION),
1528 errmsg("bind message has %d parameter formats but %d parameters",
1529 numPFormats, numParams)));
1531 if (numParams != psrc->num_params)
1533 (errcode(ERRCODE_PROTOCOL_VIOLATION),
1534 errmsg("bind message supplies %d parameters, but prepared statement \"%s\" requires %d",
1535 numParams, stmt_name, psrc->num_params)));
1538 * If we are in aborted transaction state, the only portals we can
1539 * actually run are those containing COMMIT or ROLLBACK commands. We
1540 * disallow binding anything else to avoid problems with infrastructure
1541 * that expects to run inside a valid transaction. We also disallow
1542 * binding any parameters, since we can't risk calling user-defined I/O
1545 if (IsAbortedTransactionBlockState() &&
1546 (!IsTransactionExitStmt(psrc->raw_parse_tree) ||
1549 (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
1550 errmsg("current transaction is aborted, "
1551 "commands ignored until end of transaction block"),
1552 errdetail_abort()));
1555 * Create the portal. Allow silent replacement of an existing portal only
1556 * if the unnamed portal is specified.
1558 if (portal_name[0] == '\0')
1559 portal = CreatePortal(portal_name, true, true);
1561 portal = CreatePortal(portal_name, false, false);
1564 * Prepare to copy stuff into the portal's memory context. We do all this
1565 * copying first, because it could possibly fail (out-of-memory) and we
1566 * don't want a failure to occur between RevalidateCachedPlan and
1567 * PortalDefineQuery; that would result in leaking our plancache refcount.
1569 oldContext = MemoryContextSwitchTo(PortalGetHeapMemory(portal));
1571 /* Copy the plan's query string into the portal */
1572 query_string = pstrdup(psrc->query_string);
1574 /* Likewise make a copy of the statement name, unless it's unnamed */
1576 saved_stmt_name = pstrdup(stmt_name);
1578 saved_stmt_name = NULL;
1581 * Set a snapshot if we have parameters to fetch (since the input
1582 * functions might need it) or the query isn't a utility command (and
1583 * hence could require redoing parse analysis and planning).
1585 if (numParams > 0 || analyze_requires_snapshot(psrc->raw_parse_tree))
1587 PushActiveSnapshot(GetTransactionSnapshot());
1588 snapshot_set = true;
1592 * Fetch parameters, if any, and store in the portal's memory context.
1598 /* sizeof(ParamListInfoData) includes the first array element */
1599 params = (ParamListInfo) palloc(sizeof(ParamListInfoData) +
1600 (numParams - 1) *sizeof(ParamExternData));
1601 /* we have static list of params, so no hooks needed */
1602 params->paramFetch = NULL;
1603 params->paramFetchArg = NULL;
1604 params->parserSetup = NULL;
1605 params->parserSetupArg = NULL;
1606 params->numParams = numParams;
1608 for (paramno = 0; paramno < numParams; paramno++)
1610 Oid ptype = psrc->param_types[paramno];
1614 StringInfoData pbuf;
1618 plength = pq_getmsgint(input_message, 4);
1619 isNull = (plength == -1);
1623 const char *pvalue = pq_getmsgbytes(input_message, plength);
1626 * Rather than copying data around, we just set up a phony
1627 * StringInfo pointing to the correct portion of the message
1628 * buffer. We assume we can scribble on the message buffer so
1629 * as to maintain the convention that StringInfos have a
1630 * trailing null. This is grotty but is a big win when
1631 * dealing with very large parameter strings.
1633 pbuf.data = (char *) pvalue;
1634 pbuf.maxlen = plength + 1;
1638 csave = pbuf.data[plength];
1639 pbuf.data[plength] = '\0';
1643 pbuf.data = NULL; /* keep compiler quiet */
1647 if (numPFormats > 1)
1648 pformat = pformats[paramno];
1649 else if (numPFormats > 0)
1650 pformat = pformats[0];
1652 pformat = 0; /* default = text */
1654 if (pformat == 0) /* text mode */
1660 getTypeInputInfo(ptype, &typinput, &typioparam);
1663 * We have to do encoding conversion before calling the
1669 pstring = pg_client_to_server(pbuf.data, plength);
1671 pval = OidInputFunctionCall(typinput, pstring, typioparam, -1);
1673 /* Free result of encoding conversion, if any */
1674 if (pstring && pstring != pbuf.data)
1677 else if (pformat == 1) /* binary mode */
1684 * Call the parameter type's binary input converter
1686 getTypeBinaryInputInfo(ptype, &typreceive, &typioparam);
1693 pval = OidReceiveFunctionCall(typreceive, bufptr, typioparam, -1);
1695 /* Trouble if it didn't eat the whole buffer */
1696 if (!isNull && pbuf.cursor != pbuf.len)
1698 (errcode(ERRCODE_INVALID_BINARY_REPRESENTATION),
1699 errmsg("incorrect binary data format in bind parameter %d",
1705 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1706 errmsg("unsupported format code: %d",
1708 pval = 0; /* keep compiler quiet */
1711 /* Restore message buffer contents */
1713 pbuf.data[plength] = csave;
1715 params->params[paramno].value = pval;
1716 params->params[paramno].isnull = isNull;
1719 * We mark the params as CONST. This has no effect if we already
1720 * did planning, but if we didn't, it licenses the planner to
1721 * substitute the parameters directly into the one-shot plan we
1722 * will generate below.
1724 params->params[paramno].pflags = PARAM_FLAG_CONST;
1725 params->params[paramno].ptype = ptype;
1731 /* Done storing stuff in portal's context */
1732 MemoryContextSwitchTo(oldContext);
1734 /* Get the result format codes */
1735 numRFormats = pq_getmsgint(input_message, 2);
1736 if (numRFormats > 0)
1740 rformats = (int16 *) palloc(numRFormats * sizeof(int16));
1741 for (i = 0; i < numRFormats; i++)
1742 rformats[i] = pq_getmsgint(input_message, 2);
1745 pq_getmsgend(input_message);
1747 if (psrc->fully_planned)
1750 * Revalidate the cached plan; this may result in replanning. Any
1751 * cruft will be generated in MessageContext. The plan refcount will
1752 * be assigned to the Portal, so it will be released at portal
1755 cplan = RevalidateCachedPlan(psrc, false);
1756 plan_list = cplan->stmt_list;
1763 * Revalidate the cached plan; this may result in redoing parse
1764 * analysis and rewriting (but not planning). Any cruft will be
1765 * generated in MessageContext. The plan refcount is assigned to
1766 * CurrentResourceOwner.
1768 cplan = RevalidateCachedPlan(psrc, true);
1771 * We didn't plan the query before, so do it now. This allows the
1772 * planner to make use of the concrete parameter values we now have.
1773 * Because we use PARAM_FLAG_CONST, the plan is good only for this set
1774 * of param values, and so we generate the plan in the portal's own
1775 * memory context where it will be thrown away after use. As in
1776 * exec_parse_message, we make no attempt to recover planner temporary
1777 * memory until the end of the operation.
1779 * XXX because the planner has a bad habit of scribbling on its input,
1780 * we have to make a copy of the parse trees. FIXME someday.
1782 oldContext = MemoryContextSwitchTo(PortalGetHeapMemory(portal));
1783 query_list = copyObject(cplan->stmt_list);
1784 plan_list = pg_plan_queries(query_list, 0, params);
1785 MemoryContextSwitchTo(oldContext);
1787 /* We no longer need the cached plan refcount ... */
1788 ReleaseCachedPlan(cplan, true);
1789 /* ... and we don't want the portal to depend on it, either */
1794 * Now we can define the portal.
1796 * DO NOT put any code that could possibly throw an error between the
1797 * above "RevalidateCachedPlan(psrc, false)" call and here.
1799 PortalDefineQuery(portal,
1806 /* Done with the snapshot used for parameter I/O and parsing/planning */
1808 PopActiveSnapshot();
1811 * And we're ready to start portal execution.
1813 PortalStart(portal, params, InvalidSnapshot);
1816 * Apply the result format requests to the portal.
1818 PortalSetResultFormat(portal, numRFormats, rformats);
1821 * Send BindComplete.
1823 if (whereToSendOutput == DestRemote)
1824 pq_putemptymessage('2');
1827 * Emit duration logging if appropriate.
1829 switch (check_log_duration(msec_str, false))
1833 (errmsg("duration: %s ms", msec_str),
1834 errhidestmt(true)));
1838 (errmsg("duration: %s ms bind %s%s%s: %s",
1840 *stmt_name ? stmt_name : "<unnamed>",
1841 *portal_name ? "/" : "",
1842 *portal_name ? portal_name : "",
1843 psrc->query_string),
1845 errdetail_params(params)));
1849 if (save_log_statement_stats)
1850 ShowUsage("BIND MESSAGE STATISTICS");
1852 debug_query_string = NULL;
1856 * exec_execute_message
1858 * Process an "Execute" message for a portal
1861 exec_execute_message(const char *portal_name, long max_rows)
1864 DestReceiver *receiver;
1867 char completionTag[COMPLETION_TAG_BUFSIZE];
1868 const char *sourceText;
1869 const char *prepStmtName;
1870 ParamListInfo portalParams;
1871 bool save_log_statement_stats = log_statement_stats;
1872 bool is_xact_command;
1873 bool execute_is_fetch;
1874 bool was_logged = false;
1877 /* Adjust destination to tell printtup.c what to do */
1878 dest = whereToSendOutput;
1879 if (dest == DestRemote)
1880 dest = DestRemoteExecute;
1882 portal = GetPortalByName(portal_name);
1883 if (!PortalIsValid(portal))
1885 (errcode(ERRCODE_UNDEFINED_CURSOR),
1886 errmsg("portal \"%s\" does not exist", portal_name)));
1889 * If the original query was a null string, just return
1890 * EmptyQueryResponse.
1892 if (portal->commandTag == NULL)
1894 Assert(portal->stmts == NIL);
1899 /* Does the portal contain a transaction command? */
1900 is_xact_command = IsTransactionStmtList(portal->stmts);
1903 * We must copy the sourceText and prepStmtName into MessageContext in
1904 * case the portal is destroyed during finish_xact_command. Can avoid the
1905 * copy if it's not an xact command, though.
1907 if (is_xact_command)
1909 sourceText = pstrdup(portal->sourceText);
1910 if (portal->prepStmtName)
1911 prepStmtName = pstrdup(portal->prepStmtName);
1913 prepStmtName = "<unnamed>";
1916 * An xact command shouldn't have any parameters, which is a good
1917 * thing because they wouldn't be around after finish_xact_command.
1919 portalParams = NULL;
1923 sourceText = portal->sourceText;
1924 if (portal->prepStmtName)
1925 prepStmtName = portal->prepStmtName;
1927 prepStmtName = "<unnamed>";
1928 portalParams = portal->portalParams;
1932 * Report query to various monitoring facilities.
1934 debug_query_string = sourceText;
1936 pgstat_report_activity(sourceText);
1938 set_ps_display(portal->commandTag, false);
1940 if (save_log_statement_stats)
1943 BeginCommand(portal->commandTag, dest);
1946 * Create dest receiver in MessageContext (we don't want it in transaction
1947 * context, because that may get deleted if portal contains VACUUM).
1949 receiver = CreateDestReceiver(dest);
1950 if (dest == DestRemoteExecute)
1951 SetRemoteDestReceiverParams(receiver, portal);
1954 * Ensure we are in a transaction command (this should normally be the
1955 * case already due to prior BIND).
1957 start_xact_command();
1960 * If we re-issue an Execute protocol request against an existing portal,
1961 * then we are only fetching more rows rather than completely re-executing
1962 * the query from the start. atStart is never reset for a v3 portal, so we
1963 * are safe to use this check.
1965 execute_is_fetch = !portal->atStart;
1967 /* Log immediately if dictated by log_statement */
1968 if (check_log_statement(portal->stmts))
1971 (errmsg("%s %s%s%s: %s",
1973 _("execute fetch from") :
1976 *portal_name ? "/" : "",
1977 *portal_name ? portal_name : "",
1980 errdetail_params(portalParams)));
1985 * If we are in aborted transaction state, the only portals we can
1986 * actually run are those containing COMMIT or ROLLBACK commands.
1988 if (IsAbortedTransactionBlockState() &&
1989 !IsTransactionExitStmtList(portal->stmts))
1991 (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
1992 errmsg("current transaction is aborted, "
1993 "commands ignored until end of transaction block"),
1994 errdetail_abort()));
1996 /* Check for cancel signal before we start execution */
1997 CHECK_FOR_INTERRUPTS();
2000 * Okay to run the portal.
2003 max_rows = FETCH_ALL;
2005 completed = PortalRun(portal,
2007 true, /* always top level */
2012 (*receiver->rDestroy) (receiver);
2016 if (is_xact_command)
2019 * If this was a transaction control statement, commit it. We
2020 * will start a new xact command for the next command (if any).
2022 finish_xact_command();
2027 * We need a CommandCounterIncrement after every query, except
2028 * those that start or end a transaction block.
2030 CommandCounterIncrement();
2033 /* Send appropriate CommandComplete to client */
2034 EndCommand(completionTag, dest);
2038 /* Portal run not complete, so send PortalSuspended */
2039 if (whereToSendOutput == DestRemote)
2040 pq_putemptymessage('s');
2044 * Emit duration logging if appropriate.
2046 switch (check_log_duration(msec_str, was_logged))
2050 (errmsg("duration: %s ms", msec_str),
2051 errhidestmt(true)));
2055 (errmsg("duration: %s ms %s %s%s%s: %s",
2058 _("execute fetch from") :
2061 *portal_name ? "/" : "",
2062 *portal_name ? portal_name : "",
2065 errdetail_params(portalParams)));
2069 if (save_log_statement_stats)
2070 ShowUsage("EXECUTE MESSAGE STATISTICS");
2072 debug_query_string = NULL;
2076 * check_log_statement
2077 * Determine whether command should be logged because of log_statement
2079 * parsetree_list can be either raw grammar output or a list of planned
2083 check_log_statement(List *stmt_list)
2085 ListCell *stmt_item;
2087 if (log_statement == LOGSTMT_NONE)
2089 if (log_statement == LOGSTMT_ALL)
2092 /* Else we have to inspect the statement(s) to see whether to log */
2093 foreach(stmt_item, stmt_list)
2095 Node *stmt = (Node *) lfirst(stmt_item);
2097 if (GetCommandLogLevel(stmt) <= log_statement)
2105 * check_log_duration
2106 * Determine whether current command's duration should be logged
2109 * 0 if no logging is needed
2110 * 1 if just the duration should be logged
2111 * 2 if duration and query details should be logged
2113 * If logging is needed, the duration in msec is formatted into msec_str[],
2114 * which must be a 32-byte buffer.
2116 * was_logged should be TRUE if caller already logged query details (this
2117 * essentially prevents 2 from being returned).
2120 check_log_duration(char *msec_str, bool was_logged)
2122 if (log_duration || log_min_duration_statement >= 0)
2129 TimestampDifference(GetCurrentStatementStartTimestamp(),
2130 GetCurrentTimestamp(),
2132 msecs = usecs / 1000;
2135 * This odd-looking test for log_min_duration_statement being exceeded
2136 * is designed to avoid integer overflow with very long durations:
2137 * don't compute secs * 1000 until we've verified it will fit in int.
2139 exceeded = (log_min_duration_statement == 0 ||
2140 (log_min_duration_statement > 0 &&
2141 (secs > log_min_duration_statement / 1000 ||
2142 secs * 1000 + msecs >= log_min_duration_statement)));
2144 if (exceeded || log_duration)
2146 snprintf(msec_str, 32, "%ld.%03d",
2147 secs * 1000 + msecs, usecs % 1000);
2148 if (exceeded && !was_logged)
2161 * Add an errdetail() line showing the query referenced by an EXECUTE, if any.
2162 * The argument is the raw parsetree list.
2165 errdetail_execute(List *raw_parsetree_list)
2167 ListCell *parsetree_item;
2169 foreach(parsetree_item, raw_parsetree_list)
2171 Node *parsetree = (Node *) lfirst(parsetree_item);
2173 if (IsA(parsetree, ExecuteStmt))
2175 ExecuteStmt *stmt = (ExecuteStmt *) parsetree;
2176 PreparedStatement *pstmt;
2178 pstmt = FetchPreparedStatement(stmt->name, false);
2181 errdetail("prepare: %s", pstmt->plansource->query_string);
2193 * Add an errdetail() line showing bind-parameter data, if available.
2196 errdetail_params(ParamListInfo params)
2198 /* We mustn't call user-defined I/O functions when in an aborted xact */
2199 if (params && params->numParams > 0 && !IsAbortedTransactionBlockState())
2201 StringInfoData param_str;
2202 MemoryContext oldcontext;
2205 /* Make sure any trash is generated in MessageContext */
2206 oldcontext = MemoryContextSwitchTo(MessageContext);
2208 initStringInfo(¶m_str);
2210 for (paramno = 0; paramno < params->numParams; paramno++)
2212 ParamExternData *prm = ¶ms->params[paramno];
2218 appendStringInfo(¶m_str, "%s$%d = ",
2219 paramno > 0 ? ", " : "",
2222 if (prm->isnull || !OidIsValid(prm->ptype))
2224 appendStringInfoString(¶m_str, "NULL");
2228 getTypeOutputInfo(prm->ptype, &typoutput, &typisvarlena);
2230 pstring = OidOutputFunctionCall(typoutput, prm->value);
2232 appendStringInfoCharMacro(¶m_str, '\'');
2233 for (p = pstring; *p; p++)
2235 if (*p == '\'') /* double single quotes */
2236 appendStringInfoCharMacro(¶m_str, *p);
2237 appendStringInfoCharMacro(¶m_str, *p);
2239 appendStringInfoCharMacro(¶m_str, '\'');
2244 errdetail("parameters: %s", param_str.data);
2246 pfree(param_str.data);
2248 MemoryContextSwitchTo(oldcontext);
2257 * Add an errdetail() line showing abort reason, if any.
2260 errdetail_abort(void)
2262 if (MyProc->recoveryConflictPending)
2263 errdetail("abort reason: recovery conflict");
2269 * errdetail_recovery_conflict
2271 * Add an errdetail() line showing conflict source.
2274 errdetail_recovery_conflict(void)
2276 switch (RecoveryConflictReason)
2278 case PROCSIG_RECOVERY_CONFLICT_BUFFERPIN:
2279 errdetail("User was holding shared buffer pin for too long.");
2281 case PROCSIG_RECOVERY_CONFLICT_LOCK:
2282 errdetail("User was holding a relation lock for too long.");
2284 case PROCSIG_RECOVERY_CONFLICT_TABLESPACE:
2285 errdetail("User was or might have been using tablespace that must be dropped.");
2287 case PROCSIG_RECOVERY_CONFLICT_SNAPSHOT:
2288 errdetail("User query might have needed to see row versions that must be removed.");
2290 case PROCSIG_RECOVERY_CONFLICT_STARTUP_DEADLOCK:
2291 errdetail("User transaction caused buffer deadlock with recovery.");
2293 case PROCSIG_RECOVERY_CONFLICT_DATABASE:
2294 errdetail("User was connected to a database that must be dropped.");
2305 * exec_describe_statement_message
2307 * Process a "Describe" message for a prepared statement
2310 exec_describe_statement_message(const char *stmt_name)
2312 CachedPlanSource *psrc;
2317 * Start up a transaction command. (Note that this will normally change
2318 * current memory context.) Nothing happens if we are already in one.
2320 start_xact_command();
2322 /* Switch back to message context */
2323 MemoryContextSwitchTo(MessageContext);
2325 /* Find prepared statement */
2326 if (stmt_name[0] != '\0')
2328 PreparedStatement *pstmt;
2330 pstmt = FetchPreparedStatement(stmt_name, true);
2331 psrc = pstmt->plansource;
2335 /* special-case the unnamed statement */
2336 psrc = unnamed_stmt_psrc;
2339 (errcode(ERRCODE_UNDEFINED_PSTATEMENT),
2340 errmsg("unnamed prepared statement does not exist")));
2343 /* Prepared statements shouldn't have changeable result descs */
2344 Assert(psrc->fixed_result);
2347 * If we are in aborted transaction state, we can't run
2348 * SendRowDescriptionMessage(), because that needs catalog accesses. (We
2349 * can't do RevalidateCachedPlan, either, but that's a lesser problem.)
2350 * Hence, refuse to Describe statements that return data. (We shouldn't
2351 * just refuse all Describes, since that might break the ability of some
2352 * clients to issue COMMIT or ROLLBACK commands, if they use code that
2353 * blindly Describes whatever it does.) We can Describe parameters
2354 * without doing anything dangerous, so we don't restrict that.
2356 if (IsAbortedTransactionBlockState() &&
2359 (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
2360 errmsg("current transaction is aborted, "
2361 "commands ignored until end of transaction block"),
2362 errdetail_abort()));
2364 if (whereToSendOutput != DestRemote)
2365 return; /* can't actually do anything... */
2368 * First describe the parameters...
2370 pq_beginmessage(&buf, 't'); /* parameter description message type */
2371 pq_sendint(&buf, psrc->num_params, 2);
2373 for (i = 0; i < psrc->num_params; i++)
2375 Oid ptype = psrc->param_types[i];
2377 pq_sendint(&buf, (int) ptype, 4);
2379 pq_endmessage(&buf);
2382 * Next send RowDescription or NoData to describe the result...
2384 if (psrc->resultDesc)
2389 /* Make sure the plan is up to date */
2390 cplan = RevalidateCachedPlan(psrc, true);
2392 /* Get the primary statement and find out what it returns */
2393 tlist = FetchStatementTargetList(PortalListGetPrimaryStmt(cplan->stmt_list));
2395 SendRowDescriptionMessage(psrc->resultDesc, tlist, NULL);
2397 ReleaseCachedPlan(cplan, true);
2400 pq_putemptymessage('n'); /* NoData */
2405 * exec_describe_portal_message
2407 * Process a "Describe" message for a portal
2410 exec_describe_portal_message(const char *portal_name)
2415 * Start up a transaction command. (Note that this will normally change
2416 * current memory context.) Nothing happens if we are already in one.
2418 start_xact_command();
2420 /* Switch back to message context */
2421 MemoryContextSwitchTo(MessageContext);
2423 portal = GetPortalByName(portal_name);
2424 if (!PortalIsValid(portal))
2426 (errcode(ERRCODE_UNDEFINED_CURSOR),
2427 errmsg("portal \"%s\" does not exist", portal_name)));
2430 * If we are in aborted transaction state, we can't run
2431 * SendRowDescriptionMessage(), because that needs catalog accesses.
2432 * Hence, refuse to Describe portals that return data. (We shouldn't just
2433 * refuse all Describes, since that might break the ability of some
2434 * clients to issue COMMIT or ROLLBACK commands, if they use code that
2435 * blindly Describes whatever it does.)
2437 if (IsAbortedTransactionBlockState() &&
2440 (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
2441 errmsg("current transaction is aborted, "
2442 "commands ignored until end of transaction block"),
2443 errdetail_abort()));
2445 if (whereToSendOutput != DestRemote)
2446 return; /* can't actually do anything... */
2448 if (portal->tupDesc)
2449 SendRowDescriptionMessage(portal->tupDesc,
2450 FetchPortalTargetList(portal),
2453 pq_putemptymessage('n'); /* NoData */
2458 * Convenience routines for starting/committing a single command.
2461 start_xact_command(void)
2466 (errmsg_internal("StartTransactionCommand")));
2467 StartTransactionCommand();
2469 /* Set statement timeout running, if any */
2470 /* NB: this mustn't be enabled until we are within an xact */
2471 if (StatementTimeout > 0)
2472 enable_sig_alarm(StatementTimeout, true);
2474 cancel_from_timeout = false;
2476 xact_started = true;
2481 finish_xact_command(void)
2485 /* Cancel any active statement timeout before committing */
2486 disable_sig_alarm(true);
2488 /* Now commit the command */
2490 (errmsg_internal("CommitTransactionCommand")));
2492 CommitTransactionCommand();
2494 #ifdef MEMORY_CONTEXT_CHECKING
2495 /* Check all memory contexts that weren't freed during commit */
2496 /* (those that were, were checked before being deleted) */
2497 MemoryContextCheck(TopMemoryContext);
2500 #ifdef SHOW_MEMORY_STATS
2501 /* Print mem stats after each commit for leak tracking */
2502 MemoryContextStats(TopMemoryContext);
2505 xact_started = false;
2511 * Convenience routines for checking whether a statement is one of the
2512 * ones that we allow in transaction-aborted state.
2515 /* Test a bare parsetree */
2517 IsTransactionExitStmt(Node *parsetree)
2519 if (parsetree && IsA(parsetree, TransactionStmt))
2521 TransactionStmt *stmt = (TransactionStmt *) parsetree;
2523 if (stmt->kind == TRANS_STMT_COMMIT ||
2524 stmt->kind == TRANS_STMT_PREPARE ||
2525 stmt->kind == TRANS_STMT_ROLLBACK ||
2526 stmt->kind == TRANS_STMT_ROLLBACK_TO)
2532 /* Test a list that might contain Query nodes or bare parsetrees */
2534 IsTransactionExitStmtList(List *parseTrees)
2536 if (list_length(parseTrees) == 1)
2538 Node *stmt = (Node *) linitial(parseTrees);
2540 if (IsA(stmt, Query))
2542 Query *query = (Query *) stmt;
2544 if (query->commandType == CMD_UTILITY &&
2545 IsTransactionExitStmt(query->utilityStmt))
2548 else if (IsTransactionExitStmt(stmt))
2554 /* Test a list that might contain Query nodes or bare parsetrees */
2556 IsTransactionStmtList(List *parseTrees)
2558 if (list_length(parseTrees) == 1)
2560 Node *stmt = (Node *) linitial(parseTrees);
2562 if (IsA(stmt, Query))
2564 Query *query = (Query *) stmt;
2566 if (query->commandType == CMD_UTILITY &&
2567 IsA(query->utilityStmt, TransactionStmt))
2570 else if (IsA(stmt, TransactionStmt))
2576 /* Release any existing unnamed prepared statement */
2578 drop_unnamed_stmt(void)
2580 /* Release any completed unnamed statement */
2581 if (unnamed_stmt_psrc)
2582 DropCachedPlan(unnamed_stmt_psrc);
2583 unnamed_stmt_psrc = NULL;
2586 * If we failed while trying to build a prior unnamed statement, we may
2587 * have a memory context that wasn't assigned to a completed plancache
2588 * entry. If so, drop it to avoid a permanent memory leak.
2590 if (unnamed_stmt_context)
2591 MemoryContextDelete(unnamed_stmt_context);
2592 unnamed_stmt_context = NULL;
2596 /* --------------------------------
2597 * signal handler routines used in PostgresMain()
2598 * --------------------------------
2602 * quickdie() occurs when signalled SIGQUIT by the postmaster.
2604 * Some backend has bought the farm,
2605 * so we need to stop what we're doing and exit.
2608 quickdie(SIGNAL_ARGS)
2610 sigaddset(&BlockSig, SIGQUIT); /* prevent nested calls */
2611 PG_SETMASK(&BlockSig);
2614 * If we're aborting out of client auth, don't risk trying to send
2615 * anything to the client; we will likely violate the protocol, not to
2616 * mention that we may have interrupted the guts of OpenSSL or some
2617 * authentication library.
2619 if (ClientAuthInProgress && whereToSendOutput == DestRemote)
2620 whereToSendOutput = DestNone;
2623 * Ideally this should be ereport(FATAL), but then we'd not get control
2627 (errcode(ERRCODE_CRASH_SHUTDOWN),
2628 errmsg("terminating connection because of crash of another server process"),
2629 errdetail("The postmaster has commanded this server process to roll back"
2630 " the current transaction and exit, because another"
2631 " server process exited abnormally and possibly corrupted"
2633 errhint("In a moment you should be able to reconnect to the"
2634 " database and repeat your command.")));
2637 * We DO NOT want to run proc_exit() callbacks -- we're here because
2638 * shared memory may be corrupted, so we don't want to try to clean up our
2639 * transaction. Just nail the windows shut and get out of town. Now that
2640 * there's an atexit callback to prevent third-party code from breaking
2641 * things by calling exit() directly, we have to reset the callbacks
2642 * explicitly to make this work as intended.
2647 * Note we do exit(2) not exit(0). This is to force the postmaster into a
2648 * system reset cycle if some idiot DBA sends a manual SIGQUIT to a random
2649 * backend. This is necessary precisely because we don't clean up our
2650 * shared memory state. (The "dead man switch" mechanism in pmsignal.c
2651 * should ensure the postmaster sees this as a crash, too, but no harm in
2652 * being doubly sure.)
2658 * Shutdown signal from postmaster: abort transaction and exit
2659 * at soonest convenient time
2664 int save_errno = errno;
2666 /* Don't joggle the elbow of proc_exit */
2667 if (!proc_exit_inprogress)
2669 InterruptPending = true;
2670 ProcDiePending = true;
2673 * If it's safe to interrupt, and we're waiting for input or a lock,
2674 * service the interrupt immediately
2676 if (ImmediateInterruptOK && InterruptHoldoffCount == 0 &&
2677 CritSectionCount == 0)
2679 /* bump holdoff count to make ProcessInterrupts() a no-op */
2680 /* until we are done getting ready for it */
2681 InterruptHoldoffCount++;
2682 LockWaitCancel(); /* prevent CheckDeadLock from running */
2683 DisableNotifyInterrupt();
2684 DisableCatchupInterrupt();
2685 InterruptHoldoffCount--;
2686 ProcessInterrupts();
2694 * Query-cancel signal from postmaster: abort current transaction
2695 * at soonest convenient time
2698 StatementCancelHandler(SIGNAL_ARGS)
2700 int save_errno = errno;
2703 * Don't joggle the elbow of proc_exit
2705 if (!proc_exit_inprogress)
2707 InterruptPending = true;
2708 QueryCancelPending = true;
2711 * If it's safe to interrupt, and we're waiting for input or a lock,
2712 * service the interrupt immediately
2714 if (ImmediateInterruptOK && InterruptHoldoffCount == 0 &&
2715 CritSectionCount == 0)
2717 /* bump holdoff count to make ProcessInterrupts() a no-op */
2718 /* until we are done getting ready for it */
2719 InterruptHoldoffCount++;
2720 LockWaitCancel(); /* prevent CheckDeadLock from running */
2721 DisableNotifyInterrupt();
2722 DisableCatchupInterrupt();
2723 InterruptHoldoffCount--;
2724 ProcessInterrupts();
2731 /* signal handler for floating point exception */
2733 FloatExceptionHandler(SIGNAL_ARGS)
2736 (errcode(ERRCODE_FLOATING_POINT_EXCEPTION),
2737 errmsg("floating-point exception"),
2738 errdetail("An invalid floating-point operation was signaled. "
2739 "This probably means an out-of-range result or an "
2740 "invalid operation, such as division by zero.")));
2743 /* SIGHUP: set flag to re-read config file at next convenient time */
2745 SigHupHandler(SIGNAL_ARGS)
2751 * RecoveryConflictInterrupt: out-of-line portion of recovery conflict
2752 * handling following receipt of SIGUSR1. Designed to be similar to die()
2753 * and StatementCancelHandler(). Called only by a normal user backend
2754 * that begins a transaction during recovery.
2757 RecoveryConflictInterrupt(ProcSignalReason reason)
2759 int save_errno = errno;
2762 * Don't joggle the elbow of proc_exit
2764 if (!proc_exit_inprogress)
2766 RecoveryConflictReason = reason;
2769 case PROCSIG_RECOVERY_CONFLICT_STARTUP_DEADLOCK:
2772 * If we aren't waiting for a lock we can never deadlock.
2774 if (!IsWaitingForLock())
2777 /* Intentional drop through to check wait for pin */
2779 case PROCSIG_RECOVERY_CONFLICT_BUFFERPIN:
2782 * If we aren't blocking the Startup process there is nothing
2785 if (!HoldingBufferPinThatDelaysRecovery())
2788 MyProc->recoveryConflictPending = true;
2790 /* Intentional drop through to error handling */
2792 case PROCSIG_RECOVERY_CONFLICT_LOCK:
2793 case PROCSIG_RECOVERY_CONFLICT_TABLESPACE:
2794 case PROCSIG_RECOVERY_CONFLICT_SNAPSHOT:
2797 * If we aren't in a transaction any longer then ignore.
2799 if (!IsTransactionOrTransactionBlock())
2803 * If we can abort just the current subtransaction then we are
2804 * OK to throw an ERROR to resolve the conflict. Otherwise
2805 * drop through to the FATAL case.
2807 * XXX other times that we can throw just an ERROR *may* be
2808 * PROCSIG_RECOVERY_CONFLICT_LOCK if no locks are held in
2809 * parent transactions
2811 * PROCSIG_RECOVERY_CONFLICT_SNAPSHOT if no snapshots are held
2812 * by parent transactions and the transaction is not
2813 * transaction-snapshot mode
2815 * PROCSIG_RECOVERY_CONFLICT_TABLESPACE if no temp files or
2816 * cursors open in parent transactions
2818 if (!IsSubTransaction())
2821 * If we already aborted then we no longer need to cancel.
2822 * We do this here since we do not wish to ignore aborted
2823 * subtransactions, which must cause FATAL, currently.
2825 if (IsAbortedTransactionBlockState())
2828 RecoveryConflictPending = true;
2829 QueryCancelPending = true;
2830 InterruptPending = true;
2834 /* Intentional drop through to session cancel */
2836 case PROCSIG_RECOVERY_CONFLICT_DATABASE:
2837 RecoveryConflictPending = true;
2838 ProcDiePending = true;
2839 InterruptPending = true;
2843 elog(FATAL, "Unknown conflict mode");
2846 Assert(RecoveryConflictPending && (QueryCancelPending || ProcDiePending));
2849 * All conflicts apart from database cause dynamic errors where the
2850 * command or transaction can be retried at a later point with some
2851 * potential for success. No need to reset this, since non-retryable
2852 * conflict errors are currently FATAL.
2854 if (reason == PROCSIG_RECOVERY_CONFLICT_DATABASE)
2855 RecoveryConflictRetryable = false;
2858 * If it's safe to interrupt, and we're waiting for input or a lock,
2859 * service the interrupt immediately
2861 if (ImmediateInterruptOK && InterruptHoldoffCount == 0 &&
2862 CritSectionCount == 0)
2864 /* bump holdoff count to make ProcessInterrupts() a no-op */
2865 /* until we are done getting ready for it */
2866 InterruptHoldoffCount++;
2867 LockWaitCancel(); /* prevent CheckDeadLock from running */
2868 DisableNotifyInterrupt();
2869 DisableCatchupInterrupt();
2870 InterruptHoldoffCount--;
2871 ProcessInterrupts();
2879 * ProcessInterrupts: out-of-line portion of CHECK_FOR_INTERRUPTS() macro
2881 * If an interrupt condition is pending, and it's safe to service it,
2882 * then clear the flag and accept the interrupt. Called only when
2883 * InterruptPending is true.
2886 ProcessInterrupts(void)
2888 /* OK to accept interrupt now? */
2889 if (InterruptHoldoffCount != 0 || CritSectionCount != 0)
2891 InterruptPending = false;
2894 ProcDiePending = false;
2895 QueryCancelPending = false; /* ProcDie trumps QueryCancel */
2896 ImmediateInterruptOK = false; /* not idle anymore */
2897 DisableNotifyInterrupt();
2898 DisableCatchupInterrupt();
2899 /* As in quickdie, don't risk sending to client during auth */
2900 if (ClientAuthInProgress && whereToSendOutput == DestRemote)
2901 whereToSendOutput = DestNone;
2902 if (IsAutoVacuumWorkerProcess())
2904 (errcode(ERRCODE_ADMIN_SHUTDOWN),
2905 errmsg("terminating autovacuum process due to administrator command")));
2906 else if (RecoveryConflictPending && RecoveryConflictRetryable)
2908 (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
2909 errmsg("terminating connection due to conflict with recovery"),
2910 errdetail_recovery_conflict()));
2911 else if (RecoveryConflictPending)
2913 (errcode(ERRCODE_ADMIN_SHUTDOWN),
2914 errmsg("terminating connection due to conflict with recovery"),
2915 errdetail_recovery_conflict()));
2918 (errcode(ERRCODE_ADMIN_SHUTDOWN),
2919 errmsg("terminating connection due to administrator command")));
2921 if (QueryCancelPending)
2923 QueryCancelPending = false;
2924 if (ClientAuthInProgress)
2926 ImmediateInterruptOK = false; /* not idle anymore */
2927 DisableNotifyInterrupt();
2928 DisableCatchupInterrupt();
2929 /* As in quickdie, don't risk sending to client during auth */
2930 if (whereToSendOutput == DestRemote)
2931 whereToSendOutput = DestNone;
2933 (errcode(ERRCODE_QUERY_CANCELED),
2934 errmsg("canceling authentication due to timeout")));
2936 if (cancel_from_timeout)
2938 ImmediateInterruptOK = false; /* not idle anymore */
2939 DisableNotifyInterrupt();
2940 DisableCatchupInterrupt();
2942 (errcode(ERRCODE_QUERY_CANCELED),
2943 errmsg("canceling statement due to statement timeout")));
2945 if (IsAutoVacuumWorkerProcess())
2947 ImmediateInterruptOK = false; /* not idle anymore */
2948 DisableNotifyInterrupt();
2949 DisableCatchupInterrupt();
2951 (errcode(ERRCODE_QUERY_CANCELED),
2952 errmsg("canceling autovacuum task")));
2954 if (RecoveryConflictPending)
2956 ImmediateInterruptOK = false; /* not idle anymore */
2957 RecoveryConflictPending = false;
2958 DisableNotifyInterrupt();
2959 DisableCatchupInterrupt();
2960 if (DoingCommandRead)
2962 (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
2963 errmsg("terminating connection due to conflict with recovery"),
2964 errdetail_recovery_conflict(),
2965 errhint("In a moment you should be able to reconnect to the"
2966 " database and repeat your command.")));
2969 (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
2970 errmsg("canceling statement due to conflict with recovery"),
2971 errdetail_recovery_conflict()));
2975 * If we are reading a command from the client, just ignore the cancel
2976 * request --- sending an extra error message won't accomplish
2977 * anything. Otherwise, go ahead and throw the error.
2979 if (!DoingCommandRead)
2981 ImmediateInterruptOK = false; /* not idle anymore */
2982 DisableNotifyInterrupt();
2983 DisableCatchupInterrupt();
2985 (errcode(ERRCODE_QUERY_CANCELED),
2986 errmsg("canceling statement due to user request")));
2989 /* If we get here, do nothing (probably, QueryCancelPending was reset) */
2994 * IA64-specific code to fetch the AR.BSP register for stack depth checks.
2996 * We currently support gcc and icc here.
2998 #if defined(__ia64__) || defined(__ia64)
3000 #include <asm/ia64regs.h>
3002 static __inline__ char *
3007 #ifndef __INTEL_COMPILER
3008 /* the ;; is a "stop", seems to be required before fetching BSP */
3009 __asm__ __volatile__(
3014 ret = (char *) __getReg(_IA64_REG_AR_BSP);
3023 * check_stack_depth: check for excessively deep recursion
3025 * This should be called someplace in any recursive routine that might possibly
3026 * recurse deep enough to overflow the stack. Most Unixen treat stack
3027 * overflow as an unrecoverable SIGSEGV, so we want to error out ourselves
3028 * before hitting the hardware limit.
3031 check_stack_depth(void)
3037 * Compute distance from PostgresMain's local variables to my own
3039 stack_depth = (long) (stack_base_ptr - &stack_top_loc);
3042 * Take abs value, since stacks grow up on some machines, down on others
3044 if (stack_depth < 0)
3045 stack_depth = -stack_depth;
3050 * The test on stack_base_ptr prevents us from erroring out if called
3051 * during process setup or in a non-backend process. Logically it should
3052 * be done first, but putting it here avoids wasting cycles during normal
3055 if (stack_depth > max_stack_depth_bytes &&
3056 stack_base_ptr != NULL)
3059 (errcode(ERRCODE_STATEMENT_TOO_COMPLEX),
3060 errmsg("stack depth limit exceeded"),
3061 errhint("Increase the configuration parameter \"max_stack_depth\" (currently %dkB), "
3062 "after ensuring the platform's stack depth limit is adequate.",
3067 * On IA64 there is a separate "register" stack that requires its own
3068 * independent check. For this, we have to measure the change in the
3069 * "BSP" pointer from PostgresMain to here. Logic is just as above,
3070 * except that we know IA64's register stack grows up.
3072 * Note we assume that the same max_stack_depth applies to both stacks.
3074 #if defined(__ia64__) || defined(__ia64)
3075 stack_depth = (long) (ia64_get_bsp() - register_stack_base_ptr);
3077 if (stack_depth > max_stack_depth_bytes &&
3078 register_stack_base_ptr != NULL)
3081 (errcode(ERRCODE_STATEMENT_TOO_COMPLEX),
3082 errmsg("stack depth limit exceeded"),
3083 errhint("Increase the configuration parameter \"max_stack_depth\" (currently %dkB), "
3084 "after ensuring the platform's stack depth limit is adequate.",
3090 /* GUC assign hook for max_stack_depth */
3092 assign_max_stack_depth(int newval, bool doit, GucSource source)
3094 long newval_bytes = newval * 1024L;
3095 long stack_rlimit = get_stack_depth_rlimit();
3097 if (stack_rlimit > 0 && newval_bytes > stack_rlimit - STACK_DEPTH_SLOP)
3099 ereport(GUC_complaint_elevel(source),
3100 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
3101 errmsg("\"max_stack_depth\" must not exceed %ldkB",
3102 (stack_rlimit - STACK_DEPTH_SLOP) / 1024L),
3103 errhint("Increase the platform's stack depth limit via \"ulimit -s\" or local equivalent.")));
3107 max_stack_depth_bytes = newval_bytes;
3113 * set_debug_options --- apply "-d N" command line option
3115 * -d is not quite the same as setting log_min_messages because it enables
3116 * other output options.
3119 set_debug_options(int debug_flag, GucContext context, GucSource source)
3125 sprintf(debugstr, "debug%d", debug_flag);
3126 SetConfigOption("log_min_messages", debugstr, context, source);
3129 SetConfigOption("log_min_messages", "notice", context, source);
3131 if (debug_flag >= 1 && context == PGC_POSTMASTER)
3133 SetConfigOption("log_connections", "true", context, source);
3134 SetConfigOption("log_disconnections", "true", context, source);
3136 if (debug_flag >= 2)
3137 SetConfigOption("log_statement", "all", context, source);
3138 if (debug_flag >= 3)
3139 SetConfigOption("debug_print_parse", "true", context, source);
3140 if (debug_flag >= 4)
3141 SetConfigOption("debug_print_plan", "true", context, source);
3142 if (debug_flag >= 5)
3143 SetConfigOption("debug_print_rewritten", "true", context, source);
3148 set_plan_disabling_options(const char *arg, GucContext context, GucSource source)
3154 case 's': /* seqscan */
3155 tmp = "enable_seqscan";
3157 case 'i': /* indexscan */
3158 tmp = "enable_indexscan";
3160 case 'b': /* bitmapscan */
3161 tmp = "enable_bitmapscan";
3163 case 't': /* tidscan */
3164 tmp = "enable_tidscan";
3166 case 'n': /* nestloop */
3167 tmp = "enable_nestloop";
3169 case 'm': /* mergejoin */
3170 tmp = "enable_mergejoin";
3172 case 'h': /* hashjoin */
3173 tmp = "enable_hashjoin";
3178 SetConfigOption(tmp, "false", context, source);
3187 get_stats_option_name(const char *arg)
3192 if (optarg[1] == 'a') /* "parser" */
3193 return "log_parser_stats";
3194 else if (optarg[1] == 'l') /* "planner" */
3195 return "log_planner_stats";
3198 case 'e': /* "executor" */
3199 return "log_executor_stats";
3207 /* ----------------------------------------------------------------
3208 * process_postgres_switches
3209 * Parse command line arguments for PostgresMain
3211 * This is called twice, once for the "secure" options coming from the
3212 * postmaster or command line, and once for the "insecure" options coming
3213 * from the client's startup packet. The latter have the same syntax but
3214 * may be restricted in what they can do.
3216 * argv[0] is ignored in either case (it's assumed to be the program name).
3218 * ctx is PGC_POSTMASTER for secure options, PGC_BACKEND for insecure options
3219 * coming from the client, or PGC_SUSET for insecure options coming from
3220 * a superuser client.
3222 * Returns the database name extracted from the command line, if any.
3223 * ----------------------------------------------------------------
3226 process_postgres_switches(int argc, char *argv[], GucContext ctx)
3229 bool secure = (ctx == PGC_POSTMASTER);
3231 GucSource gucsource;
3236 gucsource = PGC_S_ARGV; /* switches came from command line */
3238 /* Ignore the initial --single argument, if present */
3239 if (argc > 1 && strcmp(argv[1], "--single") == 0)
3247 gucsource = PGC_S_CLIENT; /* switches came from client */
3251 * Parse command-line options. CAUTION: keep this in sync with
3252 * postmaster/postmaster.c (the option sets should not conflict) and with
3253 * the common help() function in main/main.c.
3255 while ((flag = getopt(argc, argv, "A:B:c:D:d:EeFf:h:ijk:lN:nOo:Pp:r:S:sTt:v:W:-:")) != -1)
3260 SetConfigOption("debug_assertions", optarg, ctx, gucsource);
3264 SetConfigOption("shared_buffers", optarg, ctx, gucsource);
3269 userDoption = strdup(optarg);
3273 set_debug_options(atoi(optarg), ctx, gucsource);
3281 SetConfigOption("datestyle", "euro", ctx, gucsource);
3285 SetConfigOption("fsync", "false", ctx, gucsource);
3289 if (!set_plan_disabling_options(optarg, ctx, gucsource))
3294 SetConfigOption("listen_addresses", optarg, ctx, gucsource);
3298 SetConfigOption("listen_addresses", "*", ctx, gucsource);
3306 SetConfigOption("unix_socket_directory", optarg, ctx, gucsource);
3310 SetConfigOption("ssl", "true", ctx, gucsource);
3314 SetConfigOption("max_connections", optarg, ctx, gucsource);
3318 /* ignored for consistency with postmaster */
3322 SetConfigOption("allow_system_table_mods", "true", ctx, gucsource);
3330 SetConfigOption("ignore_system_indexes", "true", ctx, gucsource);
3334 SetConfigOption("port", optarg, ctx, gucsource);
3338 /* send output (stdout and stderr) to the given file */
3340 strlcpy(OutputFileName, optarg, MAXPGPATH);
3344 SetConfigOption("work_mem", optarg, ctx, gucsource);
3348 SetConfigOption("log_statement_stats", "true", ctx, gucsource);
3352 /* ignored for consistency with postmaster */
3357 const char *tmp = get_stats_option_name(optarg);
3360 SetConfigOption(tmp, "true", ctx, gucsource);
3369 * -v is no longer used in normal operation, since
3370 * FrontendProtocol is already set before we get here. We keep
3371 * the switch only for possible use in standalone operation,
3372 * in case we ever support using normal FE/BE protocol with a
3373 * standalone backend.
3376 FrontendProtocol = (ProtocolVersion) atoi(optarg);
3380 SetConfigOption("post_auth_delay", optarg, ctx, gucsource);
3389 ParseLongOption(optarg, &name, &value);
3394 (errcode(ERRCODE_SYNTAX_ERROR),
3395 errmsg("--%s requires a value",
3399 (errcode(ERRCODE_SYNTAX_ERROR),
3400 errmsg("-c %s requires a value",
3403 SetConfigOption(name, value, ctx, gucsource);
3417 * Should be no more arguments except an optional database name, and
3418 * that's only in the secure case.
3420 if (errs || argc - optind > 1 || (argc != optind && !secure))
3422 /* spell the error message a bit differently depending on context */
3423 if (IsUnderPostmaster)
3425 (errcode(ERRCODE_SYNTAX_ERROR),
3426 errmsg("invalid command-line arguments for server process"),
3427 errhint("Try \"%s --help\" for more information.", progname)));
3430 (errcode(ERRCODE_SYNTAX_ERROR),
3431 errmsg("%s: invalid command-line arguments",
3433 errhint("Try \"%s --help\" for more information.", progname)));
3436 if (argc - optind == 1)
3437 dbname = strdup(argv[optind]);
3442 * Reset getopt(3) library so that it will work correctly in subprocesses
3443 * or when this function is called a second time with another array.
3446 #if defined(HAVE_INT_OPTRESET) || !defined(HAVE_GETOPT)
3447 optreset = 1; /* some systems need this too */
3454 /* ----------------------------------------------------------------
3456 * postgres main loop -- all backends, interactive or otherwise start here
3458 * argc/argv are the command line arguments to be used. (When being forked
3459 * by the postmaster, these are not the original argv array of the process.)
3460 * username is the (possibly authenticated) PostgreSQL user name to be used
3462 * ----------------------------------------------------------------
3465 PostgresMain(int argc, char *argv[], const char *username)
3470 StringInfoData input_message;
3471 sigjmp_buf local_sigjmp_buf;
3472 volatile bool send_ready_for_query = true;
3475 * Initialize globals (already done if under postmaster, but not if
3478 if (!IsUnderPostmaster)
3480 MyProcPid = getpid();
3482 MyStartTime = time(NULL);
3486 * Fire up essential subsystems: error and memory management
3488 * If we are running under the postmaster, this is done already.
3490 if (!IsUnderPostmaster)
3491 MemoryContextInit();
3493 SetProcessingMode(InitProcessing);
3495 /* Set up reference point for stack depth checking */
3496 stack_base_ptr = &stack_base;
3497 #if defined(__ia64__) || defined(__ia64)
3498 register_stack_base_ptr = ia64_get_bsp();
3501 /* Compute paths, if we didn't inherit them from postmaster */
3502 if (my_exec_path[0] == '\0')
3504 if (find_my_exec(argv[0], my_exec_path) < 0)
3505 elog(FATAL, "%s: could not locate my own executable path",
3509 if (pkglib_path[0] == '\0')
3510 get_pkglib_path(my_exec_path, pkglib_path);
3513 * Set default values for command-line options.
3515 if (!IsUnderPostmaster)
3516 InitializeGUCOptions();
3519 * Parse command-line options.
3521 dbname = process_postgres_switches(argc, argv, PGC_POSTMASTER);
3523 /* Must have gotten a database name, or have a default (the username) */
3529 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
3530 errmsg("%s: no database nor user name specified",
3534 /* Acquire configuration parameters, unless inherited from postmaster */
3535 if (!IsUnderPostmaster)
3537 if (!SelectConfigFiles(userDoption, progname))
3539 /* If timezone is not set, determine what the OS uses */
3540 pg_timezone_initialize();
3541 /* If timezone_abbreviations is not set, select default */
3542 pg_timezone_abbrev_initialize();
3546 * You might expect to see a setsid() call here, but it's not needed,
3547 * because if we are under a postmaster then BackendInitialize() did it.
3551 * Set up signal handlers and masks.
3553 * Note that postmaster blocked all signals before forking child process,
3554 * so there is no race condition whereby we might receive a signal before
3555 * we have set up the handler.
3557 * Also note: it's best not to use any signals that are SIG_IGNored in the
3558 * postmaster. If such a signal arrives before we are able to change the
3559 * handler to non-SIG_IGN, it'll get dropped. Instead, make a dummy
3560 * handler in the postmaster to reserve the signal. (Of course, this isn't
3561 * an issue for signals that are locally generated, such as SIGALRM and
3568 pqsignal(SIGHUP, SigHupHandler); /* set flag to read config
3570 pqsignal(SIGINT, StatementCancelHandler); /* cancel current query */
3571 pqsignal(SIGTERM, die); /* cancel current query and exit */
3574 * In a standalone backend, SIGQUIT can be generated from the keyboard
3575 * easily, while SIGTERM cannot, so we make both signals do die()
3576 * rather than quickdie().
3578 if (IsUnderPostmaster)
3579 pqsignal(SIGQUIT, quickdie); /* hard crash time */
3581 pqsignal(SIGQUIT, die); /* cancel current query and exit */
3582 pqsignal(SIGALRM, handle_sig_alarm); /* timeout conditions */
3585 * Ignore failure to write to frontend. Note: if frontend closes
3586 * connection, we will notice it and exit cleanly when control next
3587 * returns to outer loop. This seems safer than forcing exit in the
3588 * midst of output during who-knows-what operation...
3590 pqsignal(SIGPIPE, SIG_IGN);
3591 pqsignal(SIGUSR1, procsignal_sigusr1_handler);
3592 pqsignal(SIGUSR2, SIG_IGN);
3593 pqsignal(SIGFPE, FloatExceptionHandler);
3596 * Reset some signals that are accepted by postmaster but not by
3599 pqsignal(SIGCHLD, SIG_DFL); /* system() requires this on some
3605 if (IsUnderPostmaster)
3607 /* We allow SIGQUIT (quickdie) at all times */
3608 sigdelset(&BlockSig, SIGQUIT);
3611 PG_SETMASK(&BlockSig); /* block everything except SIGQUIT */
3613 if (!IsUnderPostmaster)
3616 * Validate we have been given a reasonable-looking DataDir (if under
3617 * postmaster, assume postmaster did this already).
3620 ValidatePgVersion(DataDir);
3622 /* Change into DataDir (if under postmaster, was done already) */
3626 * Create lockfile for data directory.
3628 CreateDataDirLockFile(false);
3631 /* Early initialization */
3635 * Create a per-backend PGPROC struct in shared memory, except in the
3636 * EXEC_BACKEND case where this was done in SubPostmasterMain. We must do
3637 * this before we can use LWLocks (and in the EXEC_BACKEND case we already
3638 * had to do some stuff with LWLocks).
3641 if (!IsUnderPostmaster)
3647 /* We need to allow SIGINT, etc during the initial transaction */
3648 PG_SETMASK(&UnBlockSig);
3651 * General initialization.
3653 * NOTE: if you are tempted to add code in this vicinity, consider putting
3654 * it inside InitPostgres() instead. In particular, anything that
3655 * involves database access should be there, not here.
3657 InitPostgres(dbname, InvalidOid, username, NULL);
3660 * If the PostmasterContext is still around, recycle the space; we don't
3661 * need it anymore after InitPostgres completes. Note this does not trash
3662 * *MyProcPort, because ConnCreate() allocated that space with malloc()
3663 * ... else we'd need to copy the Port data first. Also, subsidiary data
3664 * such as the username isn't lost either; see ProcessStartupPacket().
3666 if (PostmasterContext)
3668 MemoryContextDelete(PostmasterContext);
3669 PostmasterContext = NULL;
3672 SetProcessingMode(NormalProcessing);
3675 * Now all GUC states are fully set up. Report them to client if
3678 BeginReportingGUCOptions();
3681 * Also set up handler to log session end; we have to wait till now to be
3682 * sure Log_disconnections has its final value.
3684 if (IsUnderPostmaster && Log_disconnections)
3685 on_proc_exit(log_disconnections, 0);
3687 /* If this is a WAL sender process, we're done with initialization. */
3689 proc_exit(WalSenderMain());
3692 * process any libraries that should be preloaded at backend start (this
3693 * likewise can't be done until GUC settings are complete)
3695 process_local_preload_libraries();
3698 * Send this backend's cancellation info to the frontend.
3700 if (whereToSendOutput == DestRemote &&
3701 PG_PROTOCOL_MAJOR(FrontendProtocol) >= 2)
3705 pq_beginmessage(&buf, 'K');
3706 pq_sendint(&buf, (int32) MyProcPid, sizeof(int32));
3707 pq_sendint(&buf, (int32) MyCancelKey, sizeof(int32));
3708 pq_endmessage(&buf);
3709 /* Need not flush since ReadyForQuery will do it. */
3712 /* Welcome banner for standalone case */
3713 if (whereToSendOutput == DestDebug)
3714 printf("\nPostgreSQL stand-alone backend %s\n", PG_VERSION);
3717 * Create the memory context we will use in the main loop.
3719 * MessageContext is reset once per iteration of the main loop, ie, upon
3720 * completion of processing of each command message from the client.
3722 MessageContext = AllocSetContextCreate(TopMemoryContext,
3724 ALLOCSET_DEFAULT_MINSIZE,
3725 ALLOCSET_DEFAULT_INITSIZE,
3726 ALLOCSET_DEFAULT_MAXSIZE);
3729 * Remember stand-alone backend startup time
3731 if (!IsUnderPostmaster)
3732 PgStartTime = GetCurrentTimestamp();
3735 * POSTGRES main processing loop begins here
3737 * If an exception is encountered, processing resumes here so we abort the
3738 * current transaction and start a new one.
3740 * You might wonder why this isn't coded as an infinite loop around a
3741 * PG_TRY construct. The reason is that this is the bottom of the
3742 * exception stack, and so with PG_TRY there would be no exception handler
3743 * in force at all during the CATCH part. By leaving the outermost setjmp
3744 * always active, we have at least some chance of recovering from an error
3745 * during error recovery. (If we get into an infinite loop thereby, it
3746 * will soon be stopped by overflow of elog.c's internal state stack.)
3749 if (sigsetjmp(local_sigjmp_buf, 1) != 0)
3752 * NOTE: if you are tempted to add more code in this if-block,
3753 * consider the high probability that it should be in
3754 * AbortTransaction() instead. The only stuff done directly here
3755 * should be stuff that is guaranteed to apply *only* for outer-level
3756 * error recovery, such as adjusting the FE/BE protocol status.
3759 /* Since not using PG_TRY, must reset error stack by hand */
3760 error_context_stack = NULL;
3762 /* Prevent interrupts while cleaning up */
3766 * Forget any pending QueryCancel request, since we're returning to
3767 * the idle loop anyway, and cancel the statement timer if running.
3769 QueryCancelPending = false;
3770 disable_sig_alarm(true);
3771 QueryCancelPending = false; /* again in case timeout occurred */
3774 * Turn off these interrupts too. This is only needed here and not in
3775 * other exception-catching places since these interrupts are only
3776 * enabled while we wait for client input.
3778 DoingCommandRead = false;
3779 DisableNotifyInterrupt();
3780 DisableCatchupInterrupt();
3782 /* Make sure libpq is in a good state */
3785 /* Report the error to the client and/or server log */
3789 * Make sure debug_query_string gets reset before we possibly clobber
3790 * the storage it points at.
3792 debug_query_string = NULL;
3795 * Abort the current transaction in order to recover.
3797 AbortCurrentTransaction();
3800 * Now return to normal top-level context and clear ErrorContext for
3803 MemoryContextSwitchTo(TopMemoryContext);
3807 * If we were handling an extended-query-protocol message, initiate
3808 * skip till next Sync. This also causes us not to issue
3809 * ReadyForQuery (until we get Sync).
3811 if (doing_extended_query_message)
3812 ignore_till_sync = true;
3814 /* We don't have a transaction command open anymore */
3815 xact_started = false;
3817 /* Now we can allow interrupts again */
3818 RESUME_INTERRUPTS();
3821 /* We can now handle ereport(ERROR) */
3822 PG_exception_stack = &local_sigjmp_buf;
3824 if (!ignore_till_sync)
3825 send_ready_for_query = true; /* initially, or after error */
3828 * Non-error queries loop here.
3834 * At top of loop, reset extended-query-message flag, so that any
3835 * errors encountered in "idle" state don't provoke skip.
3837 doing_extended_query_message = false;
3840 * Release storage left over from prior query cycle, and create a new
3841 * query input buffer in the cleared MessageContext.
3843 MemoryContextSwitchTo(MessageContext);
3844 MemoryContextResetAndDeleteChildren(MessageContext);
3846 initStringInfo(&input_message);
3849 * (1) If we've reached idle state, tell the frontend we're ready for
3852 * Note: this includes fflush()'ing the last of the prior output.
3854 * This is also a good time to send collected statistics to the
3855 * collector, and to update the PS stats display. We avoid doing
3856 * those every time through the message loop because it'd slow down
3857 * processing of batched messages, and because we don't want to report
3858 * uncommitted updates (that confuses autovacuum). The notification
3859 * processor wants a call too, if we are not in a transaction block.
3861 if (send_ready_for_query)
3863 if (IsAbortedTransactionBlockState())
3865 set_ps_display("idle in transaction (aborted)", false);
3866 pgstat_report_activity("<IDLE> in transaction (aborted)");
3868 else if (IsTransactionOrTransactionBlock())
3870 set_ps_display("idle in transaction", false);
3871 pgstat_report_activity("<IDLE> in transaction");
3875 ProcessCompletedNotifies();
3876 pgstat_report_stat(false);
3878 set_ps_display("idle", false);
3879 pgstat_report_activity("<IDLE>");
3882 ReadyForQuery(whereToSendOutput);
3883 send_ready_for_query = false;
3887 * (2) Allow asynchronous signals to be executed immediately if they
3888 * come in while we are waiting for client input. (This must be
3889 * conditional since we don't want, say, reads on behalf of COPY FROM
3890 * STDIN doing the same thing.)
3892 DoingCommandRead = true;
3895 * (3) read a command (loop blocks here)
3897 firstchar = ReadCommand(&input_message);
3900 * (4) disable async signal conditions again.
3902 DoingCommandRead = false;
3905 * (5) check for any other interesting events that happened while we
3911 ProcessConfigFile(PGC_SIGHUP);
3915 * (6) process the command. But ignore it if we're skipping till
3918 if (ignore_till_sync && firstchar != EOF)
3923 case 'Q': /* simple query */
3925 const char *query_string;
3927 /* Set statement_timestamp() */
3928 SetCurrentStatementStartTimestamp();
3930 query_string = pq_getmsgstring(&input_message);
3931 pq_getmsgend(&input_message);
3933 exec_simple_query(query_string);
3935 send_ready_for_query = true;
3939 case 'P': /* parse */
3941 const char *stmt_name;
3942 const char *query_string;
3944 Oid *paramTypes = NULL;
3946 /* Set statement_timestamp() */
3947 SetCurrentStatementStartTimestamp();
3949 stmt_name = pq_getmsgstring(&input_message);
3950 query_string = pq_getmsgstring(&input_message);
3951 numParams = pq_getmsgint(&input_message, 2);
3956 paramTypes = (Oid *) palloc(numParams * sizeof(Oid));
3957 for (i = 0; i < numParams; i++)
3958 paramTypes[i] = pq_getmsgint(&input_message, 4);
3960 pq_getmsgend(&input_message);
3962 exec_parse_message(query_string, stmt_name,
3963 paramTypes, numParams);
3967 case 'B': /* bind */
3968 /* Set statement_timestamp() */
3969 SetCurrentStatementStartTimestamp();
3972 * this message is complex enough that it seems best to put
3973 * the field extraction out-of-line
3975 exec_bind_message(&input_message);
3978 case 'E': /* execute */
3980 const char *portal_name;
3983 /* Set statement_timestamp() */
3984 SetCurrentStatementStartTimestamp();
3986 portal_name = pq_getmsgstring(&input_message);
3987 max_rows = pq_getmsgint(&input_message, 4);
3988 pq_getmsgend(&input_message);
3990 exec_execute_message(portal_name, max_rows);
3994 case 'F': /* fastpath function call */
3995 /* Set statement_timestamp() */
3996 SetCurrentStatementStartTimestamp();
3998 /* Tell the collector what we're doing */
3999 pgstat_report_activity("<FASTPATH> function call");
4001 /* start an xact for this function invocation */
4002 start_xact_command();
4005 * Note: we may at this point be inside an aborted
4006 * transaction. We can't throw error for that until we've
4007 * finished reading the function-call message, so
4008 * HandleFunctionRequest() must check for it after doing so.
4009 * Be careful not to do anything that assumes we're inside a
4010 * valid transaction here.
4013 /* switch back to message context */
4014 MemoryContextSwitchTo(MessageContext);
4016 if (HandleFunctionRequest(&input_message) == EOF)
4018 /* lost frontend connection during F message input */
4021 * Reset whereToSendOutput to prevent ereport from
4022 * attempting to send any more messages to client.
4024 if (whereToSendOutput == DestRemote)
4025 whereToSendOutput = DestNone;
4030 /* commit the function-invocation transaction */
4031 finish_xact_command();
4033 send_ready_for_query = true;
4036 case 'C': /* close */
4039 const char *close_target;
4041 close_type = pq_getmsgbyte(&input_message);
4042 close_target = pq_getmsgstring(&input_message);
4043 pq_getmsgend(&input_message);
4048 if (close_target[0] != '\0')
4049 DropPreparedStatement(close_target, false);
4052 /* special-case the unnamed statement */
4053 drop_unnamed_stmt();
4060 portal = GetPortalByName(close_target);
4061 if (PortalIsValid(portal))
4062 PortalDrop(portal, false);
4067 (errcode(ERRCODE_PROTOCOL_VIOLATION),
4068 errmsg("invalid CLOSE message subtype %d",
4073 if (whereToSendOutput == DestRemote)
4074 pq_putemptymessage('3'); /* CloseComplete */
4078 case 'D': /* describe */
4081 const char *describe_target;
4083 /* Set statement_timestamp() (needed for xact) */
4084 SetCurrentStatementStartTimestamp();
4086 describe_type = pq_getmsgbyte(&input_message);
4087 describe_target = pq_getmsgstring(&input_message);
4088 pq_getmsgend(&input_message);
4090 switch (describe_type)
4093 exec_describe_statement_message(describe_target);
4096 exec_describe_portal_message(describe_target);
4100 (errcode(ERRCODE_PROTOCOL_VIOLATION),
4101 errmsg("invalid DESCRIBE message subtype %d",
4108 case 'H': /* flush */
4109 pq_getmsgend(&input_message);
4110 if (whereToSendOutput == DestRemote)
4114 case 'S': /* sync */
4115 pq_getmsgend(&input_message);
4116 finish_xact_command();
4117 send_ready_for_query = true;
4121 * 'X' means that the frontend is closing down the socket. EOF
4122 * means unexpected loss of frontend connection. Either way,
4123 * perform normal shutdown.
4129 * Reset whereToSendOutput to prevent ereport from attempting
4130 * to send any more messages to client.
4132 if (whereToSendOutput == DestRemote)
4133 whereToSendOutput = DestNone;
4136 * NOTE: if you are tempted to add more code here, DON'T!
4137 * Whatever you had in mind to do should be set up as an
4138 * on_proc_exit or on_shmem_exit callback, instead. Otherwise
4139 * it will fail to be called during other backend-shutdown
4144 case 'd': /* copy data */
4145 case 'c': /* copy done */
4146 case 'f': /* copy fail */
4149 * Accept but ignore these messages, per protocol spec; we
4150 * probably got here because a COPY failed, and the frontend
4151 * is still sending data.
4157 (errcode(ERRCODE_PROTOCOL_VIOLATION),
4158 errmsg("invalid frontend message type %d",
4161 } /* end of input-reading loop */
4163 /* can't get here because the above loop never exits */
4166 return 1; /* keep compiler quiet */
4171 * Obtain platform stack depth limit (in bytes)
4173 * Return -1 if unknown
4176 get_stack_depth_rlimit(void)
4178 #if defined(HAVE_GETRLIMIT) && defined(RLIMIT_STACK)
4179 static long val = 0;
4181 /* This won't change after process launch, so check just once */
4186 if (getrlimit(RLIMIT_STACK, &rlim) < 0)
4188 else if (rlim.rlim_cur == RLIM_INFINITY)
4190 /* rlim_cur is probably of an unsigned type, so check for overflow */
4191 else if (rlim.rlim_cur >= LONG_MAX)
4194 val = rlim.rlim_cur;
4197 #else /* no getrlimit */
4198 #if defined(WIN32) || defined(__CYGWIN__)
4199 /* On Windows we set the backend stack size in src/backend/Makefile */
4200 return WIN32_STACK_RLIMIT;
4201 #else /* not windows ... give up */
4208 static struct rusage Save_r;
4209 static struct timeval Save_t;
4214 getrusage(RUSAGE_SELF, &Save_r);
4215 gettimeofday(&Save_t, NULL);
4219 ShowUsage(const char *title)
4222 struct timeval user,
4224 struct timeval elapse_t;
4227 getrusage(RUSAGE_SELF, &r);
4228 gettimeofday(&elapse_t, NULL);
4229 memcpy((char *) &user, (char *) &r.ru_utime, sizeof(user));
4230 memcpy((char *) &sys, (char *) &r.ru_stime, sizeof(sys));
4231 if (elapse_t.tv_usec < Save_t.tv_usec)
4234 elapse_t.tv_usec += 1000000;
4236 if (r.ru_utime.tv_usec < Save_r.ru_utime.tv_usec)
4238 r.ru_utime.tv_sec--;
4239 r.ru_utime.tv_usec += 1000000;
4241 if (r.ru_stime.tv_usec < Save_r.ru_stime.tv_usec)
4243 r.ru_stime.tv_sec--;
4244 r.ru_stime.tv_usec += 1000000;
4248 * the only stats we don't show here are for memory usage -- i can't
4249 * figure out how to interpret the relevant fields in the rusage struct,
4250 * and they change names across o/s platforms, anyway. if you can figure
4251 * out what the entries mean, you can somehow extract resident set size,
4252 * shared text size, and unshared data and stack sizes.
4254 initStringInfo(&str);
4256 appendStringInfo(&str, "! system usage stats:\n");
4257 appendStringInfo(&str,
4258 "!\t%ld.%06ld elapsed %ld.%06ld user %ld.%06ld system sec\n",
4259 (long) (elapse_t.tv_sec - Save_t.tv_sec),
4260 (long) (elapse_t.tv_usec - Save_t.tv_usec),
4261 (long) (r.ru_utime.tv_sec - Save_r.ru_utime.tv_sec),
4262 (long) (r.ru_utime.tv_usec - Save_r.ru_utime.tv_usec),
4263 (long) (r.ru_stime.tv_sec - Save_r.ru_stime.tv_sec),
4264 (long) (r.ru_stime.tv_usec - Save_r.ru_stime.tv_usec));
4265 appendStringInfo(&str,
4266 "!\t[%ld.%06ld user %ld.%06ld sys total]\n",
4268 (long) user.tv_usec,
4270 (long) sys.tv_usec);
4271 #if defined(HAVE_GETRUSAGE)
4272 appendStringInfo(&str,
4273 "!\t%ld/%ld [%ld/%ld] filesystem blocks in/out\n",
4274 r.ru_inblock - Save_r.ru_inblock,
4275 /* they only drink coffee at dec */
4276 r.ru_oublock - Save_r.ru_oublock,
4277 r.ru_inblock, r.ru_oublock);
4278 appendStringInfo(&str,
4279 "!\t%ld/%ld [%ld/%ld] page faults/reclaims, %ld [%ld] swaps\n",
4280 r.ru_majflt - Save_r.ru_majflt,
4281 r.ru_minflt - Save_r.ru_minflt,
4282 r.ru_majflt, r.ru_minflt,
4283 r.ru_nswap - Save_r.ru_nswap,
4285 appendStringInfo(&str,
4286 "!\t%ld [%ld] signals rcvd, %ld/%ld [%ld/%ld] messages rcvd/sent\n",
4287 r.ru_nsignals - Save_r.ru_nsignals,
4289 r.ru_msgrcv - Save_r.ru_msgrcv,
4290 r.ru_msgsnd - Save_r.ru_msgsnd,
4291 r.ru_msgrcv, r.ru_msgsnd);
4292 appendStringInfo(&str,
4293 "!\t%ld/%ld [%ld/%ld] voluntary/involuntary context switches\n",
4294 r.ru_nvcsw - Save_r.ru_nvcsw,
4295 r.ru_nivcsw - Save_r.ru_nivcsw,
4296 r.ru_nvcsw, r.ru_nivcsw);
4297 #endif /* HAVE_GETRUSAGE */
4299 /* remove trailing newline */
4300 if (str.data[str.len - 1] == '\n')
4301 str.data[--str.len] = '\0';
4304 (errmsg_internal("%s", title),
4305 errdetail("%s", str.data)));
4311 * on_proc_exit handler to log end of session
4314 log_disconnections(int code, Datum arg)
4316 Port *port = MyProcPort;
4324 TimestampDifference(port->SessionStartTime,
4325 GetCurrentTimestamp(),
4327 msecs = usecs / 1000;
4329 hours = secs / SECS_PER_HOUR;
4330 secs %= SECS_PER_HOUR;
4331 minutes = secs / SECS_PER_MINUTE;
4332 seconds = secs % SECS_PER_MINUTE;
4335 (errmsg("disconnection: session time: %d:%02d:%02d.%03d "
4336 "user=%s database=%s host=%s%s%s",
4337 hours, minutes, seconds, msecs,
4338 port->user_name, port->database_name, port->remote_host,
4339 port->remote_port[0] ? " port=" : "", port->remote_port)));