1 /*-------------------------------------------------------------------------
4 * POSTGRES C Backend Interface
6 * Portions Copyright (c) 1996-2002, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
11 * $Header: /cvsroot/pgsql/src/backend/tcop/postgres.c,v 1.354 2003/08/04 00:43:25 momjian Exp $
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>
30 #include <sys/select.h>
36 #include "access/printtup.h"
37 #include "access/xlog.h"
38 #include "catalog/pg_type.h"
39 #include "commands/async.h"
40 #include "commands/prepare.h"
41 #include "commands/trigger.h"
42 #include "libpq/libpq.h"
43 #include "libpq/pqformat.h"
44 #include "libpq/pqsignal.h"
45 #include "miscadmin.h"
46 #include "nodes/print.h"
47 #include "optimizer/cost.h"
48 #include "optimizer/planner.h"
49 #include "parser/analyze.h"
50 #include "parser/parser.h"
51 #include "rewrite/rewriteHandler.h"
52 #include "storage/freespace.h"
53 #include "storage/ipc.h"
54 #include "storage/pg_shmem.h"
55 #include "storage/proc.h"
56 #include "tcop/fastpath.h"
57 #include "tcop/pquery.h"
58 #include "tcop/tcopprot.h"
59 #include "tcop/utility.h"
60 #include "utils/guc.h"
61 #include "utils/lsyscache.h"
62 #include "utils/memutils.h"
63 #include "utils/ps_status.h"
64 #include "mb/pg_wchar.h"
76 const char *debug_query_string; /* for pgmonitor and
77 * log_min_error_statement */
79 /* Note: whereToSendOutput is initialized for the bootstrap/standalone case */
80 CommandDest whereToSendOutput = Debug;
82 /* note: these declarations had better match tcopprot.h */
83 sigjmp_buf Warn_restart;
85 bool Warn_restart_ready = false;
89 * Flags for expensive function optimization -- JMH 3/9/92
99 * Flag to mark SIGHUP. Whenever the main loop comes around it
100 * will reread the configuration file. (Better than doing the
101 * reading in the signal handler, ey?)
103 static volatile bool got_SIGHUP = false;
106 * Flag to keep track of whether we have started a transaction.
107 * For extended query protocol this has to be remembered across messages.
109 static bool xact_started = false;
112 * Flags to implement skip-till-Sync-after-error behavior for messages of
113 * the extended query protocol.
115 static bool doing_extended_query_message = false;
116 static bool ignore_till_sync = false;
119 * If an unnamed prepared statement exists, it's stored here.
120 * We keep it separate from the hashtable kept by commands/prepare.c
121 * in order to reduce overhead for short-lived queries.
123 static MemoryContext unnamed_stmt_context = NULL;
124 static PreparedStatement *unnamed_stmt_pstmt = NULL;
127 static bool EchoQuery = false; /* default don't echo */
130 * people who want to use EOF should #define DONTUSENEWLINE in
133 #ifndef TCOP_DONTUSENEWLINE
134 static int UseNewLine = 1; /* Use newlines query delimiters (the
138 static int UseNewLine = 0; /* Use EOF as query delimiters */
139 #endif /* TCOP_DONTUSENEWLINE */
142 /* ----------------------------------------------------------------
143 * decls for routines only used in this file
144 * ----------------------------------------------------------------
146 static int InteractiveBackend(StringInfo inBuf);
147 static int SocketBackend(StringInfo inBuf);
148 static int ReadCommand(StringInfo inBuf);
149 static void start_xact_command(void);
150 static void finish_xact_command(void);
151 static void SigHupHandler(SIGNAL_ARGS);
152 static void FloatExceptionHandler(SIGNAL_ARGS);
155 /* ----------------------------------------------------------------
156 * routines to obtain user input
157 * ----------------------------------------------------------------
161 * InteractiveBackend() is called for user interactive connections
163 * the string entered by the user is placed in its parameter inBuf,
164 * and we act like a Q message was received.
166 * EOF is returned if end-of-file input is seen; time to shut down.
171 InteractiveBackend(StringInfo inBuf)
173 int c; /* character read from getc() */
174 bool end = false; /* end-of-input flag */
175 bool backslashSeen = false; /* have we seen a \ ? */
178 * display a prompt and obtain input from the user
183 /* Reset inBuf to empty */
185 inBuf->data[0] = '\0';
193 * if we are using \n as a delimiter, then read characters
196 while ((c = getc(stdin)) != EOF)
202 /* discard backslash from inBuf */
203 inBuf->data[--inBuf->len] = '\0';
204 backslashSeen = false;
209 /* keep the newline character */
210 appendStringInfoChar(inBuf, '\n');
215 backslashSeen = true;
217 backslashSeen = false;
219 appendStringInfoChar(inBuf, (char) c);
228 * otherwise read characters until EOF.
230 while ((c = getc(stdin)) != EOF)
231 appendStringInfoChar(inBuf, (char) c);
241 * otherwise we have a user query so process it.
246 /* Add '\0' to make it look the same as message case. */
247 appendStringInfoChar(inBuf, (char) '\0');
250 * if the query echo flag was given, print the query..
253 printf("statement: %s\n", inBuf->data);
260 * SocketBackend() Is called for frontend-backend connections
262 * Returns the message type code, and loads message body data into inBuf.
264 * EOF is returned if the connection is lost.
268 SocketBackend(StringInfo inBuf)
273 * Get message type code from the frontend.
275 qtype = pq_getbyte();
277 if (qtype == EOF) /* frontend disconnected */
280 (errcode(ERRCODE_PROTOCOL_VIOLATION),
281 errmsg("unexpected EOF on client connection")));
286 * Validate message type code before trying to read body; if we have
287 * lost sync, better to say "command unknown" than to run out of
288 * memory because we used garbage as a length word.
290 * This also gives us a place to set the doing_extended_query_message
291 * flag as soon as possible.
295 case 'Q': /* simple query */
296 doing_extended_query_message = false;
297 if (PG_PROTOCOL_MAJOR(FrontendProtocol) < 3)
299 /* old style without length word; convert */
300 if (pq_getstring(inBuf))
303 (errcode(ERRCODE_PROTOCOL_VIOLATION),
304 errmsg("unexpected EOF on client connection")));
310 case 'F': /* fastpath function call */
311 /* we let fastpath.c cope with old-style input of this */
312 doing_extended_query_message = false;
315 case 'X': /* terminate */
316 doing_extended_query_message = false;
317 ignore_till_sync = false;
321 case 'C': /* close */
322 case 'D': /* describe */
323 case 'E': /* execute */
324 case 'H': /* flush */
325 case 'P': /* parse */
326 doing_extended_query_message = true;
327 /* these are only legal in protocol 3 */
328 if (PG_PROTOCOL_MAJOR(FrontendProtocol) < 3)
330 (errcode(ERRCODE_PROTOCOL_VIOLATION),
331 errmsg("invalid frontend message type %d", qtype)));
335 /* stop any active skip-till-Sync */
336 ignore_till_sync = false;
337 /* mark not-extended, so that a new error doesn't begin skip */
338 doing_extended_query_message = false;
339 /* only legal in protocol 3 */
340 if (PG_PROTOCOL_MAJOR(FrontendProtocol) < 3)
342 (errcode(ERRCODE_PROTOCOL_VIOLATION),
343 errmsg("invalid frontend message type %d", qtype)));
346 case 'd': /* copy data */
347 case 'c': /* copy done */
348 case 'f': /* copy fail */
349 doing_extended_query_message = false;
350 /* these are only legal in protocol 3 */
351 if (PG_PROTOCOL_MAJOR(FrontendProtocol) < 3)
353 (errcode(ERRCODE_PROTOCOL_VIOLATION),
354 errmsg("invalid frontend message type %d", qtype)));
360 * Otherwise we got garbage from the frontend. We treat this
361 * as fatal because we have probably lost message boundary
362 * sync, and there's no good way to recover.
365 (errcode(ERRCODE_PROTOCOL_VIOLATION),
366 errmsg("invalid frontend message type %d", qtype)));
371 * In protocol version 3, all frontend messages have a length word
372 * next after the type code; we can read the message contents
373 * independently of the type.
375 if (PG_PROTOCOL_MAJOR(FrontendProtocol) >= 3)
377 if (pq_getmessage(inBuf, 0))
378 return EOF; /* suitable message already logged */
385 * ReadCommand reads a command from either the frontend or
386 * standard input, places it in inBuf, and returns the
387 * message type code (first byte of the message).
388 * EOF is returned if end of file.
392 ReadCommand(StringInfo inBuf)
396 if (IsUnderPostmaster)
397 result = SocketBackend(inBuf);
399 result = InteractiveBackend(inBuf);
405 * Parse a query string and pass it through the rewriter.
407 * A list of Query nodes is returned, since the string might contain
408 * multiple queries and/or the rewriter might expand one query to several.
410 * NOTE: this routine is no longer used for processing interactive queries,
411 * but it is still needed for parsing of SQL function bodies.
414 pg_parse_and_rewrite(const char *query_string, /* string to execute */
415 Oid *paramTypes, /* parameter types */
416 int numParams) /* number of parameters */
418 List *raw_parsetree_list;
419 List *querytree_list;
423 * (1) parse the request string into a list of raw parse trees.
425 raw_parsetree_list = pg_parse_query(query_string);
428 * (2) Do parse analysis and rule rewrite.
430 querytree_list = NIL;
431 foreach(list_item, raw_parsetree_list)
433 Node *parsetree = (Node *) lfirst(list_item);
435 querytree_list = nconc(querytree_list,
436 pg_analyze_and_rewrite(parsetree,
441 return querytree_list;
445 * Do raw parsing (only).
447 * A list of parsetrees is returned, since there might be multiple
448 * commands in the given string.
450 * NOTE: for interactive queries, it is important to keep this routine
451 * separate from the analysis & rewrite stages. Analysis and rewriting
452 * cannot be done in an aborted transaction, since they require access to
453 * database tables. So, we rely on the raw parser to determine whether
454 * we've seen a COMMIT or ABORT command; when we are in abort state, other
455 * commands are not processed any further than the raw parse stage.
458 pg_parse_query(const char *query_string)
460 List *raw_parsetree_list;
464 (errmsg("query: %s", query_string)));
466 if (log_parser_stats)
469 raw_parsetree_list = raw_parser(query_string);
471 if (log_parser_stats)
472 ShowUsage("PARSER STATISTICS");
474 return raw_parsetree_list;
478 * Given a raw parsetree (gram.y output), and optionally information about
479 * types of parameter symbols ($n), perform parse analysis and rule rewriting.
481 * A list of Query nodes is returned, since either the analyzer or the
482 * rewriter might expand one query to several.
484 * NOTE: for reasons mentioned above, this must be separate from raw parsing.
487 pg_analyze_and_rewrite(Node *parsetree, Oid *paramTypes, int numParams)
489 List *querytree_list;
492 * (1) Perform parse analysis.
494 if (log_parser_stats)
497 querytree_list = parse_analyze(parsetree, paramTypes, numParams);
499 if (log_parser_stats)
500 ShowUsage("PARSE ANALYSIS STATISTICS");
503 * (2) Rewrite the queries, as necessary
505 querytree_list = pg_rewrite_queries(querytree_list);
507 return querytree_list;
511 * Perform rewriting of a list of queries produced by parse analysis.
514 pg_rewrite_queries(List *querytree_list)
516 List *new_list = NIL;
519 if (log_parser_stats)
523 * rewritten queries are collected in new_list. Note there may be
524 * more or fewer than in the original list.
526 foreach(list_item, querytree_list)
528 Query *querytree = (Query *) lfirst(list_item);
530 if (Debug_print_parse)
531 elog_node_display(DEBUG1, "parse tree", querytree,
534 if (querytree->commandType == CMD_UTILITY)
536 /* don't rewrite utilities, just dump 'em into new_list */
537 new_list = lappend(new_list, querytree);
541 /* rewrite regular queries */
542 List *rewritten = QueryRewrite(querytree);
544 new_list = nconc(new_list, rewritten);
548 querytree_list = new_list;
550 if (log_parser_stats)
551 ShowUsage("REWRITER STATISTICS");
553 #ifdef COPY_PARSE_PLAN_TREES
556 * Optional debugging check: pass querytree output through
559 new_list = (List *) copyObject(querytree_list);
560 /* This checks both copyObject() and the equal() routines... */
561 if (!equal(new_list, querytree_list))
563 (errmsg("copyObject failed to produce an equal parse tree")));
565 querytree_list = new_list;
568 if (Debug_print_rewritten)
569 elog_node_display(DEBUG1, "rewritten parse tree", querytree_list,
572 return querytree_list;
576 /* Generate a plan for a single already-rewritten query. */
578 pg_plan_query(Query *querytree)
582 /* Utility commands have no plans. */
583 if (querytree->commandType == CMD_UTILITY)
586 if (log_planner_stats)
589 /* call the optimizer */
590 plan = planner(querytree, false, 0);
592 if (log_planner_stats)
593 ShowUsage("PLANNER STATISTICS");
595 #ifdef COPY_PARSE_PLAN_TREES
596 /* Optional debugging check: pass plan output through copyObject() */
598 Plan *new_plan = (Plan *) copyObject(plan);
601 * equal() currently does not have routines to compare Plan nodes,
602 * so don't try to test equality here. Perhaps fix someday?
605 /* This checks both copyObject() and the equal() routines... */
606 if (!equal(new_plan, plan))
608 (errmsg("copyObject failed to produce an equal plan tree")));
616 * Print plan if debugging.
618 if (Debug_print_plan)
619 elog_node_display(DEBUG1, "plan", plan, Debug_pretty_print);
625 * Generate plans for a list of already-rewritten queries.
627 * If needSnapshot is TRUE, we haven't yet set a snapshot for the current
628 * query. A snapshot must be set before invoking the planner, since it
629 * might try to evaluate user-defined functions. But we must not set a
630 * snapshot if the list contains only utility statements, because some
631 * utility statements depend on not having frozen the snapshot yet.
632 * (We assume that such statements cannot appear together with plannable
633 * statements in the rewriter's output.)
636 pg_plan_queries(List *querytrees, bool needSnapshot)
638 List *plan_list = NIL;
641 foreach(query_list, querytrees)
643 Query *query = (Query *) lfirst(query_list);
646 if (query->commandType == CMD_UTILITY)
648 /* Utility commands have no plans. */
656 needSnapshot = false;
658 plan = pg_plan_query(query);
661 plan_list = lappend(plan_list, plan);
671 * Execute a "simple Query" protocol message.
674 exec_simple_query(const char *query_string)
676 CommandDest dest = whereToSendOutput;
677 MemoryContext oldcontext;
678 List *parsetree_list,
680 struct timeval start_t,
682 bool save_log_duration = log_duration;
683 int save_log_min_duration_statement = log_min_duration_statement;
684 bool save_log_statement_stats = log_statement_stats;
687 * Report query to various monitoring facilities.
689 debug_query_string = query_string;
691 pgstat_report_activity(query_string);
694 * We use save_log_* so "SET log_duration = true" and "SET
695 * log_min_duration_statement = true" don't report incorrect time
696 * because gettimeofday() wasn't called. Similarly,
697 * log_statement_stats has to be captured once.
699 if (save_log_duration || save_log_min_duration_statement > 0)
700 gettimeofday(&start_t, NULL);
702 if (save_log_statement_stats)
706 * Start up a transaction command. All queries generated by the
707 * query_string will be in this same command block, *unless* we find a
708 * BEGIN/COMMIT/ABORT statement; we have to force a new xact command
709 * after one of those, else bad things will happen in xact.c. (Note
710 * that this will normally change current memory context.)
712 start_xact_command();
715 * Zap any pre-existing unnamed statement. (While not strictly
716 * necessary, it seems best to define simple-Query mode as if it used
717 * the unnamed statement and portal; this ensures we recover any
718 * storage used by prior unnamed operations.)
720 unnamed_stmt_pstmt = NULL;
721 if (unnamed_stmt_context)
723 DropDependentPortals(unnamed_stmt_context);
724 MemoryContextDelete(unnamed_stmt_context);
726 unnamed_stmt_context = NULL;
729 * Switch to appropriate context for constructing parsetrees.
731 oldcontext = MemoryContextSwitchTo(MessageContext);
733 QueryContext = CurrentMemoryContext;
736 * Do basic parsing of the query or queries (this should be safe even
737 * if we are in aborted transaction state!)
739 parsetree_list = pg_parse_query(query_string);
742 * Switch back to transaction context to enter the loop.
744 MemoryContextSwitchTo(oldcontext);
747 * Run through the raw parsetree(s) and process each one.
749 foreach(parsetree_item, parsetree_list)
751 Node *parsetree = (Node *) lfirst(parsetree_item);
752 const char *commandTag;
753 char completionTag[COMPLETION_TAG_BUFSIZE];
754 List *querytree_list,
757 DestReceiver *receiver;
761 * Get the command name for use in status display (it also becomes
762 * the default completion tag, down inside PortalRun). Set
763 * ps_status and do any special start-of-SQL-command processing
764 * needed by the destination.
766 commandTag = CreateCommandTag(parsetree);
768 set_ps_display(commandTag);
770 BeginCommand(commandTag, dest);
773 * If we are in an aborted transaction, reject all commands except
774 * COMMIT/ABORT. It is important that this test occur before we
775 * try to do parse analysis, rewrite, or planning, since all those
776 * phases try to do database accesses, which may fail in abort
777 * state. (It might be safe to allow some additional utility
778 * commands in this state, but not many...)
780 if (IsAbortedTransactionBlockState())
782 bool allowit = false;
784 if (IsA(parsetree, TransactionStmt))
786 TransactionStmt *stmt = (TransactionStmt *) parsetree;
788 if (stmt->kind == TRANS_STMT_COMMIT ||
789 stmt->kind == TRANS_STMT_ROLLBACK)
795 (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
796 errmsg("current transaction is aborted, "
797 "queries ignored until end of transaction block")));
800 /* Make sure we are in a transaction command */
801 start_xact_command();
803 /* If we got a cancel signal in parsing or prior command, quit */
804 CHECK_FOR_INTERRUPTS();
807 * OK to analyze, rewrite, and plan this query.
809 * Switch to appropriate context for constructing querytrees (again,
810 * these must outlive the execution context).
812 oldcontext = MemoryContextSwitchTo(MessageContext);
814 querytree_list = pg_analyze_and_rewrite(parsetree, NULL, 0);
816 plantree_list = pg_plan_queries(querytree_list, true);
818 /* If we got a cancel signal in analysis or planning, quit */
819 CHECK_FOR_INTERRUPTS();
822 * Create unnamed portal to run the query or queries in. If there
823 * already is one, silently drop it.
825 portal = CreatePortal("", true, true);
827 PortalDefineQuery(portal,
835 * Start the portal. No parameters here.
837 PortalStart(portal, NULL);
840 * Select the appropriate output format: text unless we are doing
841 * a FETCH from a binary cursor. (Pretty grotty to have to do
842 * this here --- but it avoids grottiness in other places. Ah,
843 * the joys of backward compatibility...)
845 format = 0; /* TEXT is default */
846 if (IsA(parsetree, FetchStmt))
848 FetchStmt *stmt = (FetchStmt *) parsetree;
852 Portal fportal = GetPortalByName(stmt->portalname);
854 if (PortalIsValid(fportal) &&
855 (fportal->cursorOptions & CURSOR_OPT_BINARY))
856 format = 1; /* BINARY */
859 PortalSetResultFormat(portal, 1, &format);
862 * Now we can create the destination receiver object.
864 receiver = CreateDestReceiver(dest, portal);
867 * Switch back to transaction context for execution.
869 MemoryContextSwitchTo(oldcontext);
872 * Run the portal to completion, and then drop it (and the
875 (void) PortalRun(portal,
881 (*receiver->destroy) (receiver);
883 PortalDrop(portal, false);
885 if (IsA(parsetree, TransactionStmt))
888 * If this was a transaction control statement, commit it. We
889 * will start a new xact command for the next command (if
892 finish_xact_command();
894 else if (lnext(parsetree_item) == NIL)
897 * If this is the last parsetree of the query string, close
898 * down transaction statement before reporting
899 * command-complete. This is so that any end-of-transaction
900 * errors are reported before the command-complete message is
901 * issued, to avoid confusing clients who will expect either a
902 * command-complete message or an error, not one and then the
903 * other. But for compatibility with historical Postgres
904 * behavior, we do not force a transaction boundary between
905 * queries appearing in a single query string.
907 finish_xact_command();
912 * We need a CommandCounterIncrement after every query, except
913 * those that start or end a transaction block.
915 CommandCounterIncrement();
919 * Tell client that we're done with this query. Note we emit
920 * exactly one EndCommand report for each raw parsetree, thus one
921 * for each SQL command the client sent, regardless of rewriting.
922 * (But a command aborted by error will not send an EndCommand
925 EndCommand(completionTag, dest);
926 } /* end loop over parsetrees */
929 * Close down transaction statement, if one is open.
931 finish_xact_command();
934 * If there were no parsetrees, return EmptyQueryResponse message.
942 * Combine processing here as we need to calculate the query duration
945 if (save_log_duration || save_log_min_duration_statement > 0)
949 gettimeofday(&stop_t, NULL);
950 if (stop_t.tv_usec < start_t.tv_usec)
953 stop_t.tv_usec += 1000000;
955 usecs = (long) (stop_t.tv_sec - start_t.tv_sec) * 1000000 + (long) (stop_t.tv_usec - start_t.tv_usec);
958 * Output a duration_query to the log if the query has exceeded
961 if (usecs >= save_log_min_duration_statement * 1000)
963 (errmsg("duration_statement: %ld.%06ld %s",
964 (long) (stop_t.tv_sec - start_t.tv_sec),
965 (long) (stop_t.tv_usec - start_t.tv_usec),
969 * If the user is requesting logging of all durations, then log
972 if (save_log_duration)
974 (errmsg("duration: %ld.%06ld sec",
975 (long) (stop_t.tv_sec - start_t.tv_sec),
976 (long) (stop_t.tv_usec - start_t.tv_usec))));
979 if (save_log_statement_stats)
980 ShowUsage("QUERY STATISTICS");
982 debug_query_string = NULL;
988 * Execute a "Parse" protocol message.
991 exec_parse_message(const char *query_string, /* string to execute */
992 const char *stmt_name, /* name for prepared stmt */
993 Oid *paramTypes, /* parameter types */
994 int numParams) /* number of parameters */
996 MemoryContext oldcontext;
997 List *parsetree_list;
998 const char *commandTag;
999 List *querytree_list,
1003 bool save_log_statement_stats = log_statement_stats;
1006 * Report query to various monitoring facilities.
1008 debug_query_string = query_string;
1010 pgstat_report_activity(query_string);
1012 set_ps_display("PARSE");
1014 if (save_log_statement_stats)
1018 * Start up a transaction command so we can run parse analysis etc.
1019 * (Note that this will normally change current memory context.)
1020 * Nothing happens if we are already in one.
1022 start_xact_command();
1025 * Switch to appropriate context for constructing parsetrees.
1027 * We have two strategies depending on whether the prepared statement is
1028 * named or not. For a named prepared statement, we do parsing in
1029 * MessageContext and copy the finished trees into the prepared
1030 * statement's private context; then the reset of MessageContext
1031 * releases temporary space used by parsing and planning. For an
1032 * unnamed prepared statement, we assume the statement isn't going to
1033 * hang around long, so getting rid of temp space quickly is probably
1034 * not worth the costs of copying parse/plan trees. So in this case,
1035 * we set up a special context for the unnamed statement, and do all
1036 * the parsing/planning therein.
1038 is_named = (stmt_name[0] != '\0');
1041 /* Named prepared statement --- parse in MessageContext */
1042 oldcontext = MemoryContextSwitchTo(MessageContext);
1046 /* Unnamed prepared statement --- release any prior unnamed stmt */
1047 unnamed_stmt_pstmt = NULL;
1048 if (unnamed_stmt_context)
1050 DropDependentPortals(unnamed_stmt_context);
1051 MemoryContextDelete(unnamed_stmt_context);
1053 unnamed_stmt_context = NULL;
1054 /* create context for parsing/planning */
1055 unnamed_stmt_context =
1056 AllocSetContextCreate(TopMemoryContext,
1057 "unnamed prepared statement",
1058 ALLOCSET_DEFAULT_MINSIZE,
1059 ALLOCSET_DEFAULT_INITSIZE,
1060 ALLOCSET_DEFAULT_MAXSIZE);
1061 oldcontext = MemoryContextSwitchTo(unnamed_stmt_context);
1064 QueryContext = CurrentMemoryContext;
1067 * Do basic parsing of the query or queries (this should be safe even
1068 * if we are in aborted transaction state!)
1070 parsetree_list = pg_parse_query(query_string);
1073 * We only allow a single user statement in a prepared statement. This
1074 * is mainly to keep the protocol simple --- otherwise we'd need to
1075 * worry about multiple result tupdescs and things like that.
1077 if (length(parsetree_list) > 1)
1079 (errcode(ERRCODE_SYNTAX_ERROR),
1080 errmsg("cannot insert multiple commands into a prepared statement")));
1082 if (parsetree_list != NIL)
1084 Node *parsetree = (Node *) lfirst(parsetree_list);
1088 * Get the command name for possible use in status display.
1090 commandTag = CreateCommandTag(parsetree);
1093 * If we are in an aborted transaction, reject all commands except
1094 * COMMIT/ROLLBACK. It is important that this test occur before
1095 * we try to do parse analysis, rewrite, or planning, since all
1096 * those phases try to do database accesses, which may fail in
1097 * abort state. (It might be safe to allow some additional utility
1098 * commands in this state, but not many...)
1100 if (IsAbortedTransactionBlockState())
1102 bool allowit = false;
1104 if (IsA(parsetree, TransactionStmt))
1106 TransactionStmt *stmt = (TransactionStmt *) parsetree;
1108 if (stmt->kind == TRANS_STMT_COMMIT ||
1109 stmt->kind == TRANS_STMT_ROLLBACK)
1115 (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
1116 errmsg("current transaction is aborted, "
1117 "queries ignored until end of transaction block")));
1121 * OK to analyze, rewrite, and plan this query. Note that the
1122 * originally specified parameter set is not required to be
1123 * complete, so we have to use parse_analyze_varparams().
1125 if (log_parser_stats)
1128 querytree_list = parse_analyze_varparams(parsetree,
1133 * Check all parameter types got determined, and convert array
1134 * representation to a list for storage.
1137 for (i = 0; i < numParams; i++)
1139 Oid ptype = paramTypes[i];
1141 if (ptype == InvalidOid || ptype == UNKNOWNOID)
1143 (errcode(ERRCODE_INDETERMINATE_DATATYPE),
1144 errmsg("could not determine datatype of parameter $%d",
1146 param_list = lappendo(param_list, ptype);
1149 if (log_parser_stats)
1150 ShowUsage("PARSE ANALYSIS STATISTICS");
1152 querytree_list = pg_rewrite_queries(querytree_list);
1154 plantree_list = pg_plan_queries(querytree_list, true);
1158 /* Empty input string. This is legal. */
1160 querytree_list = NIL;
1161 plantree_list = NIL;
1165 /* If we got a cancel signal in analysis or planning, quit */
1166 CHECK_FOR_INTERRUPTS();
1169 * Store the query as a prepared statement. See above comments.
1173 StorePreparedStatement(stmt_name,
1182 PreparedStatement *pstmt;
1184 pstmt = (PreparedStatement *) palloc0(sizeof(PreparedStatement));
1185 /* query_string needs to be copied into unnamed_stmt_context */
1186 pstmt->query_string = pstrdup(query_string);
1187 /* the rest is there already */
1188 pstmt->commandTag = commandTag;
1189 pstmt->query_list = querytree_list;
1190 pstmt->plan_list = plantree_list;
1191 pstmt->argtype_list = param_list;
1192 pstmt->context = unnamed_stmt_context;
1193 /* Now the unnamed statement is complete and valid */
1194 unnamed_stmt_pstmt = pstmt;
1197 MemoryContextSwitchTo(oldcontext);
1199 QueryContext = NULL;
1202 * We do NOT close the open transaction command here; that only
1203 * happens when the client sends Sync. Instead, do
1204 * CommandCounterIncrement just in case something happened during
1207 CommandCounterIncrement();
1210 * Send ParseComplete.
1212 if (whereToSendOutput == Remote)
1213 pq_putemptymessage('1');
1215 if (save_log_statement_stats)
1216 ShowUsage("PARSE MESSAGE STATISTICS");
1218 debug_query_string = NULL;
1224 * Process a "Bind" message to create a portal from a prepared statement
1227 exec_bind_message(StringInfo input_message)
1229 const char *portal_name;
1230 const char *stmt_name;
1232 int16 *pformats = NULL;
1235 int16 *rformats = NULL;
1237 PreparedStatement *pstmt;
1239 ParamListInfo params;
1241 pgstat_report_activity("<BIND>");
1243 set_ps_display("BIND");
1246 * Start up a transaction command so we can call functions etc. (Note
1247 * that this will normally change current memory context.) Nothing
1248 * happens if we are already in one.
1250 start_xact_command();
1252 /* Switch back to message context */
1253 MemoryContextSwitchTo(MessageContext);
1255 /* Get the fixed part of the message */
1256 portal_name = pq_getmsgstring(input_message);
1257 stmt_name = pq_getmsgstring(input_message);
1259 /* Get the parameter format codes */
1260 numPFormats = pq_getmsgint(input_message, 2);
1261 if (numPFormats > 0)
1263 pformats = (int16 *) palloc(numPFormats * sizeof(int16));
1264 for (i = 0; i < numPFormats; i++)
1265 pformats[i] = pq_getmsgint(input_message, 2);
1268 /* Get the parameter value count */
1269 numParams = pq_getmsgint(input_message, 2);
1271 if (numPFormats > 1 && numPFormats != numParams)
1273 (errcode(ERRCODE_PROTOCOL_VIOLATION),
1274 errmsg("bind message has %d parameter formats but %d parameters",
1275 numPFormats, numParams)));
1277 /* Find prepared statement */
1278 if (stmt_name[0] != '\0')
1279 pstmt = FetchPreparedStatement(stmt_name, true);
1282 /* special-case the unnamed statement */
1283 pstmt = unnamed_stmt_pstmt;
1286 (errcode(ERRCODE_UNDEFINED_PSTATEMENT),
1287 errmsg("unnamed prepared statement does not exist")));
1290 if (numParams != length(pstmt->argtype_list))
1292 (errcode(ERRCODE_PROTOCOL_VIOLATION),
1293 errmsg("bind message supplies %d parameters, but prepared statement \"%s\" requires %d",
1294 numParams, stmt_name, length(pstmt->argtype_list))));
1297 * Create the portal. Allow silent replacement of an existing portal
1298 * only if the unnamed portal is specified.
1300 if (portal_name[0] == '\0')
1301 portal = CreatePortal(portal_name, true, true);
1303 portal = CreatePortal(portal_name, false, false);
1305 PortalDefineQuery(portal,
1306 pstmt->query_string,
1313 * Fetch parameters, if any, and store in the portal's memory context.
1315 * In an aborted transaction, we can't risk calling user-defined
1316 * functions, but we can't fail to Bind either, so bind all parameters
1321 bool isaborted = IsAbortedTransactionBlockState();
1323 MemoryContext oldContext;
1325 oldContext = MemoryContextSwitchTo(PortalGetHeapMemory(portal));
1327 params = (ParamListInfo)
1328 palloc0((numParams + 1) * sizeof(ParamListInfoData));
1331 foreach(l, pstmt->argtype_list)
1333 Oid ptype = lfirsto(l);
1337 plength = pq_getmsgint(input_message, 4);
1338 isNull = (plength == -1);
1342 const char *pvalue = pq_getmsgbytes(input_message, plength);
1346 /* We don't bother to check the format in this case */
1352 StringInfoData pbuf;
1355 if (numPFormats > 1)
1356 pformat = pformats[i];
1357 else if (numPFormats > 0)
1358 pformat = pformats[0];
1360 pformat = 0; /* default = text */
1363 * Rather than copying data around, we just set up a
1364 * phony StringInfo pointing to the correct portion of
1365 * the message buffer. We assume we can scribble on
1366 * the message buffer so as to maintain the convention
1367 * that StringInfos have a trailing null. This is
1368 * grotty but is a big win when dealing with very
1369 * large parameter strings.
1371 pbuf.data = (char *) pvalue;
1372 pbuf.maxlen = plength + 1;
1376 csave = pbuf.data[plength];
1377 pbuf.data[plength] = '\0';
1385 getTypeInputInfo(ptype, &typInput, &typElem);
1388 * We have to do encoding conversion before
1389 * calling the typinput routine.
1392 pg_client_to_server((unsigned char *) pbuf.data,
1395 OidFunctionCall3(typInput,
1396 CStringGetDatum(pstring),
1397 ObjectIdGetDatum(typElem),
1399 /* Free result of encoding conversion, if any */
1400 if (pstring != pbuf.data)
1403 else if (pformat == 1)
1409 * Call the parameter type's binary input
1412 getTypeBinaryInputInfo(ptype, &typReceive, &typElem);
1415 OidFunctionCall2(typReceive,
1416 PointerGetDatum(&pbuf),
1417 ObjectIdGetDatum(typElem));
1419 /* Trouble if it didn't eat the whole buffer */
1420 if (pbuf.cursor != pbuf.len)
1422 (errcode(ERRCODE_INVALID_BINARY_REPRESENTATION),
1423 errmsg("incorrect binary data format in bind parameter %d",
1429 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1430 errmsg("unsupported format code: %d",
1434 /* Restore message buffer contents */
1435 pbuf.data[plength] = csave;
1439 params[i].kind = PARAM_NUM;
1440 params[i].id = i + 1;
1441 params[i].isnull = isNull;
1446 params[i].kind = PARAM_INVALID;
1448 MemoryContextSwitchTo(oldContext);
1453 /* Get the result format codes */
1454 numRFormats = pq_getmsgint(input_message, 2);
1455 if (numRFormats > 0)
1457 rformats = (int16 *) palloc(numRFormats * sizeof(int16));
1458 for (i = 0; i < numRFormats; i++)
1459 rformats[i] = pq_getmsgint(input_message, 2);
1462 pq_getmsgend(input_message);
1465 * Start portal execution.
1467 PortalStart(portal, params);
1470 * Apply the result format requests to the portal.
1472 PortalSetResultFormat(portal, numRFormats, rformats);
1475 * Send BindComplete.
1477 if (whereToSendOutput == Remote)
1478 pq_putemptymessage('2');
1482 * exec_execute_message
1484 * Process an "Execute" message for a portal
1487 exec_execute_message(const char *portal_name, long max_rows)
1490 DestReceiver *receiver;
1492 bool is_trans_stmt = false;
1493 bool is_trans_exit = false;
1495 char completionTag[COMPLETION_TAG_BUFSIZE];
1497 /* Adjust destination to tell printtup.c what to do */
1498 dest = whereToSendOutput;
1500 dest = RemoteExecute;
1502 portal = GetPortalByName(portal_name);
1503 if (!PortalIsValid(portal))
1505 (errcode(ERRCODE_UNDEFINED_CURSOR),
1506 errmsg("portal \"%s\" does not exist", portal_name)));
1509 * If the original query was a null string, just return
1510 * EmptyQueryResponse.
1512 if (portal->commandTag == NULL)
1514 Assert(portal->parseTrees == NIL);
1519 if (portal->sourceText)
1521 debug_query_string = portal->sourceText;
1522 pgstat_report_activity(portal->sourceText);
1526 debug_query_string = "execute message";
1527 pgstat_report_activity("<EXECUTE>");
1530 set_ps_display(portal->commandTag);
1532 BeginCommand(portal->commandTag, dest);
1534 /* Check for transaction-control commands */
1535 if (length(portal->parseTrees) == 1)
1537 Query *query = (Query *) lfirst(portal->parseTrees);
1539 if (query->commandType == CMD_UTILITY &&
1540 query->utilityStmt != NULL &&
1541 IsA(query->utilityStmt, TransactionStmt))
1543 TransactionStmt *stmt = (TransactionStmt *) query->utilityStmt;
1545 is_trans_stmt = true;
1546 if (stmt->kind == TRANS_STMT_COMMIT ||
1547 stmt->kind == TRANS_STMT_ROLLBACK)
1548 is_trans_exit = true;
1553 * Create dest receiver in MessageContext (we don't want it in
1554 * transaction context, because that may get deleted if portal
1557 receiver = CreateDestReceiver(dest, portal);
1560 * Ensure we are in a transaction command (this should normally be the
1561 * case already due to prior BIND).
1563 start_xact_command();
1566 * If we are in aborted transaction state, the only portals we can
1567 * actually run are those containing COMMIT or ROLLBACK commands.
1569 if (IsAbortedTransactionBlockState())
1573 (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
1574 errmsg("current transaction is aborted, "
1575 "queries ignored until end of transaction block")));
1578 /* Check for cancel signal before we start execution */
1579 CHECK_FOR_INTERRUPTS();
1582 * Okay to run the portal.
1585 max_rows = FETCH_ALL;
1587 completed = PortalRun(portal,
1593 (*receiver->destroy) (receiver);
1600 * If this was a transaction control statement, commit it. We
1601 * will start a new xact command for the next command (if
1604 finish_xact_command();
1609 * We need a CommandCounterIncrement after every query, except
1610 * those that start or end a transaction block.
1612 CommandCounterIncrement();
1615 /* Send appropriate CommandComplete to client */
1616 EndCommand(completionTag, dest);
1620 /* Portal run not complete, so send PortalSuspended */
1621 if (whereToSendOutput == Remote)
1622 pq_putemptymessage('s');
1625 debug_query_string = NULL;
1629 * exec_describe_statement_message
1631 * Process a "Describe" message for a prepared statement
1634 exec_describe_statement_message(const char *stmt_name)
1636 PreparedStatement *pstmt;
1641 /* Find prepared statement */
1642 if (stmt_name[0] != '\0')
1643 pstmt = FetchPreparedStatement(stmt_name, true);
1646 /* special-case the unnamed statement */
1647 pstmt = unnamed_stmt_pstmt;
1650 (errcode(ERRCODE_UNDEFINED_PSTATEMENT),
1651 errmsg("unnamed prepared statement does not exist")));
1654 if (whereToSendOutput != Remote)
1655 return; /* can't actually do anything... */
1658 * First describe the parameters...
1660 pq_beginmessage(&buf, 't'); /* parameter description message type */
1661 pq_sendint(&buf, length(pstmt->argtype_list), 2);
1663 foreach(l, pstmt->argtype_list)
1665 Oid ptype = lfirsto(l);
1667 pq_sendint(&buf, (int) ptype, 4);
1669 pq_endmessage(&buf);
1672 * Next send RowDescription or NoData to describe the result...
1674 tupdesc = FetchPreparedStatementResultDesc(pstmt);
1679 if (ChoosePortalStrategy(pstmt->query_list) == PORTAL_ONE_SELECT)
1680 targetlist = ((Query *) lfirst(pstmt->query_list))->targetList;
1683 SendRowDescriptionMessage(tupdesc, targetlist, NULL);
1686 pq_putemptymessage('n'); /* NoData */
1691 * exec_describe_portal_message
1693 * Process a "Describe" message for a portal
1696 exec_describe_portal_message(const char *portal_name)
1700 portal = GetPortalByName(portal_name);
1701 if (!PortalIsValid(portal))
1703 (errcode(ERRCODE_UNDEFINED_CURSOR),
1704 errmsg("portal \"%s\" does not exist", portal_name)));
1706 if (whereToSendOutput != Remote)
1707 return; /* can't actually do anything... */
1709 if (portal->tupDesc)
1713 if (portal->strategy == PORTAL_ONE_SELECT)
1714 targetlist = ((Query *) lfirst(portal->parseTrees))->targetList;
1717 SendRowDescriptionMessage(portal->tupDesc, targetlist,
1721 pq_putemptymessage('n'); /* NoData */
1726 * Convenience routines for starting/committing a single command.
1729 start_xact_command(void)
1733 elog(DEBUG3, "StartTransactionCommand");
1734 StartTransactionCommand();
1736 /* Set statement timeout running, if any */
1737 if (StatementTimeout > 0)
1738 enable_sig_alarm(StatementTimeout, true);
1740 xact_started = true;
1745 finish_xact_command(void)
1749 /* Invoke IMMEDIATE constraint triggers */
1750 DeferredTriggerEndQuery();
1752 /* Cancel any active statement timeout before committing */
1753 disable_sig_alarm(true);
1755 /* Now commit the command */
1756 elog(DEBUG3, "CommitTransactionCommand");
1758 CommitTransactionCommand();
1760 #ifdef SHOW_MEMORY_STATS
1761 /* Print mem stats at each commit for leak tracking */
1763 MemoryContextStats(TopMemoryContext);
1766 xact_started = false;
1771 /* --------------------------------
1772 * signal handler routines used in PostgresMain()
1773 * --------------------------------
1777 * quickdie() occurs when signalled SIGQUIT by the postmaster.
1779 * Some backend has bought the farm,
1780 * so we need to stop what we're doing and exit.
1783 quickdie(SIGNAL_ARGS)
1785 PG_SETMASK(&BlockSig);
1788 * Ideally this should be ereport(FATAL), but then we'd not get
1789 * control back (perhaps could fix by doing local sigsetjmp?)
1792 (errcode(ERRCODE_CRASH_SHUTDOWN),
1793 errmsg("terminating connection due to crash of another backend"),
1794 errdetail("The postmaster has commanded this backend to roll back"
1795 " the current transaction and exit, because another"
1796 " backend exited abnormally and possibly corrupted"
1798 errhint("In a moment you should be able to reconnect to the"
1799 " database and repeat your query.")));
1802 * DO NOT proc_exit() -- we're here because shared memory may be
1803 * corrupted, so we don't want to try to clean up our transaction.
1804 * Just nail the windows shut and get out of town.
1806 * Note we do exit(1) not exit(0). This is to force the postmaster into
1807 * a system reset cycle if some idiot DBA sends a manual SIGQUIT to a
1808 * random backend. This is necessary precisely because we don't clean
1809 * up our shared memory state.
1815 * Shutdown signal from postmaster: abort transaction and exit
1816 * at soonest convenient time
1821 int save_errno = errno;
1823 /* Don't joggle the elbow of proc_exit */
1824 if (!proc_exit_inprogress)
1826 InterruptPending = true;
1827 ProcDiePending = true;
1830 * If it's safe to interrupt, and we're waiting for input or a
1831 * lock, service the interrupt immediately
1833 if (ImmediateInterruptOK && InterruptHoldoffCount == 0 &&
1834 CritSectionCount == 0)
1836 /* bump holdoff count to make ProcessInterrupts() a no-op */
1837 /* until we are done getting ready for it */
1838 InterruptHoldoffCount++;
1839 DisableNotifyInterrupt();
1840 /* Make sure CheckDeadLock won't run while shutting down... */
1842 InterruptHoldoffCount--;
1843 ProcessInterrupts();
1851 * Timeout or shutdown signal from postmaster during client authentication.
1854 * XXX: possible future improvement: try to send a message indicating
1855 * why we are disconnecting. Problem is to be sure we don't block while
1856 * doing so, nor mess up the authentication message exchange.
1859 authdie(SIGNAL_ARGS)
1865 * Query-cancel signal from postmaster: abort current transaction
1866 * at soonest convenient time
1869 StatementCancelHandler(SIGNAL_ARGS)
1871 int save_errno = errno;
1874 * Don't joggle the elbow of proc_exit, nor an already-in-progress
1877 if (!proc_exit_inprogress && !InError)
1879 InterruptPending = true;
1880 QueryCancelPending = true;
1883 * If it's safe to interrupt, and we're waiting for a lock,
1884 * service the interrupt immediately. No point in interrupting if
1885 * we're waiting for input, however.
1887 if (ImmediateInterruptOK && InterruptHoldoffCount == 0 &&
1888 CritSectionCount == 0)
1890 /* bump holdoff count to make ProcessInterrupts() a no-op */
1891 /* until we are done getting ready for it */
1892 InterruptHoldoffCount++;
1893 if (LockWaitCancel())
1895 DisableNotifyInterrupt();
1896 InterruptHoldoffCount--;
1897 ProcessInterrupts();
1900 InterruptHoldoffCount--;
1907 /* signal handler for floating point exception */
1909 FloatExceptionHandler(SIGNAL_ARGS)
1912 (errcode(ERRCODE_FLOATING_POINT_EXCEPTION),
1913 errmsg("floating-point exception"),
1914 errdetail("An invalid floating-point operation was signaled. "
1915 "This probably means an out-of-range result or an "
1916 "invalid operation, such as division by zero.")));
1919 /* SIGHUP: set flag to re-read config file at next convenient time */
1921 SigHupHandler(SIGNAL_ARGS)
1928 * ProcessInterrupts: out-of-line portion of CHECK_FOR_INTERRUPTS() macro
1930 * If an interrupt condition is pending, and it's safe to service it,
1931 * then clear the flag and accept the interrupt. Called only when
1932 * InterruptPending is true.
1935 ProcessInterrupts(void)
1937 /* OK to accept interrupt now? */
1938 if (InterruptHoldoffCount != 0 || CritSectionCount != 0)
1940 InterruptPending = false;
1943 ProcDiePending = false;
1944 QueryCancelPending = false; /* ProcDie trumps QueryCancel */
1945 ImmediateInterruptOK = false; /* not idle anymore */
1946 DisableNotifyInterrupt();
1948 (errcode(ERRCODE_ADMIN_SHUTDOWN),
1949 errmsg("terminating connection due to administrator command")));
1951 if (QueryCancelPending)
1953 QueryCancelPending = false;
1954 ImmediateInterruptOK = false; /* not idle anymore */
1955 DisableNotifyInterrupt();
1957 (errcode(ERRCODE_QUERY_CANCELED),
1958 errmsg("canceling query due to user request")));
1960 /* If we get here, do nothing (probably, QueryCancelPending was reset) */
1965 usage(char *progname)
1967 printf("%s is the PostgreSQL stand-alone backend. It is not\nintended to be used by normal users.\n\n", progname);
1969 printf("Usage:\n %s [OPTION]... [DBNAME]\n\n", progname);
1970 printf("Options:\n");
1971 #ifdef USE_ASSERT_CHECKING
1972 printf(" -A 1|0 enable/disable run-time assert checking\n");
1974 printf(" -B NBUFFERS number of shared buffers (default %d)\n", DEF_NBUFFERS);
1975 printf(" -c NAME=VALUE set run-time parameter\n");
1976 printf(" -d 0-5 debugging level (0 is off)\n");
1977 printf(" -D DATADIR database directory\n");
1978 printf(" -e use European date input format (DMY)\n");
1979 printf(" -E echo query before execution\n");
1980 printf(" -F turn fsync off\n");
1981 printf(" -N do not use newline as interactive query delimiter\n");
1982 printf(" -o FILENAME send stdout and stderr to given file\n");
1983 printf(" -P disable system indexes\n");
1984 printf(" -s show statistics after each query\n");
1985 printf(" -S SORT-MEM set amount of memory for sorts (in kbytes)\n");
1986 printf(" --help-config show configuration options, then exit. Details: --help-config -h\n");
1987 printf(" --help show this help, then exit\n");
1988 printf(" --version output version information, then exit\n");
1989 printf("\nDeveloper options:\n");
1990 printf(" -f s|i|n|m|h forbid use of some plan types\n");
1991 printf(" -i do not execute queries\n");
1992 printf(" -O allow system table structure changes\n");
1993 printf(" -t pa|pl|ex show timings after each query\n");
1994 printf(" -W NUM wait NUM seconds to allow attach from a debugger\n");
1995 printf("\nReport bugs to <pgsql-bugs@postgresql.org>.\n");
2000 /* ----------------------------------------------------------------
2002 * postgres main loop -- all backends, interactive or otherwise start here
2004 * argc/argv are the command line arguments to be used. (When being forked
2005 * by the postmaster, these are not the original argv array of the process.)
2006 * username is the (possibly authenticated) PostgreSQL user name to be used
2008 * ----------------------------------------------------------------
2011 PostgresMain(int argc, char *argv[], const char *username)
2014 const char *dbname = NULL;
2015 char *potential_DataDir = NULL;
2021 GucSource gucsource;
2024 StringInfo input_message;
2025 volatile bool send_rfq = true;
2028 * Catch standard options before doing much else. This even works on
2029 * systems without getopt_long.
2031 if (!IsUnderPostmaster && argc > 1)
2033 if (strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-?") == 0)
2038 if (strcmp(argv[1], "--version") == 0 || strcmp(argv[1], "-V") == 0)
2040 puts("postgres (PostgreSQL) " PG_VERSION);
2046 * initialize globals (already done if under postmaster, but not if
2047 * standalone; cheap enough to do over)
2050 MyProcPid = getpid();
2053 * Fire up essential subsystems: error and memory management
2055 * If we are running under the postmaster, this is done already.
2057 if (!IsUnderPostmaster)
2058 MemoryContextInit();
2060 set_ps_display("startup");
2062 SetProcessingMode(InitProcessing);
2065 * Set default values for command-line options.
2070 if (!IsUnderPostmaster /* when exec || ExecBackend */ )
2072 InitializeGUCOptions();
2073 potential_DataDir = getenv("PGDATA");
2077 * parse command line arguments
2079 * There are now two styles of command line layout for the backend:
2081 * For interactive use (not started from postmaster) the format is
2082 * postgres [switches] [databasename]
2083 * If the databasename is omitted it is taken to be the user name.
2085 * When started from the postmaster, the format is
2086 * postgres [secure switches] -p databasename [insecure switches]
2087 * Switches appearing after -p came from the client (via "options"
2088 * field of connection request). For security reasons we restrict
2089 * what these switches can do.
2093 /* all options are allowed until '-p' */
2095 ctx = debug_context = PGC_POSTMASTER;
2096 gucsource = PGC_S_ARGV; /* initial switches came from command line */
2098 while ((flag = getopt(argc, argv, "A:B:c:CD:d:Eef:FiNOPo:p:S:st:v:W:x:-:")) != -1)
2102 #ifdef USE_ASSERT_CHECKING
2103 SetConfigOption("debug_assertions", optarg, ctx, gucsource);
2106 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2107 errmsg("assert checking is not compiled in")));
2114 * specify the size of buffer pool
2116 SetConfigOption("shared_buffers", optarg, ctx, gucsource);
2122 * don't print version string
2127 case 'D': /* PGDATA directory */
2129 potential_DataDir = optarg;
2132 case 'd': /* debug level */
2135 * Client option can't decrease debug level. We have
2136 * to do the test here because we group priv and
2137 * client set GUC calls below, after we know the final
2140 if (ctx != PGC_BACKEND || atoi(optarg) > debug_flag)
2142 debug_flag = atoi(optarg);
2143 debug_context = ctx; /* save context for use
2145 /* Set server debugging level. */
2146 if (debug_flag != 0)
2148 char *debugstr = palloc(strlen("debug") + strlen(optarg) + 1);
2150 sprintf(debugstr, "debug%s", optarg);
2151 SetConfigOption("log_min_messages", debugstr, ctx, gucsource);
2158 * -d0 allows user to prevent postmaster debug
2159 * from propagating to backend. It would be
2160 * nice to set it to the postgresql.conf value
2163 SetConfigOption("log_min_messages", "notice",
2172 * E - echo the query the user entered
2180 * Use European date input format (DMY)
2182 SetConfigOption("datestyle", "euro", ctx, gucsource);
2190 SetConfigOption("fsync", "false", ctx, gucsource);
2196 * f - forbid generation of certain plans
2201 case 's': /* seqscan */
2202 tmp = "enable_seqscan";
2204 case 'i': /* indexscan */
2205 tmp = "enable_indexscan";
2207 case 't': /* tidscan */
2208 tmp = "enable_tidscan";
2210 case 'n': /* nestloop */
2211 tmp = "enable_nestloop";
2213 case 'm': /* mergejoin */
2214 tmp = "enable_mergejoin";
2216 case 'h': /* hashjoin */
2217 tmp = "enable_hashjoin";
2223 SetConfigOption(tmp, "false", ctx, gucsource);
2229 * N - Don't use newline as a query delimiter
2237 * allow system table structure modifications
2239 if (secure) /* XXX safe to allow from client??? */
2240 allowSystemTableMods = true;
2246 * ignore system indexes
2248 if (secure) /* XXX safe to allow from client??? */
2249 IgnoreSystemIndexes(true);
2255 * o - send output (stdout and stderr) to the given file
2258 StrNCpy(OutputFileName, optarg, MAXPGPATH);
2264 * p - special flag passed if backend was forked by a
2272 int PMcanAcceptConnections; /* will eventually be
2276 sscanf(optarg, "%d,%d,%d,%p,", &MyProcPort->sock, &PMcanAcceptConnections,
2277 &UsedShmemSegID, &UsedShmemSegAddr);
2278 /* Grab dbname as last param */
2279 for (i = 0, p = optarg - 1; i < 4 && p; i++)
2280 p = strchr(p + 1, ',');
2282 dbname = strdup(p + 1);
2284 dbname = strdup(optarg);
2286 secure = false; /* subsequent switches are NOT
2289 gucsource = PGC_S_CLIENT;
2296 * S - amount of sort memory to use in 1k bytes
2298 SetConfigOption("sort_mem", optarg, ctx, gucsource);
2304 * s - report usage statistics (timings) after each query
2306 SetConfigOption("show_statement_stats", "true", ctx, gucsource);
2311 * tell postgres to report usage statistics (timings) for
2314 * -tpa[rser] = print stats for parser time of each query
2315 * -tpl[anner] = print stats for planner time of each query
2316 * -te[xecutor] = print stats for executor time of each query
2317 * caution: -s can not be used together with -t.
2324 if (optarg[1] == 'a')
2325 tmp = "log_parser_stats";
2326 else if (optarg[1] == 'l')
2327 tmp = "log_planner_stats";
2332 tmp = "show_executor_stats";
2339 SetConfigOption(tmp, "true", ctx, gucsource);
2344 FrontendProtocol = (ProtocolVersion) atoi(optarg);
2350 * wait N seconds to allow attach from a debugger
2352 sleep(atoi(optarg));
2356 #ifdef NOT_USED /* planner/xfunc.h */
2359 * control joey hellerstein's expensive function
2364 elog(WARNING, "only one -x flag is allowed");
2368 if (strcmp(optarg, "off") == 0)
2369 XfuncMode = XFUNC_OFF;
2370 else if (strcmp(optarg, "nor") == 0)
2371 XfuncMode = XFUNC_NOR;
2372 else if (strcmp(optarg, "nopull") == 0)
2373 XfuncMode = XFUNC_NOPULL;
2374 else if (strcmp(optarg, "nopm") == 0)
2375 XfuncMode = XFUNC_NOPM;
2376 else if (strcmp(optarg, "pullall") == 0)
2377 XfuncMode = XFUNC_PULLALL;
2378 else if (strcmp(optarg, "wait") == 0)
2379 XfuncMode = XFUNC_WAIT;
2382 elog(WARNING, "use -x {off,nor,nopull,nopm,pullall,wait}");
2394 ParseLongOption(optarg, &name, &value);
2399 (errcode(ERRCODE_SYNTAX_ERROR),
2400 errmsg("--%s requires a value",
2404 (errcode(ERRCODE_SYNTAX_ERROR),
2405 errmsg("-c %s requires a value",
2409 SetConfigOption(name, value, ctx, gucsource);
2423 * -d is not the same as setting log_min_messages because it enables
2424 * other output options.
2426 if (debug_flag >= 1)
2427 SetConfigOption("log_connections", "true", debug_context, gucsource);
2428 if (debug_flag >= 2)
2429 SetConfigOption("log_statement", "true", debug_context, gucsource);
2430 if (debug_flag >= 3)
2431 SetConfigOption("debug_print_parse", "true", debug_context, gucsource);
2432 if (debug_flag >= 4)
2433 SetConfigOption("debug_print_plan", "true", debug_context, gucsource);
2434 if (debug_flag >= 5)
2435 SetConfigOption("debug_print_rewritten", "true", debug_context, gucsource);
2438 * Process any additional GUC variable settings passed in startup
2441 if (MyProcPort != NULL)
2443 List *gucopts = MyProcPort->guc_options;
2450 name = lfirst(gucopts);
2451 gucopts = lnext(gucopts);
2452 value = lfirst(gucopts);
2453 gucopts = lnext(gucopts);
2454 SetConfigOption(name, value, PGC_BACKEND, PGC_S_CLIENT);
2459 * Post-processing for command line options.
2461 if (log_statement_stats &&
2462 (log_parser_stats || log_planner_stats || log_executor_stats))
2465 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
2466 errmsg("query-level statistics are disabled because parser, planner, or executor statistics are on")));
2467 SetConfigOption("show_statement_stats", "false", ctx, gucsource);
2470 if (!IsUnderPostmaster)
2472 if (!potential_DataDir)
2475 gettext("%s does not know where to find the database system data.\n"
2476 "You must specify the directory that contains the database system\n"
2477 "either by specifying the -D invocation option or by setting the\n"
2478 "PGDATA environment variable.\n"),
2482 SetDataDir(potential_DataDir);
2487 read_nondefault_variables();
2491 * Set up signal handlers and masks.
2493 * Note that postmaster blocked all signals before forking child process,
2494 * so there is no race condition whereby we might receive a signal
2495 * before we have set up the handler.
2497 * Also note: it's best not to use any signals that are SIG_IGNored in
2498 * the postmaster. If such a signal arrives before we are able to
2499 * change the handler to non-SIG_IGN, it'll get dropped. Instead,
2500 * make a dummy handler in the postmaster to reserve the signal. (Of
2501 * course, this isn't an issue for signals that are locally generated,
2502 * such as SIGALRM and SIGPIPE.)
2505 pqsignal(SIGHUP, SigHupHandler); /* set flag to read config file */
2506 pqsignal(SIGINT, StatementCancelHandler); /* cancel current query */
2507 pqsignal(SIGTERM, die); /* cancel current query and exit */
2508 pqsignal(SIGQUIT, quickdie); /* hard crash time */
2509 pqsignal(SIGALRM, handle_sig_alarm); /* timeout conditions */
2512 * Ignore failure to write to frontend. Note: if frontend closes
2513 * connection, we will notice it and exit cleanly when control next
2514 * returns to outer loop. This seems safer than forcing exit in the
2515 * midst of output during who-knows-what operation...
2517 pqsignal(SIGPIPE, SIG_IGN);
2518 pqsignal(SIGUSR1, SIG_IGN); /* this signal available for use */
2520 pqsignal(SIGUSR2, Async_NotifyHandler); /* flush also sinval cache */
2521 pqsignal(SIGFPE, FloatExceptionHandler);
2524 * Reset some signals that are accepted by postmaster but not by
2527 pqsignal(SIGCHLD, SIG_DFL); /* system() requires this on some
2532 /* We allow SIGQUIT (quickdie) at all times */
2533 #ifdef HAVE_SIGPROCMASK
2534 sigdelset(&BlockSig, SIGQUIT);
2536 BlockSig &= ~(sigmask(SIGQUIT));
2539 PG_SETMASK(&BlockSig); /* block everything except SIGQUIT */
2542 if (IsUnderPostmaster)
2544 /* noninteractive case: nothing should be left after switches */
2545 if (errs || argc != optind || dbname == NULL)
2548 (errcode(ERRCODE_SYNTAX_ERROR),
2549 errmsg("invalid backend command-line arguments"),
2550 errhint("Try -? for help.")));
2554 AttachSharedMemoryAndSemaphores();
2559 /* interactive case: database name can be last arg on command line */
2560 if (errs || argc - optind > 1)
2563 (errcode(ERRCODE_SYNTAX_ERROR),
2564 errmsg("%s: invalid command-line arguments",
2566 errhint("Try -? for help.")));
2568 else if (argc - optind == 1)
2569 dbname = argv[optind];
2570 else if ((dbname = username) == NULL)
2573 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
2574 errmsg("%s: no database nor user name specified",
2579 * On some systems our dynloader code needs the executable's
2580 * pathname. (If under postmaster, this was done already.)
2582 if (FindExec(pg_pathname, argv[0], "postgres") < 0)
2584 (errmsg("%s: could not locate postgres executable",
2588 * Validate we have been given a reasonable-looking DataDir (if
2589 * under postmaster, assume postmaster did this already).
2591 ValidatePgVersion(DataDir);
2594 * Create lockfile for data directory.
2596 CreateDataDirLockFile(DataDir, false);
2602 * Start up xlog for standalone backend, and register to have it
2603 * closed down at exit.
2606 on_shmem_exit(ShutdownXLOG, 0);
2609 * Read any existing FSM cache file, and register to write one out
2613 on_shmem_exit(DumpFreeSpaceMap, 0);
2617 * Set up additional info.
2625 * General initialization.
2627 * NOTE: if you are tempted to add code in this vicinity, consider
2628 * putting it inside InitPostgres() instead. In particular, anything
2629 * that involves database access should be there, not here.
2631 elog(DEBUG3, "InitPostgres");
2632 InitPostgres(dbname, username);
2634 SetProcessingMode(NormalProcessing);
2637 * Send this backend's cancellation info to the frontend.
2639 if (whereToSendOutput == Remote &&
2640 PG_PROTOCOL_MAJOR(FrontendProtocol) >= 2)
2644 pq_beginmessage(&buf, 'K');
2645 pq_sendint(&buf, (int32) MyProcPid, sizeof(int32));
2646 pq_sendint(&buf, (int32) MyCancelKey, sizeof(int32));
2647 pq_endmessage(&buf);
2648 /* Need not flush since ReadyForQuery will do it. */
2651 if (!IsUnderPostmaster)
2653 puts("\nPOSTGRES backend interactive interface ");
2654 puts("$Revision: 1.354 $ $Date: 2003/08/04 00:43:25 $\n");
2658 * Create the memory context we will use in the main loop.
2660 * MessageContext is reset once per iteration of the main loop, ie, upon
2661 * completion of processing of each command message from the client.
2663 MessageContext = AllocSetContextCreate(TopMemoryContext,
2665 ALLOCSET_DEFAULT_MINSIZE,
2666 ALLOCSET_DEFAULT_INITSIZE,
2667 ALLOCSET_DEFAULT_MAXSIZE);
2670 * Tell the statistics collector that we're alive and
2671 * to which database we belong.
2677 * POSTGRES main processing loop begins here
2679 * If an exception is encountered, processing resumes here so we abort
2680 * the current transaction and start a new one.
2683 if (sigsetjmp(Warn_restart, 1) != 0)
2686 * NOTE: if you are tempted to add more code in this if-block,
2687 * consider the probability that it should be in
2688 * AbortTransaction() instead.
2690 * Make sure we're not interrupted while cleaning up. Also forget
2691 * any pending QueryCancel request, since we're aborting anyway.
2692 * Force InterruptHoldoffCount to a known state in case we
2693 * ereport'd from inside a holdoff section.
2695 ImmediateInterruptOK = false;
2696 QueryCancelPending = false;
2697 InterruptHoldoffCount = 1;
2698 CritSectionCount = 0; /* should be unnecessary, but... */
2699 disable_sig_alarm(true);
2700 QueryCancelPending = false; /* again in case timeout occurred */
2701 DisableNotifyInterrupt();
2702 debug_query_string = NULL;
2705 * Make sure we are in a valid memory context during recovery.
2707 * We use ErrorContext in hopes that it will have some free space
2708 * even if we're otherwise up against it...
2710 MemoryContextSwitchTo(ErrorContext);
2712 /* Do the recovery */
2713 elog(DEBUG2, "AbortCurrentTransaction");
2714 AbortCurrentTransaction();
2717 * Now return to normal top-level context and clear ErrorContext
2720 MemoryContextSwitchTo(TopMemoryContext);
2721 MemoryContextResetAndDeleteChildren(ErrorContext);
2722 PortalContext = NULL;
2723 QueryContext = NULL;
2726 * Clear flag to indicate that we got out of error recovery mode
2727 * successfully. (Flag was set in elog.c before longjmp().)
2730 xact_started = false;
2733 * If we were handling an extended-query-protocol message,
2734 * initiate skip till next Sync. This also causes us not to issue
2735 * ReadyForQuery (until we get Sync).
2737 if (doing_extended_query_message)
2738 ignore_till_sync = true;
2741 * Exit interrupt holdoff section we implicitly established above.
2743 RESUME_INTERRUPTS();
2746 Warn_restart_ready = true; /* we can now handle ereport(ERROR) */
2748 PG_SETMASK(&UnBlockSig);
2750 if (!ignore_till_sync)
2751 send_rfq = true; /* initially, or after error */
2754 * Non-error queries loop here.
2760 * At top of loop, reset extended-query-message flag, so that any
2761 * errors encountered in "idle" state don't provoke skip.
2763 doing_extended_query_message = false;
2766 * Release storage left over from prior query cycle, and create a
2767 * new query input buffer in the cleared MessageContext.
2769 MemoryContextSwitchTo(MessageContext);
2770 MemoryContextResetAndDeleteChildren(MessageContext);
2772 input_message = makeStringInfo();
2775 * (1) tell the frontend we're ready for a new query.
2777 * Note: this includes fflush()'ing the last of the prior output.
2781 ReadyForQuery(whereToSendOutput);
2786 * Tell the statistics collector what we've collected
2790 pgstat_report_tabstat();
2792 if (IsTransactionBlock())
2794 set_ps_display("idle in transaction");
2795 pgstat_report_activity("<IDLE> in transaction");
2799 set_ps_display("idle");
2800 pgstat_report_activity("<IDLE>");
2804 * (2) deal with pending asynchronous NOTIFY from other backends,
2805 * and enable async.c's signal handler to execute NOTIFY directly.
2806 * Then set up other stuff needed before blocking for input.
2808 QueryCancelPending = false; /* forget any earlier CANCEL
2811 EnableNotifyInterrupt();
2813 /* Allow "die" interrupt to be processed while waiting */
2814 ImmediateInterruptOK = true;
2815 /* and don't forget to detect one that already arrived */
2816 QueryCancelPending = false;
2817 CHECK_FOR_INTERRUPTS();
2820 * (3) read a command (loop blocks here)
2822 firstchar = ReadCommand(input_message);
2825 * (4) disable async signal conditions again.
2827 ImmediateInterruptOK = false;
2828 QueryCancelPending = false; /* forget any CANCEL signal */
2830 DisableNotifyInterrupt();
2833 * (5) check for any other interesting events that happened while
2839 ProcessConfigFile(PGC_SIGHUP);
2843 * (6) process the command. But ignore it if we're skipping till
2846 if (ignore_till_sync && firstchar != EOF)
2851 case 'Q': /* simple query */
2853 const char *query_string;
2855 query_string = pq_getmsgstring(input_message);
2856 pq_getmsgend(input_message);
2858 exec_simple_query(query_string);
2864 case 'P': /* parse */
2866 const char *stmt_name;
2867 const char *query_string;
2869 Oid *paramTypes = NULL;
2871 stmt_name = pq_getmsgstring(input_message);
2872 query_string = pq_getmsgstring(input_message);
2873 numParams = pq_getmsgint(input_message, 2);
2878 paramTypes = (Oid *) palloc(numParams * sizeof(Oid));
2879 for (i = 0; i < numParams; i++)
2880 paramTypes[i] = pq_getmsgint(input_message, 4);
2882 pq_getmsgend(input_message);
2884 exec_parse_message(query_string, stmt_name,
2885 paramTypes, numParams);
2889 case 'B': /* bind */
2892 * this message is complex enough that it seems best to
2893 * put the field extraction out-of-line
2895 exec_bind_message(input_message);
2898 case 'E': /* execute */
2900 const char *portal_name;
2903 portal_name = pq_getmsgstring(input_message);
2904 max_rows = pq_getmsgint(input_message, 4);
2905 pq_getmsgend(input_message);
2907 exec_execute_message(portal_name, max_rows);
2911 case 'F': /* fastpath function call */
2912 /* Tell the collector what we're doing */
2913 pgstat_report_activity("<FASTPATH> function call");
2915 /* start an xact for this function invocation */
2916 start_xact_command();
2918 /* switch back to message context */
2919 MemoryContextSwitchTo(MessageContext);
2921 if (HandleFunctionRequest(input_message) == EOF)
2923 /* lost frontend connection during F message input */
2926 * Reset whereToSendOutput to prevent ereport from
2927 * attempting to send any more messages to client.
2929 if (whereToSendOutput == Remote)
2930 whereToSendOutput = None;
2935 /* commit the function-invocation transaction */
2936 finish_xact_command();
2941 case 'C': /* close */
2944 const char *close_target;
2946 close_type = pq_getmsgbyte(input_message);
2947 close_target = pq_getmsgstring(input_message);
2948 pq_getmsgend(input_message);
2953 if (close_target[0] != '\0')
2954 DropPreparedStatement(close_target, false);
2957 /* special-case the unnamed statement */
2958 unnamed_stmt_pstmt = NULL;
2959 if (unnamed_stmt_context)
2961 DropDependentPortals(unnamed_stmt_context);
2962 MemoryContextDelete(unnamed_stmt_context);
2964 unnamed_stmt_context = NULL;
2971 portal = GetPortalByName(close_target);
2972 if (PortalIsValid(portal))
2973 PortalDrop(portal, false);
2978 (errcode(ERRCODE_PROTOCOL_VIOLATION),
2979 errmsg("invalid CLOSE message subtype %d",
2984 if (whereToSendOutput == Remote)
2985 pq_putemptymessage('3'); /* CloseComplete */
2989 case 'D': /* describe */
2992 const char *describe_target;
2994 describe_type = pq_getmsgbyte(input_message);
2995 describe_target = pq_getmsgstring(input_message);
2996 pq_getmsgend(input_message);
2998 switch (describe_type)
3001 exec_describe_statement_message(describe_target);
3004 exec_describe_portal_message(describe_target);
3008 (errcode(ERRCODE_PROTOCOL_VIOLATION),
3009 errmsg("invalid DESCRIBE message subtype %d",
3016 case 'H': /* flush */
3017 pq_getmsgend(input_message);
3018 if (whereToSendOutput == Remote)
3022 case 'S': /* sync */
3023 pq_getmsgend(input_message);
3024 finish_xact_command();
3029 * 'X' means that the frontend is closing down the socket.
3030 * EOF means unexpected loss of frontend connection.
3031 * Either way, perform normal shutdown.
3037 * Reset whereToSendOutput to prevent ereport from
3038 * attempting to send any more messages to client.
3040 if (whereToSendOutput == Remote)
3041 whereToSendOutput = None;
3044 * NOTE: if you are tempted to add more code here, DON'T!
3045 * Whatever you had in mind to do should be set up as an
3046 * on_proc_exit or on_shmem_exit callback, instead.
3047 * Otherwise it will fail to be called during other
3048 * backend-shutdown scenarios.
3052 case 'd': /* copy data */
3053 case 'c': /* copy done */
3054 case 'f': /* copy fail */
3057 * Accept but ignore these messages, per protocol spec; we
3058 * probably got here because a COPY failed, and the
3059 * frontend is still sending data.
3065 (errcode(ERRCODE_PROTOCOL_VIOLATION),
3066 errmsg("invalid frontend message type %d",
3070 #ifdef MEMORY_CONTEXT_CHECKING
3073 * Check all memory after each backend loop. This is a rather
3074 * weird place to do it, perhaps.
3076 MemoryContextCheck(TopMemoryContext);
3078 } /* end of input-reading loop */
3080 /* can't get here because the above loop never exits */
3083 return 1; /* keep compiler quiet */
3086 #ifndef HAVE_GETRUSAGE
3087 #include "rusagestub.h"
3089 #include <sys/resource.h>
3090 #endif /* HAVE_GETRUSAGE */
3092 struct rusage Save_r;
3093 struct timeval Save_t;
3098 getrusage(RUSAGE_SELF, &Save_r);
3099 gettimeofday(&Save_t, NULL);
3101 /* ResetTupleCount(); */
3105 ShowUsage(const char *title)
3108 struct timeval user,
3110 struct timeval elapse_t;
3114 getrusage(RUSAGE_SELF, &r);
3115 gettimeofday(&elapse_t, NULL);
3116 memcpy((char *) &user, (char *) &r.ru_utime, sizeof(user));
3117 memcpy((char *) &sys, (char *) &r.ru_stime, sizeof(sys));
3118 if (elapse_t.tv_usec < Save_t.tv_usec)
3121 elapse_t.tv_usec += 1000000;
3123 if (r.ru_utime.tv_usec < Save_r.ru_utime.tv_usec)
3125 r.ru_utime.tv_sec--;
3126 r.ru_utime.tv_usec += 1000000;
3128 if (r.ru_stime.tv_usec < Save_r.ru_stime.tv_usec)
3130 r.ru_stime.tv_sec--;
3131 r.ru_stime.tv_usec += 1000000;
3135 * the only stats we don't show here are for memory usage -- i can't
3136 * figure out how to interpret the relevant fields in the rusage
3137 * struct, and they change names across o/s platforms, anyway. if you
3138 * can figure out what the entries mean, you can somehow extract
3139 * resident set size, shared text size, and unshared data and stack
3142 initStringInfo(&str);
3144 appendStringInfo(&str, "! system usage stats:\n");
3145 appendStringInfo(&str,
3146 "!\t%ld.%06ld elapsed %ld.%06ld user %ld.%06ld system sec\n",
3147 (long) (elapse_t.tv_sec - Save_t.tv_sec),
3148 (long) (elapse_t.tv_usec - Save_t.tv_usec),
3149 (long) (r.ru_utime.tv_sec - Save_r.ru_utime.tv_sec),
3150 (long) (r.ru_utime.tv_usec - Save_r.ru_utime.tv_usec),
3151 (long) (r.ru_stime.tv_sec - Save_r.ru_stime.tv_sec),
3152 (long) (r.ru_stime.tv_usec - Save_r.ru_stime.tv_usec));
3153 appendStringInfo(&str,
3154 "!\t[%ld.%06ld user %ld.%06ld sys total]\n",
3156 (long) user.tv_usec,
3158 (long) sys.tv_usec);
3159 /* BeOS has rusage but only has some fields, and not these... */
3160 #if defined(HAVE_GETRUSAGE)
3161 appendStringInfo(&str,
3162 "!\t%ld/%ld [%ld/%ld] filesystem blocks in/out\n",
3163 r.ru_inblock - Save_r.ru_inblock,
3164 /* they only drink coffee at dec */
3165 r.ru_oublock - Save_r.ru_oublock,
3166 r.ru_inblock, r.ru_oublock);
3167 appendStringInfo(&str,
3168 "!\t%ld/%ld [%ld/%ld] page faults/reclaims, %ld [%ld] swaps\n",
3169 r.ru_majflt - Save_r.ru_majflt,
3170 r.ru_minflt - Save_r.ru_minflt,
3171 r.ru_majflt, r.ru_minflt,
3172 r.ru_nswap - Save_r.ru_nswap,
3174 appendStringInfo(&str,
3175 "!\t%ld [%ld] signals rcvd, %ld/%ld [%ld/%ld] messages rcvd/sent\n",
3176 r.ru_nsignals - Save_r.ru_nsignals,
3178 r.ru_msgrcv - Save_r.ru_msgrcv,
3179 r.ru_msgsnd - Save_r.ru_msgsnd,
3180 r.ru_msgrcv, r.ru_msgsnd);
3181 appendStringInfo(&str,
3182 "!\t%ld/%ld [%ld/%ld] voluntary/involuntary context switches\n",
3183 r.ru_nvcsw - Save_r.ru_nvcsw,
3184 r.ru_nivcsw - Save_r.ru_nivcsw,
3185 r.ru_nvcsw, r.ru_nivcsw);
3186 #endif /* HAVE_GETRUSAGE */
3188 bufusage = ShowBufferUsage();
3189 appendStringInfo(&str, "! buffer usage stats:\n%s", bufusage);
3192 /* remove trailing newline */
3193 if (str.data[str.len - 1] == '\n')
3194 str.data[--str.len] = '\0';
3197 (errmsg_internal("%s", title),
3198 errdetail("%s", str.data)));