1 /*-------------------------------------------------------------------------
4 * POSTGRES C Backend Interface
6 * Portions Copyright (c) 1996-2003, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
11 * $PostgreSQL: pgsql/src/backend/tcop/postgres.c,v 1.379 2003/12/01 22:15:37 tgl 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("statement: %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))
562 elog(WARNING, "copyObject() failed to produce an equal parse tree");
564 querytree_list = new_list;
567 if (Debug_print_rewritten)
568 elog_node_display(DEBUG1, "rewritten parse tree", querytree_list,
571 return querytree_list;
575 /* Generate a plan for a single already-rewritten query. */
577 pg_plan_query(Query *querytree)
581 /* Utility commands have no plans. */
582 if (querytree->commandType == CMD_UTILITY)
585 if (log_planner_stats)
588 /* call the optimizer */
589 plan = planner(querytree, false, 0);
591 if (log_planner_stats)
592 ShowUsage("PLANNER STATISTICS");
594 #ifdef COPY_PARSE_PLAN_TREES
595 /* Optional debugging check: pass plan output through copyObject() */
597 Plan *new_plan = (Plan *) copyObject(plan);
600 * equal() currently does not have routines to compare Plan nodes,
601 * so don't try to test equality here. Perhaps fix someday?
604 /* This checks both copyObject() and the equal() routines... */
605 if (!equal(new_plan, plan))
606 elog(WARNING, "copyObject() failed to produce an equal plan tree");
614 * Print plan if debugging.
616 if (Debug_print_plan)
617 elog_node_display(DEBUG1, "plan", plan, Debug_pretty_print);
623 * Generate plans for a list of already-rewritten queries.
625 * If needSnapshot is TRUE, we haven't yet set a snapshot for the current
626 * query. A snapshot must be set before invoking the planner, since it
627 * might try to evaluate user-defined functions. But we must not set a
628 * snapshot if the list contains only utility statements, because some
629 * utility statements depend on not having frozen the snapshot yet.
630 * (We assume that such statements cannot appear together with plannable
631 * statements in the rewriter's output.)
634 pg_plan_queries(List *querytrees, bool needSnapshot)
636 List *plan_list = NIL;
639 foreach(query_list, querytrees)
641 Query *query = (Query *) lfirst(query_list);
644 if (query->commandType == CMD_UTILITY)
646 /* Utility commands have no plans. */
654 needSnapshot = false;
656 plan = pg_plan_query(query);
659 plan_list = lappend(plan_list, plan);
669 * Execute a "simple Query" protocol message.
672 exec_simple_query(const char *query_string)
674 CommandDest dest = whereToSendOutput;
675 MemoryContext oldcontext;
676 List *parsetree_list,
678 struct timeval start_t,
680 bool save_log_duration = log_duration;
681 int save_log_min_duration_statement = log_min_duration_statement;
682 bool save_log_statement_stats = log_statement_stats;
685 * Report query to various monitoring facilities.
687 debug_query_string = query_string;
689 pgstat_report_activity(query_string);
692 * We use save_log_* so "SET log_duration = true" and "SET
693 * log_min_duration_statement = true" don't report incorrect time
694 * because gettimeofday() wasn't called. Similarly,
695 * log_statement_stats has to be captured once.
697 if (save_log_duration || save_log_min_duration_statement != -1)
698 gettimeofday(&start_t, NULL);
700 if (save_log_statement_stats)
704 * Start up a transaction command. All queries generated by the
705 * query_string will be in this same command block, *unless* we find a
706 * BEGIN/COMMIT/ABORT statement; we have to force a new xact command
707 * after one of those, else bad things will happen in xact.c. (Note
708 * that this will normally change current memory context.)
710 start_xact_command();
713 * Zap any pre-existing unnamed statement. (While not strictly
714 * necessary, it seems best to define simple-Query mode as if it used
715 * the unnamed statement and portal; this ensures we recover any
716 * storage used by prior unnamed operations.)
718 unnamed_stmt_pstmt = NULL;
719 if (unnamed_stmt_context)
721 DropDependentPortals(unnamed_stmt_context);
722 MemoryContextDelete(unnamed_stmt_context);
724 unnamed_stmt_context = NULL;
727 * Switch to appropriate context for constructing parsetrees.
729 oldcontext = MemoryContextSwitchTo(MessageContext);
731 QueryContext = CurrentMemoryContext;
734 * Do basic parsing of the query or queries (this should be safe even
735 * if we are in aborted transaction state!)
737 parsetree_list = pg_parse_query(query_string);
740 * Switch back to transaction context to enter the loop.
742 MemoryContextSwitchTo(oldcontext);
745 * Run through the raw parsetree(s) and process each one.
747 foreach(parsetree_item, parsetree_list)
749 Node *parsetree = (Node *) lfirst(parsetree_item);
750 const char *commandTag;
751 char completionTag[COMPLETION_TAG_BUFSIZE];
752 List *querytree_list,
755 DestReceiver *receiver;
759 * Get the command name for use in status display (it also becomes
760 * the default completion tag, down inside PortalRun). Set
761 * ps_status and do any special start-of-SQL-command processing
762 * needed by the destination.
764 commandTag = CreateCommandTag(parsetree);
766 set_ps_display(commandTag);
768 BeginCommand(commandTag, dest);
771 * If we are in an aborted transaction, reject all commands except
772 * COMMIT/ABORT. It is important that this test occur before we
773 * try to do parse analysis, rewrite, or planning, since all those
774 * phases try to do database accesses, which may fail in abort
775 * state. (It might be safe to allow some additional utility
776 * commands in this state, but not many...)
778 if (IsAbortedTransactionBlockState())
780 bool allowit = false;
782 if (IsA(parsetree, TransactionStmt))
784 TransactionStmt *stmt = (TransactionStmt *) parsetree;
786 if (stmt->kind == TRANS_STMT_COMMIT ||
787 stmt->kind == TRANS_STMT_ROLLBACK)
793 (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
794 errmsg("current transaction is aborted, "
795 "commands ignored until end of transaction block")));
798 /* Make sure we are in a transaction command */
799 start_xact_command();
801 /* If we got a cancel signal in parsing or prior command, quit */
802 CHECK_FOR_INTERRUPTS();
805 * OK to analyze, rewrite, and plan this query.
807 * Switch to appropriate context for constructing querytrees (again,
808 * these must outlive the execution context).
810 oldcontext = MemoryContextSwitchTo(MessageContext);
812 querytree_list = pg_analyze_and_rewrite(parsetree, NULL, 0);
814 plantree_list = pg_plan_queries(querytree_list, true);
816 /* If we got a cancel signal in analysis or planning, quit */
817 CHECK_FOR_INTERRUPTS();
820 * Create unnamed portal to run the query or queries in. If there
821 * already is one, silently drop it.
823 portal = CreatePortal("", true, true);
825 PortalDefineQuery(portal,
833 * Start the portal. No parameters here.
835 PortalStart(portal, NULL);
838 * Select the appropriate output format: text unless we are doing
839 * a FETCH from a binary cursor. (Pretty grotty to have to do
840 * this here --- but it avoids grottiness in other places. Ah,
841 * the joys of backward compatibility...)
843 format = 0; /* TEXT is default */
844 if (IsA(parsetree, FetchStmt))
846 FetchStmt *stmt = (FetchStmt *) parsetree;
850 Portal fportal = GetPortalByName(stmt->portalname);
852 if (PortalIsValid(fportal) &&
853 (fportal->cursorOptions & CURSOR_OPT_BINARY))
854 format = 1; /* BINARY */
857 PortalSetResultFormat(portal, 1, &format);
860 * Now we can create the destination receiver object.
862 receiver = CreateDestReceiver(dest, portal);
865 * Switch back to transaction context for execution.
867 MemoryContextSwitchTo(oldcontext);
870 * Run the portal to completion, and then drop it (and the
873 (void) PortalRun(portal,
879 (*receiver->rDestroy) (receiver);
881 PortalDrop(portal, false);
883 if (IsA(parsetree, TransactionStmt))
886 * If this was a transaction control statement, commit it. We
887 * will start a new xact command for the next command (if
890 finish_xact_command();
892 else if (lnext(parsetree_item) == NIL)
895 * If this is the last parsetree of the query string, close
896 * down transaction statement before reporting
897 * command-complete. This is so that any end-of-transaction
898 * errors are reported before the command-complete message is
899 * issued, to avoid confusing clients who will expect either a
900 * command-complete message or an error, not one and then the
901 * other. But for compatibility with historical Postgres
902 * behavior, we do not force a transaction boundary between
903 * queries appearing in a single query string.
905 finish_xact_command();
910 * We need a CommandCounterIncrement after every query, except
911 * those that start or end a transaction block.
913 CommandCounterIncrement();
917 * Tell client that we're done with this query. Note we emit
918 * exactly one EndCommand report for each raw parsetree, thus one
919 * for each SQL command the client sent, regardless of rewriting.
920 * (But a command aborted by error will not send an EndCommand
923 EndCommand(completionTag, dest);
924 } /* end loop over parsetrees */
927 * Close down transaction statement, if one is open.
929 finish_xact_command();
932 * If there were no parsetrees, return EmptyQueryResponse message.
940 * Combine processing here as we need to calculate the query duration
943 if (save_log_duration || save_log_min_duration_statement != -1)
947 gettimeofday(&stop_t, NULL);
948 if (stop_t.tv_usec < start_t.tv_usec)
951 stop_t.tv_usec += 1000000;
953 usecs = (long) (stop_t.tv_sec - start_t.tv_sec) * 1000000 + (long) (stop_t.tv_usec - start_t.tv_usec);
955 if (save_log_duration)
957 (errmsg("duration: %ld.%03ld ms",
958 (long) ((stop_t.tv_sec - start_t.tv_sec) * 1000 +
959 (stop_t.tv_usec - start_t.tv_usec) / 1000),
960 (long) (stop_t.tv_usec - start_t.tv_usec) % 1000)));
963 * Output a duration_statement to the log if the query has exceeded
964 * the min duration, or if we are to print all durations.
966 if (save_log_min_duration_statement == 0 ||
967 (save_log_min_duration_statement > 0 &&
968 usecs >= save_log_min_duration_statement * 1000))
970 (errmsg("duration: %ld.%03ld ms statement: %s",
971 (long) ((stop_t.tv_sec - start_t.tv_sec) * 1000 +
972 (stop_t.tv_usec - start_t.tv_usec) / 1000),
973 (long) (stop_t.tv_usec - start_t.tv_usec) % 1000,
977 if (save_log_statement_stats)
978 ShowUsage("QUERY STATISTICS");
980 debug_query_string = NULL;
986 * Execute a "Parse" protocol message.
989 exec_parse_message(const char *query_string, /* string to execute */
990 const char *stmt_name, /* name for prepared stmt */
991 Oid *paramTypes, /* parameter types */
992 int numParams) /* number of parameters */
994 MemoryContext oldcontext;
995 List *parsetree_list;
996 const char *commandTag;
997 List *querytree_list,
1001 bool save_log_statement_stats = log_statement_stats;
1004 * Report query to various monitoring facilities.
1006 debug_query_string = query_string;
1008 pgstat_report_activity(query_string);
1010 set_ps_display("PARSE");
1012 if (save_log_statement_stats)
1016 * Start up a transaction command so we can run parse analysis etc.
1017 * (Note that this will normally change current memory context.)
1018 * Nothing happens if we are already in one.
1020 start_xact_command();
1023 * Switch to appropriate context for constructing parsetrees.
1025 * We have two strategies depending on whether the prepared statement is
1026 * named or not. For a named prepared statement, we do parsing in
1027 * MessageContext and copy the finished trees into the prepared
1028 * statement's private context; then the reset of MessageContext
1029 * releases temporary space used by parsing and planning. For an
1030 * unnamed prepared statement, we assume the statement isn't going to
1031 * hang around long, so getting rid of temp space quickly is probably
1032 * not worth the costs of copying parse/plan trees. So in this case,
1033 * we set up a special context for the unnamed statement, and do all
1034 * the parsing/planning therein.
1036 is_named = (stmt_name[0] != '\0');
1039 /* Named prepared statement --- parse in MessageContext */
1040 oldcontext = MemoryContextSwitchTo(MessageContext);
1044 /* Unnamed prepared statement --- release any prior unnamed stmt */
1045 unnamed_stmt_pstmt = NULL;
1046 if (unnamed_stmt_context)
1048 DropDependentPortals(unnamed_stmt_context);
1049 MemoryContextDelete(unnamed_stmt_context);
1051 unnamed_stmt_context = NULL;
1052 /* create context for parsing/planning */
1053 unnamed_stmt_context =
1054 AllocSetContextCreate(TopMemoryContext,
1055 "unnamed prepared statement",
1056 ALLOCSET_DEFAULT_MINSIZE,
1057 ALLOCSET_DEFAULT_INITSIZE,
1058 ALLOCSET_DEFAULT_MAXSIZE);
1059 oldcontext = MemoryContextSwitchTo(unnamed_stmt_context);
1062 QueryContext = CurrentMemoryContext;
1065 * Do basic parsing of the query or queries (this should be safe even
1066 * if we are in aborted transaction state!)
1068 parsetree_list = pg_parse_query(query_string);
1071 * We only allow a single user statement in a prepared statement. This
1072 * is mainly to keep the protocol simple --- otherwise we'd need to
1073 * worry about multiple result tupdescs and things like that.
1075 if (length(parsetree_list) > 1)
1077 (errcode(ERRCODE_SYNTAX_ERROR),
1078 errmsg("cannot insert multiple commands into a prepared statement")));
1080 if (parsetree_list != NIL)
1082 Node *parsetree = (Node *) lfirst(parsetree_list);
1086 * Get the command name for possible use in status display.
1088 commandTag = CreateCommandTag(parsetree);
1091 * If we are in an aborted transaction, reject all commands except
1092 * COMMIT/ROLLBACK. It is important that this test occur before
1093 * we try to do parse analysis, rewrite, or planning, since all
1094 * those phases try to do database accesses, which may fail in
1095 * abort state. (It might be safe to allow some additional utility
1096 * commands in this state, but not many...)
1098 if (IsAbortedTransactionBlockState())
1100 bool allowit = false;
1102 if (IsA(parsetree, TransactionStmt))
1104 TransactionStmt *stmt = (TransactionStmt *) parsetree;
1106 if (stmt->kind == TRANS_STMT_COMMIT ||
1107 stmt->kind == TRANS_STMT_ROLLBACK)
1113 (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
1114 errmsg("current transaction is aborted, "
1115 "commands ignored until end of transaction block")));
1119 * OK to analyze, rewrite, and plan this query. Note that the
1120 * originally specified parameter set is not required to be
1121 * complete, so we have to use parse_analyze_varparams().
1123 if (log_parser_stats)
1126 querytree_list = parse_analyze_varparams(parsetree,
1131 * Check all parameter types got determined, and convert array
1132 * representation to a list for storage.
1135 for (i = 0; i < numParams; i++)
1137 Oid ptype = paramTypes[i];
1139 if (ptype == InvalidOid || ptype == UNKNOWNOID)
1141 (errcode(ERRCODE_INDETERMINATE_DATATYPE),
1142 errmsg("could not determine data type of parameter $%d",
1144 param_list = lappendo(param_list, ptype);
1147 if (log_parser_stats)
1148 ShowUsage("PARSE ANALYSIS STATISTICS");
1150 querytree_list = pg_rewrite_queries(querytree_list);
1152 plantree_list = pg_plan_queries(querytree_list, true);
1156 /* Empty input string. This is legal. */
1158 querytree_list = NIL;
1159 plantree_list = NIL;
1163 /* If we got a cancel signal in analysis or planning, quit */
1164 CHECK_FOR_INTERRUPTS();
1167 * Store the query as a prepared statement. See above comments.
1171 StorePreparedStatement(stmt_name,
1180 PreparedStatement *pstmt;
1182 pstmt = (PreparedStatement *) palloc0(sizeof(PreparedStatement));
1183 /* query_string needs to be copied into unnamed_stmt_context */
1184 pstmt->query_string = pstrdup(query_string);
1185 /* the rest is there already */
1186 pstmt->commandTag = commandTag;
1187 pstmt->query_list = querytree_list;
1188 pstmt->plan_list = plantree_list;
1189 pstmt->argtype_list = param_list;
1190 pstmt->context = unnamed_stmt_context;
1191 /* Now the unnamed statement is complete and valid */
1192 unnamed_stmt_pstmt = pstmt;
1195 MemoryContextSwitchTo(oldcontext);
1197 QueryContext = NULL;
1200 * We do NOT close the open transaction command here; that only
1201 * happens when the client sends Sync. Instead, do
1202 * CommandCounterIncrement just in case something happened during
1205 CommandCounterIncrement();
1208 * Send ParseComplete.
1210 if (whereToSendOutput == Remote)
1211 pq_putemptymessage('1');
1213 if (save_log_statement_stats)
1214 ShowUsage("PARSE MESSAGE STATISTICS");
1216 debug_query_string = NULL;
1222 * Process a "Bind" message to create a portal from a prepared statement
1225 exec_bind_message(StringInfo input_message)
1227 const char *portal_name;
1228 const char *stmt_name;
1230 int16 *pformats = NULL;
1233 int16 *rformats = NULL;
1235 PreparedStatement *pstmt;
1237 ParamListInfo params;
1239 pgstat_report_activity("<BIND>");
1241 set_ps_display("BIND");
1244 * Start up a transaction command so we can call functions etc. (Note
1245 * that this will normally change current memory context.) Nothing
1246 * happens if we are already in one.
1248 start_xact_command();
1250 /* Switch back to message context */
1251 MemoryContextSwitchTo(MessageContext);
1253 /* Get the fixed part of the message */
1254 portal_name = pq_getmsgstring(input_message);
1255 stmt_name = pq_getmsgstring(input_message);
1257 /* Get the parameter format codes */
1258 numPFormats = pq_getmsgint(input_message, 2);
1259 if (numPFormats > 0)
1261 pformats = (int16 *) palloc(numPFormats * sizeof(int16));
1262 for (i = 0; i < numPFormats; i++)
1263 pformats[i] = pq_getmsgint(input_message, 2);
1266 /* Get the parameter value count */
1267 numParams = pq_getmsgint(input_message, 2);
1269 if (numPFormats > 1 && numPFormats != numParams)
1271 (errcode(ERRCODE_PROTOCOL_VIOLATION),
1272 errmsg("bind message has %d parameter formats but %d parameters",
1273 numPFormats, numParams)));
1275 /* Find prepared statement */
1276 if (stmt_name[0] != '\0')
1277 pstmt = FetchPreparedStatement(stmt_name, true);
1280 /* special-case the unnamed statement */
1281 pstmt = unnamed_stmt_pstmt;
1284 (errcode(ERRCODE_UNDEFINED_PSTATEMENT),
1285 errmsg("unnamed prepared statement does not exist")));
1288 if (numParams != length(pstmt->argtype_list))
1290 (errcode(ERRCODE_PROTOCOL_VIOLATION),
1291 errmsg("bind message supplies %d parameters, but prepared statement \"%s\" requires %d",
1292 numParams, stmt_name, length(pstmt->argtype_list))));
1295 * Create the portal. Allow silent replacement of an existing portal
1296 * only if the unnamed portal is specified.
1298 if (portal_name[0] == '\0')
1299 portal = CreatePortal(portal_name, true, true);
1301 portal = CreatePortal(portal_name, false, false);
1303 PortalDefineQuery(portal,
1304 pstmt->query_string,
1311 * Fetch parameters, if any, and store in the portal's memory context.
1313 * In an aborted transaction, we can't risk calling user-defined
1314 * functions, but we can't fail to Bind either, so bind all parameters
1319 bool isaborted = IsAbortedTransactionBlockState();
1321 MemoryContext oldContext;
1323 oldContext = MemoryContextSwitchTo(PortalGetHeapMemory(portal));
1325 params = (ParamListInfo)
1326 palloc0((numParams + 1) * sizeof(ParamListInfoData));
1329 foreach(l, pstmt->argtype_list)
1331 Oid ptype = lfirsto(l);
1335 plength = pq_getmsgint(input_message, 4);
1336 isNull = (plength == -1);
1340 const char *pvalue = pq_getmsgbytes(input_message, plength);
1344 /* We don't bother to check the format in this case */
1350 StringInfoData pbuf;
1353 if (numPFormats > 1)
1354 pformat = pformats[i];
1355 else if (numPFormats > 0)
1356 pformat = pformats[0];
1358 pformat = 0; /* default = text */
1361 * Rather than copying data around, we just set up a
1362 * phony StringInfo pointing to the correct portion of
1363 * the message buffer. We assume we can scribble on
1364 * the message buffer so as to maintain the convention
1365 * that StringInfos have a trailing null. This is
1366 * grotty but is a big win when dealing with very
1367 * large parameter strings.
1369 pbuf.data = (char *) pvalue;
1370 pbuf.maxlen = plength + 1;
1374 csave = pbuf.data[plength];
1375 pbuf.data[plength] = '\0';
1383 getTypeInputInfo(ptype, &typInput, &typElem);
1386 * We have to do encoding conversion before
1387 * calling the typinput routine.
1390 pg_client_to_server((unsigned char *) pbuf.data,
1393 OidFunctionCall3(typInput,
1394 CStringGetDatum(pstring),
1395 ObjectIdGetDatum(typElem),
1397 /* Free result of encoding conversion, if any */
1398 if (pstring != pbuf.data)
1401 else if (pformat == 1)
1407 * Call the parameter type's binary input
1410 getTypeBinaryInputInfo(ptype, &typReceive, &typElem);
1413 OidFunctionCall2(typReceive,
1414 PointerGetDatum(&pbuf),
1415 ObjectIdGetDatum(typElem));
1417 /* Trouble if it didn't eat the whole buffer */
1418 if (pbuf.cursor != pbuf.len)
1420 (errcode(ERRCODE_INVALID_BINARY_REPRESENTATION),
1421 errmsg("incorrect binary data format in bind parameter %d",
1427 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1428 errmsg("unsupported format code: %d",
1432 /* Restore message buffer contents */
1433 pbuf.data[plength] = csave;
1437 params[i].kind = PARAM_NUM;
1438 params[i].id = i + 1;
1439 params[i].isnull = isNull;
1444 params[i].kind = PARAM_INVALID;
1446 MemoryContextSwitchTo(oldContext);
1451 /* Get the result format codes */
1452 numRFormats = pq_getmsgint(input_message, 2);
1453 if (numRFormats > 0)
1455 rformats = (int16 *) palloc(numRFormats * sizeof(int16));
1456 for (i = 0; i < numRFormats; i++)
1457 rformats[i] = pq_getmsgint(input_message, 2);
1460 pq_getmsgend(input_message);
1463 * Start portal execution.
1465 PortalStart(portal, params);
1468 * Apply the result format requests to the portal.
1470 PortalSetResultFormat(portal, numRFormats, rformats);
1473 * Send BindComplete.
1475 if (whereToSendOutput == Remote)
1476 pq_putemptymessage('2');
1480 * exec_execute_message
1482 * Process an "Execute" message for a portal
1485 exec_execute_message(const char *portal_name, long max_rows)
1488 DestReceiver *receiver;
1490 bool is_trans_stmt = false;
1491 bool is_trans_exit = false;
1493 char completionTag[COMPLETION_TAG_BUFSIZE];
1495 /* Adjust destination to tell printtup.c what to do */
1496 dest = whereToSendOutput;
1498 dest = RemoteExecute;
1500 portal = GetPortalByName(portal_name);
1501 if (!PortalIsValid(portal))
1503 (errcode(ERRCODE_UNDEFINED_CURSOR),
1504 errmsg("portal \"%s\" does not exist", portal_name)));
1507 * If the original query was a null string, just return
1508 * EmptyQueryResponse.
1510 if (portal->commandTag == NULL)
1512 Assert(portal->parseTrees == NIL);
1517 if (portal->sourceText)
1519 debug_query_string = portal->sourceText;
1520 pgstat_report_activity(portal->sourceText);
1524 debug_query_string = "execute message";
1525 pgstat_report_activity("<EXECUTE>");
1528 set_ps_display(portal->commandTag);
1530 BeginCommand(portal->commandTag, dest);
1532 /* Check for transaction-control commands */
1533 if (length(portal->parseTrees) == 1)
1535 Query *query = (Query *) lfirst(portal->parseTrees);
1537 if (query->commandType == CMD_UTILITY &&
1538 query->utilityStmt != NULL &&
1539 IsA(query->utilityStmt, TransactionStmt))
1541 TransactionStmt *stmt = (TransactionStmt *) query->utilityStmt;
1543 is_trans_stmt = true;
1544 if (stmt->kind == TRANS_STMT_COMMIT ||
1545 stmt->kind == TRANS_STMT_ROLLBACK)
1546 is_trans_exit = true;
1551 * Create dest receiver in MessageContext (we don't want it in
1552 * transaction context, because that may get deleted if portal
1555 receiver = CreateDestReceiver(dest, portal);
1558 * Ensure we are in a transaction command (this should normally be the
1559 * case already due to prior BIND).
1561 start_xact_command();
1564 * If we are in aborted transaction state, the only portals we can
1565 * actually run are those containing COMMIT or ROLLBACK commands.
1567 if (IsAbortedTransactionBlockState())
1571 (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
1572 errmsg("current transaction is aborted, "
1573 "commands ignored until end of transaction block")));
1576 /* Check for cancel signal before we start execution */
1577 CHECK_FOR_INTERRUPTS();
1580 * Okay to run the portal.
1583 max_rows = FETCH_ALL;
1585 completed = PortalRun(portal,
1591 (*receiver->rDestroy) (receiver);
1598 * If this was a transaction control statement, commit it. We
1599 * will start a new xact command for the next command (if
1602 finish_xact_command();
1607 * We need a CommandCounterIncrement after every query, except
1608 * those that start or end a transaction block.
1610 CommandCounterIncrement();
1613 /* Send appropriate CommandComplete to client */
1614 EndCommand(completionTag, dest);
1618 /* Portal run not complete, so send PortalSuspended */
1619 if (whereToSendOutput == Remote)
1620 pq_putemptymessage('s');
1623 debug_query_string = NULL;
1627 * exec_describe_statement_message
1629 * Process a "Describe" message for a prepared statement
1632 exec_describe_statement_message(const char *stmt_name)
1634 PreparedStatement *pstmt;
1639 /* Find prepared statement */
1640 if (stmt_name[0] != '\0')
1641 pstmt = FetchPreparedStatement(stmt_name, true);
1644 /* special-case the unnamed statement */
1645 pstmt = unnamed_stmt_pstmt;
1648 (errcode(ERRCODE_UNDEFINED_PSTATEMENT),
1649 errmsg("unnamed prepared statement does not exist")));
1652 if (whereToSendOutput != Remote)
1653 return; /* can't actually do anything... */
1656 * First describe the parameters...
1658 pq_beginmessage(&buf, 't'); /* parameter description message type */
1659 pq_sendint(&buf, length(pstmt->argtype_list), 2);
1661 foreach(l, pstmt->argtype_list)
1663 Oid ptype = lfirsto(l);
1665 pq_sendint(&buf, (int) ptype, 4);
1667 pq_endmessage(&buf);
1670 * Next send RowDescription or NoData to describe the result...
1672 tupdesc = FetchPreparedStatementResultDesc(pstmt);
1677 if (ChoosePortalStrategy(pstmt->query_list) == PORTAL_ONE_SELECT)
1678 targetlist = ((Query *) lfirst(pstmt->query_list))->targetList;
1681 SendRowDescriptionMessage(tupdesc, targetlist, NULL);
1684 pq_putemptymessage('n'); /* NoData */
1689 * exec_describe_portal_message
1691 * Process a "Describe" message for a portal
1694 exec_describe_portal_message(const char *portal_name)
1698 portal = GetPortalByName(portal_name);
1699 if (!PortalIsValid(portal))
1701 (errcode(ERRCODE_UNDEFINED_CURSOR),
1702 errmsg("portal \"%s\" does not exist", portal_name)));
1704 if (whereToSendOutput != Remote)
1705 return; /* can't actually do anything... */
1707 if (portal->tupDesc)
1711 if (portal->strategy == PORTAL_ONE_SELECT)
1712 targetlist = ((Query *) lfirst(portal->parseTrees))->targetList;
1715 SendRowDescriptionMessage(portal->tupDesc, targetlist,
1719 pq_putemptymessage('n'); /* NoData */
1724 * Convenience routines for starting/committing a single command.
1727 start_xact_command(void)
1732 (errmsg_internal("StartTransactionCommand")));
1733 StartTransactionCommand();
1735 /* Set statement timeout running, if any */
1736 if (StatementTimeout > 0)
1737 enable_sig_alarm(StatementTimeout, true);
1739 xact_started = true;
1744 finish_xact_command(void)
1748 /* Invoke IMMEDIATE constraint triggers */
1749 DeferredTriggerEndQuery();
1751 /* Cancel any active statement timeout before committing */
1752 disable_sig_alarm(true);
1754 /* Now commit the command */
1756 (errmsg_internal("CommitTransactionCommand")));
1758 CommitTransactionCommand();
1760 #ifdef MEMORY_CONTEXT_CHECKING
1761 /* Check all memory contexts that weren't freed during commit */
1762 /* (those that were, were checked before being deleted) */
1763 MemoryContextCheck(TopMemoryContext);
1766 #ifdef SHOW_MEMORY_STATS
1767 /* Print mem stats after each commit for leak tracking */
1769 MemoryContextStats(TopMemoryContext);
1772 xact_started = false;
1777 /* --------------------------------
1778 * signal handler routines used in PostgresMain()
1779 * --------------------------------
1783 * quickdie() occurs when signalled SIGQUIT by the postmaster.
1785 * Some backend has bought the farm,
1786 * so we need to stop what we're doing and exit.
1789 quickdie(SIGNAL_ARGS)
1791 PG_SETMASK(&BlockSig);
1794 * Ideally this should be ereport(FATAL), but then we'd not get
1795 * control back (perhaps could fix by doing local sigsetjmp?)
1798 (errcode(ERRCODE_CRASH_SHUTDOWN),
1799 errmsg("terminating connection because of crash of another server process"),
1800 errdetail("The postmaster has commanded this server process to roll back"
1801 " the current transaction and exit, because another"
1802 " server process exited abnormally and possibly corrupted"
1804 errhint("In a moment you should be able to reconnect to the"
1805 " database and repeat your command.")));
1808 * DO NOT proc_exit() -- we're here because shared memory may be
1809 * corrupted, so we don't want to try to clean up our transaction.
1810 * Just nail the windows shut and get out of town.
1812 * Note we do exit(1) not exit(0). This is to force the postmaster into
1813 * a system reset cycle if some idiot DBA sends a manual SIGQUIT to a
1814 * random backend. This is necessary precisely because we don't clean
1815 * up our shared memory state.
1821 * Shutdown signal from postmaster: abort transaction and exit
1822 * at soonest convenient time
1827 int save_errno = errno;
1829 /* Don't joggle the elbow of proc_exit */
1830 if (!proc_exit_inprogress)
1832 InterruptPending = true;
1833 ProcDiePending = true;
1836 * If it's safe to interrupt, and we're waiting for input or a
1837 * lock, service the interrupt immediately
1839 if (ImmediateInterruptOK && InterruptHoldoffCount == 0 &&
1840 CritSectionCount == 0)
1842 /* bump holdoff count to make ProcessInterrupts() a no-op */
1843 /* until we are done getting ready for it */
1844 InterruptHoldoffCount++;
1845 DisableNotifyInterrupt();
1846 /* Make sure CheckDeadLock won't run while shutting down... */
1848 InterruptHoldoffCount--;
1849 ProcessInterrupts();
1857 * Timeout or shutdown signal from postmaster during client authentication.
1860 * XXX: possible future improvement: try to send a message indicating
1861 * why we are disconnecting. Problem is to be sure we don't block while
1862 * doing so, nor mess up the authentication message exchange.
1865 authdie(SIGNAL_ARGS)
1871 * Query-cancel signal from postmaster: abort current transaction
1872 * at soonest convenient time
1875 StatementCancelHandler(SIGNAL_ARGS)
1877 int save_errno = errno;
1880 * Don't joggle the elbow of proc_exit, nor an already-in-progress
1883 if (!proc_exit_inprogress && !InError)
1885 InterruptPending = true;
1886 QueryCancelPending = true;
1889 * If it's safe to interrupt, and we're waiting for a lock,
1890 * service the interrupt immediately. No point in interrupting if
1891 * we're waiting for input, however.
1893 if (ImmediateInterruptOK && InterruptHoldoffCount == 0 &&
1894 CritSectionCount == 0)
1896 /* bump holdoff count to make ProcessInterrupts() a no-op */
1897 /* until we are done getting ready for it */
1898 InterruptHoldoffCount++;
1899 if (LockWaitCancel())
1901 DisableNotifyInterrupt();
1902 InterruptHoldoffCount--;
1903 ProcessInterrupts();
1906 InterruptHoldoffCount--;
1913 /* signal handler for floating point exception */
1915 FloatExceptionHandler(SIGNAL_ARGS)
1918 (errcode(ERRCODE_FLOATING_POINT_EXCEPTION),
1919 errmsg("floating-point exception"),
1920 errdetail("An invalid floating-point operation was signaled. "
1921 "This probably means an out-of-range result or an "
1922 "invalid operation, such as division by zero.")));
1925 /* SIGHUP: set flag to re-read config file at next convenient time */
1927 SigHupHandler(SIGNAL_ARGS)
1934 * ProcessInterrupts: out-of-line portion of CHECK_FOR_INTERRUPTS() macro
1936 * If an interrupt condition is pending, and it's safe to service it,
1937 * then clear the flag and accept the interrupt. Called only when
1938 * InterruptPending is true.
1941 ProcessInterrupts(void)
1943 /* OK to accept interrupt now? */
1944 if (InterruptHoldoffCount != 0 || CritSectionCount != 0)
1946 InterruptPending = false;
1949 ProcDiePending = false;
1950 QueryCancelPending = false; /* ProcDie trumps QueryCancel */
1951 ImmediateInterruptOK = false; /* not idle anymore */
1952 DisableNotifyInterrupt();
1954 (errcode(ERRCODE_ADMIN_SHUTDOWN),
1955 errmsg("terminating connection due to administrator command")));
1957 if (QueryCancelPending)
1959 QueryCancelPending = false;
1960 ImmediateInterruptOK = false; /* not idle anymore */
1961 DisableNotifyInterrupt();
1963 (errcode(ERRCODE_QUERY_CANCELED),
1964 errmsg("canceling query due to user request")));
1966 /* If we get here, do nothing (probably, QueryCancelPending was reset) */
1971 usage(char *progname)
1973 printf(gettext("%s is the PostgreSQL stand-alone backend. It is not\nintended to be used by normal users.\n\n"), progname);
1975 printf(gettext("Usage:\n %s [OPTION]... [DBNAME]\n\n"), progname);
1976 printf(gettext("Options:\n"));
1977 #ifdef USE_ASSERT_CHECKING
1978 printf(gettext(" -A 1|0 enable/disable run-time assert checking\n"));
1980 printf(gettext(" -B NBUFFERS number of shared buffers\n"));
1981 printf(gettext(" -c NAME=VALUE set run-time parameter\n"));
1982 printf(gettext(" -d 0-5 debugging level (0 is off)\n"));
1983 printf(gettext(" -D DATADIR database directory\n"));
1984 printf(gettext(" -e use European date input format (DMY)\n"));
1985 printf(gettext(" -E echo query before execution\n"));
1986 printf(gettext(" -F turn fsync off\n"));
1987 printf(gettext(" -N do not use newline as interactive query delimiter\n"));
1988 printf(gettext(" -o FILENAME send stdout and stderr to given file\n"));
1989 printf(gettext(" -P disable system indexes\n"));
1990 printf(gettext(" -s show statistics after each query\n"));
1991 printf(gettext(" -S SORT-MEM set amount of memory for sorts (in kbytes)\n"));
1992 printf(gettext(" --describe-config describe configuration parameters, then exit\n"));
1993 printf(gettext(" --help show this help, then exit\n"));
1994 printf(gettext(" --version output version information, then exit\n"));
1995 printf(gettext("\nDeveloper options:\n"));
1996 printf(gettext(" -f s|i|n|m|h forbid use of some plan types\n"));
1997 printf(gettext(" -i do not execute queries\n"));
1998 printf(gettext(" -O allow system table structure changes\n"));
1999 printf(gettext(" -t pa|pl|ex show timings after each query\n"));
2000 printf(gettext(" -W NUM wait NUM seconds to allow attach from a debugger\n"));
2001 printf(gettext("\nReport bugs to <pgsql-bugs@postgresql.org>.\n"));
2006 /* ----------------------------------------------------------------
2008 * postgres main loop -- all backends, interactive or otherwise start here
2010 * argc/argv are the command line arguments to be used. (When being forked
2011 * by the postmaster, these are not the original argv array of the process.)
2012 * username is the (possibly authenticated) PostgreSQL user name to be used
2014 * ----------------------------------------------------------------
2017 PostgresMain(int argc, char *argv[], const char *username)
2020 const char *dbname = NULL;
2021 char *potential_DataDir = NULL;
2027 GucSource gucsource;
2030 StringInfoData input_message;
2031 volatile bool send_rfq = true;
2034 * Catch standard options before doing much else. This even works on
2035 * systems without getopt_long.
2037 if (!IsUnderPostmaster && argc > 1)
2039 if (strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-?") == 0)
2044 if (strcmp(argv[1], "--version") == 0 || strcmp(argv[1], "-V") == 0)
2046 puts("postgres (PostgreSQL) " PG_VERSION);
2052 * initialize globals (already done if under postmaster, but not if
2053 * standalone; cheap enough to do over)
2056 MyProcPid = getpid();
2059 * Fire up essential subsystems: error and memory management
2061 * If we are running under the postmaster, this is done already.
2063 if (!IsUnderPostmaster)
2064 MemoryContextInit();
2066 set_ps_display("startup");
2068 SetProcessingMode(InitProcessing);
2071 * Set default values for command-line options.
2076 if (!IsUnderPostmaster /* when exec || ExecBackend */ )
2078 InitializeGUCOptions();
2079 potential_DataDir = getenv("PGDATA");
2083 * parse command line arguments
2085 * There are now two styles of command line layout for the backend:
2087 * For interactive use (not started from postmaster) the format is
2088 * postgres [switches] [databasename]
2089 * If the databasename is omitted it is taken to be the user name.
2091 * When started from the postmaster, the format is
2092 * postgres [secure switches] -p databasename [insecure switches]
2093 * Switches appearing after -p came from the client (via "options"
2094 * field of connection request). For security reasons we restrict
2095 * what these switches can do.
2099 /* all options are allowed until '-p' */
2101 ctx = debug_context = PGC_POSTMASTER;
2102 gucsource = PGC_S_ARGV; /* initial switches came from command line */
2104 while ((flag = getopt(argc, argv, "A:B:c:CD:d:Eef:FiNOPo:p:S:st:v:W:x:-:")) != -1)
2108 #ifdef USE_ASSERT_CHECKING
2109 SetConfigOption("debug_assertions", optarg, ctx, gucsource);
2112 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2113 errmsg("assert checking is not compiled in")));
2120 * specify the size of buffer pool
2122 SetConfigOption("shared_buffers", optarg, ctx, gucsource);
2128 * don't print version string
2133 case 'D': /* PGDATA directory */
2135 potential_DataDir = optarg;
2138 case 'd': /* debug level */
2141 * Client option can't decrease debug level. We have
2142 * to do the test here because we group priv and
2143 * client set GUC calls below, after we know the final
2146 if (ctx != PGC_BACKEND || atoi(optarg) > debug_flag)
2148 debug_flag = atoi(optarg);
2149 debug_context = ctx; /* save context for use
2151 /* Set server debugging level. */
2152 if (debug_flag != 0)
2154 char *debugstr = palloc(strlen("debug") + strlen(optarg) + 1);
2156 sprintf(debugstr, "debug%s", optarg);
2157 SetConfigOption("log_min_messages", debugstr, ctx, gucsource);
2164 * -d0 allows user to prevent postmaster debug
2165 * from propagating to backend. It would be
2166 * nice to set it to the postgresql.conf value
2169 SetConfigOption("log_min_messages", "notice",
2178 * E - echo the query the user entered
2186 * Use European date input format (DMY)
2188 SetConfigOption("datestyle", "euro", ctx, gucsource);
2196 SetConfigOption("fsync", "false", ctx, gucsource);
2202 * f - forbid generation of certain plans
2207 case 's': /* seqscan */
2208 tmp = "enable_seqscan";
2210 case 'i': /* indexscan */
2211 tmp = "enable_indexscan";
2213 case 't': /* tidscan */
2214 tmp = "enable_tidscan";
2216 case 'n': /* nestloop */
2217 tmp = "enable_nestloop";
2219 case 'm': /* mergejoin */
2220 tmp = "enable_mergejoin";
2222 case 'h': /* hashjoin */
2223 tmp = "enable_hashjoin";
2229 SetConfigOption(tmp, "false", ctx, gucsource);
2235 * N - Don't use newline as a query delimiter
2243 * allow system table structure modifications
2245 if (secure) /* XXX safe to allow from client??? */
2246 allowSystemTableMods = true;
2252 * ignore system indexes
2254 * As of PG 7.4 this is safe to allow from the client,
2255 * since it only disables reading the system indexes,
2256 * not writing them. Worst case consequence is slowness.
2258 IgnoreSystemIndexes(true);
2264 * o - send output (stdout and stderr) to the given file
2267 StrNCpy(OutputFileName, optarg, MAXPGPATH);
2273 * p - special flag passed if backend was forked by a
2281 int PMcanAcceptConnections; /* will eventually be
2285 sscanf(optarg, "%d,%d,%lu,%p,",
2286 &MyProcPort->sock, &PMcanAcceptConnections,
2287 &UsedShmemSegID, &UsedShmemSegAddr);
2288 /* Grab dbname as last param */
2289 for (i = 0, p = optarg - 1; i < 4 && p; i++)
2290 p = strchr(p + 1, ',');
2292 dbname = strdup(p + 1);
2294 dbname = strdup(optarg);
2296 secure = false; /* subsequent switches are NOT
2299 gucsource = PGC_S_CLIENT;
2306 * S - amount of sort memory to use in 1k bytes
2308 SetConfigOption("sort_mem", optarg, ctx, gucsource);
2314 * s - report usage statistics (timings) after each query
2316 SetConfigOption("log_statement_stats", "true", ctx, gucsource);
2321 * tell postgres to report usage statistics (timings) for
2324 * -tpa[rser] = print stats for parser time of each query
2325 * -tpl[anner] = print stats for planner time of each query
2326 * -te[xecutor] = print stats for executor time of each query
2327 * caution: -s can not be used together with -t.
2334 if (optarg[1] == 'a')
2335 tmp = "log_parser_stats";
2336 else if (optarg[1] == 'l')
2337 tmp = "log_planner_stats";
2342 tmp = "log_executor_stats";
2349 SetConfigOption(tmp, "true", ctx, gucsource);
2354 FrontendProtocol = (ProtocolVersion) atoi(optarg);
2360 * wait N seconds to allow attach from a debugger
2362 sleep(atoi(optarg));
2366 #ifdef NOT_USED /* planner/xfunc.h */
2369 * control joey hellerstein's expensive function
2374 elog(WARNING, "only one -x flag is allowed");
2378 if (strcmp(optarg, "off") == 0)
2379 XfuncMode = XFUNC_OFF;
2380 else if (strcmp(optarg, "nor") == 0)
2381 XfuncMode = XFUNC_NOR;
2382 else if (strcmp(optarg, "nopull") == 0)
2383 XfuncMode = XFUNC_NOPULL;
2384 else if (strcmp(optarg, "nopm") == 0)
2385 XfuncMode = XFUNC_NOPM;
2386 else if (strcmp(optarg, "pullall") == 0)
2387 XfuncMode = XFUNC_PULLALL;
2388 else if (strcmp(optarg, "wait") == 0)
2389 XfuncMode = XFUNC_WAIT;
2392 elog(WARNING, "use -x {off,nor,nopull,nopm,pullall,wait}");
2404 ParseLongOption(optarg, &name, &value);
2409 (errcode(ERRCODE_SYNTAX_ERROR),
2410 errmsg("--%s requires a value",
2414 (errcode(ERRCODE_SYNTAX_ERROR),
2415 errmsg("-c %s requires a value",
2419 SetConfigOption(name, value, ctx, gucsource);
2433 * -d is not the same as setting log_min_messages because it enables
2434 * other output options.
2436 if (debug_flag >= 1)
2437 SetConfigOption("log_connections", "true", debug_context, gucsource);
2438 if (debug_flag >= 2)
2439 SetConfigOption("log_statement", "true", debug_context, gucsource);
2440 if (debug_flag >= 3)
2441 SetConfigOption("debug_print_parse", "true", debug_context, gucsource);
2442 if (debug_flag >= 4)
2443 SetConfigOption("debug_print_plan", "true", debug_context, gucsource);
2444 if (debug_flag >= 5)
2445 SetConfigOption("debug_print_rewritten", "true", debug_context, gucsource);
2448 * Process any additional GUC variable settings passed in startup
2451 if (MyProcPort != NULL)
2453 List *gucopts = MyProcPort->guc_options;
2460 name = lfirst(gucopts);
2461 gucopts = lnext(gucopts);
2462 value = lfirst(gucopts);
2463 gucopts = lnext(gucopts);
2464 SetConfigOption(name, value, PGC_BACKEND, PGC_S_CLIENT);
2469 * Post-processing for command line options.
2471 if (log_statement_stats &&
2472 (log_parser_stats || log_planner_stats || log_executor_stats))
2475 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
2476 errmsg("statement-level statistics are disabled because parser, planner, or executor statistics are on")));
2477 SetConfigOption("log_statement_stats", "false", ctx, gucsource);
2480 if (!IsUnderPostmaster)
2482 if (!potential_DataDir)
2485 gettext("%s does not know where to find the database system data.\n"
2486 "You must specify the directory that contains the database system\n"
2487 "either by specifying the -D invocation option or by setting the\n"
2488 "PGDATA environment variable.\n"),
2492 SetDataDir(potential_DataDir);
2496 /* Acquire configuration parameters */
2497 if (IsUnderPostmaster)
2500 read_nondefault_variables();
2504 ProcessConfigFile(PGC_POSTMASTER);
2507 * Set up signal handlers and masks.
2509 * Note that postmaster blocked all signals before forking child process,
2510 * so there is no race condition whereby we might receive a signal
2511 * before we have set up the handler.
2513 * Also note: it's best not to use any signals that are SIG_IGNored in
2514 * the postmaster. If such a signal arrives before we are able to
2515 * change the handler to non-SIG_IGN, it'll get dropped. Instead,
2516 * make a dummy handler in the postmaster to reserve the signal. (Of
2517 * course, this isn't an issue for signals that are locally generated,
2518 * such as SIGALRM and SIGPIPE.)
2521 pqsignal(SIGHUP, SigHupHandler); /* set flag to read config file */
2522 pqsignal(SIGINT, StatementCancelHandler); /* cancel current query */
2523 pqsignal(SIGTERM, die); /* cancel current query and exit */
2524 pqsignal(SIGQUIT, quickdie); /* hard crash time */
2525 pqsignal(SIGALRM, handle_sig_alarm); /* timeout conditions */
2528 * Ignore failure to write to frontend. Note: if frontend closes
2529 * connection, we will notice it and exit cleanly when control next
2530 * returns to outer loop. This seems safer than forcing exit in the
2531 * midst of output during who-knows-what operation...
2533 pqsignal(SIGPIPE, SIG_IGN);
2534 pqsignal(SIGUSR1, SIG_IGN); /* this signal available for use */
2536 pqsignal(SIGUSR2, Async_NotifyHandler); /* flush also sinval cache */
2537 pqsignal(SIGFPE, FloatExceptionHandler);
2540 * Reset some signals that are accepted by postmaster but not by
2543 pqsignal(SIGCHLD, SIG_DFL); /* system() requires this on some
2548 /* We allow SIGQUIT (quickdie) at all times */
2549 #ifdef HAVE_SIGPROCMASK
2550 sigdelset(&BlockSig, SIGQUIT);
2552 BlockSig &= ~(sigmask(SIGQUIT));
2555 PG_SETMASK(&BlockSig); /* block everything except SIGQUIT */
2558 if (IsUnderPostmaster)
2560 /* noninteractive case: nothing should be left after switches */
2561 if (errs || argc != optind || dbname == NULL)
2564 (errcode(ERRCODE_SYNTAX_ERROR),
2565 errmsg("invalid command-line arguments for server process"),
2566 errhint("Try \"%s --help\" for more information.", argv[0])));
2570 AttachSharedMemoryAndSemaphores();
2575 /* interactive case: database name can be last arg on command line */
2576 if (errs || argc - optind > 1)
2579 (errcode(ERRCODE_SYNTAX_ERROR),
2580 errmsg("%s: invalid command-line arguments",
2582 errhint("Try \"%s --help\" for more information.", argv[0])));
2584 else if (argc - optind == 1)
2585 dbname = argv[optind];
2586 else if ((dbname = username) == NULL)
2589 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
2590 errmsg("%s: no database nor user name specified",
2595 * On some systems our dynloader code needs the executable's
2596 * pathname. (If under postmaster, this was done already.)
2598 if (FindExec(pg_pathname, argv[0], "postgres") < 0)
2600 (errmsg("%s: could not locate postgres executable",
2604 * Validate we have been given a reasonable-looking DataDir (if
2605 * under postmaster, assume postmaster did this already).
2607 ValidatePgVersion(DataDir);
2610 * Create lockfile for data directory.
2612 CreateDataDirLockFile(DataDir, false);
2618 * Start up xlog for standalone backend, and register to have it
2619 * closed down at exit.
2622 on_shmem_exit(ShutdownXLOG, 0);
2625 * Read any existing FSM cache file, and register to write one out
2629 on_shmem_exit(DumpFreeSpaceMap, 0);
2633 * General initialization.
2635 * NOTE: if you are tempted to add code in this vicinity, consider
2636 * putting it inside InitPostgres() instead. In particular, anything
2637 * that involves database access should be there, not here.
2640 (errmsg_internal("InitPostgres")));
2641 InitPostgres(dbname, username);
2643 SetProcessingMode(NormalProcessing);
2646 * Send this backend's cancellation info to the frontend.
2648 if (whereToSendOutput == Remote &&
2649 PG_PROTOCOL_MAJOR(FrontendProtocol) >= 2)
2653 pq_beginmessage(&buf, 'K');
2654 pq_sendint(&buf, (int32) MyProcPid, sizeof(int32));
2655 pq_sendint(&buf, (int32) MyCancelKey, sizeof(int32));
2656 pq_endmessage(&buf);
2657 /* Need not flush since ReadyForQuery will do it. */
2660 /* Welcome banner for non-frontend case */
2661 if (!IsUnderPostmaster)
2662 printf("\nPostgreSQL stand-alone backend %s\n", PG_VERSION);
2665 * Create the memory context we will use in the main loop.
2667 * MessageContext is reset once per iteration of the main loop, ie, upon
2668 * completion of processing of each command message from the client.
2670 MessageContext = AllocSetContextCreate(TopMemoryContext,
2672 ALLOCSET_DEFAULT_MINSIZE,
2673 ALLOCSET_DEFAULT_INITSIZE,
2674 ALLOCSET_DEFAULT_MAXSIZE);
2677 * Tell the statistics collector that we're alive and
2678 * to which database we belong.
2684 * POSTGRES main processing loop begins here
2686 * If an exception is encountered, processing resumes here so we abort
2687 * the current transaction and start a new one.
2690 if (sigsetjmp(Warn_restart, 1) != 0)
2693 * NOTE: if you are tempted to add more code in this if-block,
2694 * consider the probability that it should be in
2695 * AbortTransaction() instead.
2697 * Make sure we're not interrupted while cleaning up. Also forget
2698 * any pending QueryCancel request, since we're aborting anyway.
2699 * Force InterruptHoldoffCount to a known state in case we
2700 * ereport'd from inside a holdoff section.
2702 ImmediateInterruptOK = false;
2703 QueryCancelPending = false;
2704 InterruptHoldoffCount = 1;
2705 CritSectionCount = 0; /* should be unnecessary, but... */
2706 disable_sig_alarm(true);
2707 QueryCancelPending = false; /* again in case timeout occurred */
2708 DisableNotifyInterrupt();
2709 debug_query_string = NULL;
2712 * Make sure we are in a valid memory context during recovery.
2714 * We use ErrorContext in hopes that it will have some free space
2715 * even if we're otherwise up against it...
2717 MemoryContextSwitchTo(ErrorContext);
2719 /* Do the recovery */
2721 (errmsg_internal("AbortCurrentTransaction")));
2722 AbortCurrentTransaction();
2725 * Now return to normal top-level context and clear ErrorContext
2728 MemoryContextSwitchTo(TopMemoryContext);
2729 MemoryContextResetAndDeleteChildren(ErrorContext);
2730 PortalContext = NULL;
2731 QueryContext = NULL;
2734 * Clear flag to indicate that we got out of error recovery mode
2735 * successfully. (Flag was set in elog.c before longjmp().)
2738 xact_started = false;
2741 * If we were handling an extended-query-protocol message,
2742 * initiate skip till next Sync. This also causes us not to issue
2743 * ReadyForQuery (until we get Sync).
2745 if (doing_extended_query_message)
2746 ignore_till_sync = true;
2749 * Exit interrupt holdoff section we implicitly established above.
2751 RESUME_INTERRUPTS();
2754 Warn_restart_ready = true; /* we can now handle ereport(ERROR) */
2756 PG_SETMASK(&UnBlockSig);
2758 if (!ignore_till_sync)
2759 send_rfq = true; /* initially, or after error */
2762 * Non-error queries loop here.
2768 * At top of loop, reset extended-query-message flag, so that any
2769 * errors encountered in "idle" state don't provoke skip.
2771 doing_extended_query_message = false;
2774 * Release storage left over from prior query cycle, and create a
2775 * new query input buffer in the cleared MessageContext.
2777 MemoryContextSwitchTo(MessageContext);
2778 MemoryContextResetAndDeleteChildren(MessageContext);
2780 initStringInfo(&input_message);
2783 * (1) If we've reached idle state, tell the frontend we're ready
2786 * Note: this includes fflush()'ing the last of the prior output.
2788 * This is also a good time to send collected statistics to the
2789 * collector, and to update the PS stats display. We avoid doing
2790 * those every time through the message loop because it'd slow down
2791 * processing of batched messages.
2795 pgstat_report_tabstat();
2797 if (IsTransactionOrTransactionBlock())
2799 set_ps_display("idle in transaction");
2800 pgstat_report_activity("<IDLE> in transaction");
2804 set_ps_display("idle");
2805 pgstat_report_activity("<IDLE>");
2808 ReadyForQuery(whereToSendOutput);
2813 * (2) deal with pending asynchronous NOTIFY from other backends,
2814 * and enable async.c's signal handler to execute NOTIFY directly.
2815 * Then set up other stuff needed before blocking for input.
2817 QueryCancelPending = false; /* forget any earlier CANCEL
2820 EnableNotifyInterrupt();
2822 /* Allow "die" interrupt to be processed while waiting */
2823 ImmediateInterruptOK = true;
2824 /* and don't forget to detect one that already arrived */
2825 QueryCancelPending = false;
2826 CHECK_FOR_INTERRUPTS();
2829 * (3) read a command (loop blocks here)
2831 firstchar = ReadCommand(&input_message);
2834 * (4) disable async signal conditions again.
2836 ImmediateInterruptOK = false;
2837 QueryCancelPending = false; /* forget any CANCEL signal */
2839 DisableNotifyInterrupt();
2842 * (5) check for any other interesting events that happened while
2848 ProcessConfigFile(PGC_SIGHUP);
2852 * (6) process the command. But ignore it if we're skipping till
2855 if (ignore_till_sync && firstchar != EOF)
2860 case 'Q': /* simple query */
2862 const char *query_string;
2864 query_string = pq_getmsgstring(&input_message);
2865 pq_getmsgend(&input_message);
2867 exec_simple_query(query_string);
2873 case 'P': /* parse */
2875 const char *stmt_name;
2876 const char *query_string;
2878 Oid *paramTypes = NULL;
2880 stmt_name = pq_getmsgstring(&input_message);
2881 query_string = pq_getmsgstring(&input_message);
2882 numParams = pq_getmsgint(&input_message, 2);
2887 paramTypes = (Oid *) palloc(numParams * sizeof(Oid));
2888 for (i = 0; i < numParams; i++)
2889 paramTypes[i] = pq_getmsgint(&input_message, 4);
2891 pq_getmsgend(&input_message);
2893 exec_parse_message(query_string, stmt_name,
2894 paramTypes, numParams);
2898 case 'B': /* bind */
2901 * this message is complex enough that it seems best to
2902 * put the field extraction out-of-line
2904 exec_bind_message(&input_message);
2907 case 'E': /* execute */
2909 const char *portal_name;
2912 portal_name = pq_getmsgstring(&input_message);
2913 max_rows = pq_getmsgint(&input_message, 4);
2914 pq_getmsgend(&input_message);
2916 exec_execute_message(portal_name, max_rows);
2920 case 'F': /* fastpath function call */
2921 /* Tell the collector what we're doing */
2922 pgstat_report_activity("<FASTPATH> function call");
2924 /* start an xact for this function invocation */
2925 start_xact_command();
2927 /* switch back to message context */
2928 MemoryContextSwitchTo(MessageContext);
2930 if (HandleFunctionRequest(&input_message) == EOF)
2932 /* lost frontend connection during F message input */
2935 * Reset whereToSendOutput to prevent ereport from
2936 * attempting to send any more messages to client.
2938 if (whereToSendOutput == Remote)
2939 whereToSendOutput = None;
2944 /* commit the function-invocation transaction */
2945 finish_xact_command();
2950 case 'C': /* close */
2953 const char *close_target;
2955 close_type = pq_getmsgbyte(&input_message);
2956 close_target = pq_getmsgstring(&input_message);
2957 pq_getmsgend(&input_message);
2962 if (close_target[0] != '\0')
2963 DropPreparedStatement(close_target, false);
2966 /* special-case the unnamed statement */
2967 unnamed_stmt_pstmt = NULL;
2968 if (unnamed_stmt_context)
2970 DropDependentPortals(unnamed_stmt_context);
2971 MemoryContextDelete(unnamed_stmt_context);
2973 unnamed_stmt_context = NULL;
2980 portal = GetPortalByName(close_target);
2981 if (PortalIsValid(portal))
2982 PortalDrop(portal, false);
2987 (errcode(ERRCODE_PROTOCOL_VIOLATION),
2988 errmsg("invalid CLOSE message subtype %d",
2993 if (whereToSendOutput == Remote)
2994 pq_putemptymessage('3'); /* CloseComplete */
2998 case 'D': /* describe */
3001 const char *describe_target;
3003 describe_type = pq_getmsgbyte(&input_message);
3004 describe_target = pq_getmsgstring(&input_message);
3005 pq_getmsgend(&input_message);
3007 switch (describe_type)
3010 exec_describe_statement_message(describe_target);
3013 exec_describe_portal_message(describe_target);
3017 (errcode(ERRCODE_PROTOCOL_VIOLATION),
3018 errmsg("invalid DESCRIBE message subtype %d",
3025 case 'H': /* flush */
3026 pq_getmsgend(&input_message);
3027 if (whereToSendOutput == Remote)
3031 case 'S': /* sync */
3032 pq_getmsgend(&input_message);
3033 finish_xact_command();
3038 * 'X' means that the frontend is closing down the socket.
3039 * EOF means unexpected loss of frontend connection.
3040 * Either way, perform normal shutdown.
3046 * Reset whereToSendOutput to prevent ereport from
3047 * attempting to send any more messages to client.
3049 if (whereToSendOutput == Remote)
3050 whereToSendOutput = None;
3053 * NOTE: if you are tempted to add more code here, DON'T!
3054 * Whatever you had in mind to do should be set up as an
3055 * on_proc_exit or on_shmem_exit callback, instead.
3056 * Otherwise it will fail to be called during other
3057 * backend-shutdown scenarios.
3061 case 'd': /* copy data */
3062 case 'c': /* copy done */
3063 case 'f': /* copy fail */
3066 * Accept but ignore these messages, per protocol spec; we
3067 * probably got here because a COPY failed, and the
3068 * frontend is still sending data.
3074 (errcode(ERRCODE_PROTOCOL_VIOLATION),
3075 errmsg("invalid frontend message type %d",
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 static struct rusage Save_r;
3093 static 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)));