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.381 2003/12/25 03:52:51 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"
72 extern bool BackendInit(Port*);
73 extern void read_backend_variables(pid_t, Port*);
80 const char *debug_query_string; /* for pgmonitor and
81 * log_min_error_statement */
83 /* Note: whereToSendOutput is initialized for the bootstrap/standalone case */
84 CommandDest whereToSendOutput = Debug;
86 /* note: these declarations had better match tcopprot.h */
87 sigjmp_buf Warn_restart;
89 bool Warn_restart_ready = false;
93 * Flags for expensive function optimization -- JMH 3/9/92
103 * Flag to mark SIGHUP. Whenever the main loop comes around it
104 * will reread the configuration file. (Better than doing the
105 * reading in the signal handler, ey?)
107 static volatile bool got_SIGHUP = false;
110 * Flag to keep track of whether we have started a transaction.
111 * For extended query protocol this has to be remembered across messages.
113 static bool xact_started = false;
116 * Flags to implement skip-till-Sync-after-error behavior for messages of
117 * the extended query protocol.
119 static bool doing_extended_query_message = false;
120 static bool ignore_till_sync = false;
123 * If an unnamed prepared statement exists, it's stored here.
124 * We keep it separate from the hashtable kept by commands/prepare.c
125 * in order to reduce overhead for short-lived queries.
127 static MemoryContext unnamed_stmt_context = NULL;
128 static PreparedStatement *unnamed_stmt_pstmt = NULL;
131 static bool EchoQuery = false; /* default don't echo */
134 * people who want to use EOF should #define DONTUSENEWLINE in
137 #ifndef TCOP_DONTUSENEWLINE
138 static int UseNewLine = 1; /* Use newlines query delimiters (the
142 static int UseNewLine = 0; /* Use EOF as query delimiters */
143 #endif /* TCOP_DONTUSENEWLINE */
146 /* ----------------------------------------------------------------
147 * decls for routines only used in this file
148 * ----------------------------------------------------------------
150 static int InteractiveBackend(StringInfo inBuf);
151 static int SocketBackend(StringInfo inBuf);
152 static int ReadCommand(StringInfo inBuf);
153 static void start_xact_command(void);
154 static void finish_xact_command(void);
155 static void SigHupHandler(SIGNAL_ARGS);
156 static void FloatExceptionHandler(SIGNAL_ARGS);
159 /* ----------------------------------------------------------------
160 * routines to obtain user input
161 * ----------------------------------------------------------------
165 * InteractiveBackend() is called for user interactive connections
167 * the string entered by the user is placed in its parameter inBuf,
168 * and we act like a Q message was received.
170 * EOF is returned if end-of-file input is seen; time to shut down.
175 InteractiveBackend(StringInfo inBuf)
177 int c; /* character read from getc() */
178 bool end = false; /* end-of-input flag */
179 bool backslashSeen = false; /* have we seen a \ ? */
182 * display a prompt and obtain input from the user
187 /* Reset inBuf to empty */
189 inBuf->data[0] = '\0';
197 * if we are using \n as a delimiter, then read characters
200 while ((c = getc(stdin)) != EOF)
206 /* discard backslash from inBuf */
207 inBuf->data[--inBuf->len] = '\0';
208 backslashSeen = false;
213 /* keep the newline character */
214 appendStringInfoChar(inBuf, '\n');
219 backslashSeen = true;
221 backslashSeen = false;
223 appendStringInfoChar(inBuf, (char) c);
232 * otherwise read characters until EOF.
234 while ((c = getc(stdin)) != EOF)
235 appendStringInfoChar(inBuf, (char) c);
245 * otherwise we have a user query so process it.
250 /* Add '\0' to make it look the same as message case. */
251 appendStringInfoChar(inBuf, (char) '\0');
254 * if the query echo flag was given, print the query..
257 printf("statement: %s\n", inBuf->data);
264 * SocketBackend() Is called for frontend-backend connections
266 * Returns the message type code, and loads message body data into inBuf.
268 * EOF is returned if the connection is lost.
272 SocketBackend(StringInfo inBuf)
277 * Get message type code from the frontend.
279 qtype = pq_getbyte();
281 if (qtype == EOF) /* frontend disconnected */
284 (errcode(ERRCODE_PROTOCOL_VIOLATION),
285 errmsg("unexpected EOF on client connection")));
290 * Validate message type code before trying to read body; if we have
291 * lost sync, better to say "command unknown" than to run out of
292 * memory because we used garbage as a length word.
294 * This also gives us a place to set the doing_extended_query_message
295 * flag as soon as possible.
299 case 'Q': /* simple query */
300 doing_extended_query_message = false;
301 if (PG_PROTOCOL_MAJOR(FrontendProtocol) < 3)
303 /* old style without length word; convert */
304 if (pq_getstring(inBuf))
307 (errcode(ERRCODE_PROTOCOL_VIOLATION),
308 errmsg("unexpected EOF on client connection")));
314 case 'F': /* fastpath function call */
315 /* we let fastpath.c cope with old-style input of this */
316 doing_extended_query_message = false;
319 case 'X': /* terminate */
320 doing_extended_query_message = false;
321 ignore_till_sync = false;
325 case 'C': /* close */
326 case 'D': /* describe */
327 case 'E': /* execute */
328 case 'H': /* flush */
329 case 'P': /* parse */
330 doing_extended_query_message = true;
331 /* these are only legal in protocol 3 */
332 if (PG_PROTOCOL_MAJOR(FrontendProtocol) < 3)
334 (errcode(ERRCODE_PROTOCOL_VIOLATION),
335 errmsg("invalid frontend message type %d", qtype)));
339 /* stop any active skip-till-Sync */
340 ignore_till_sync = false;
341 /* mark not-extended, so that a new error doesn't begin skip */
342 doing_extended_query_message = false;
343 /* only legal in protocol 3 */
344 if (PG_PROTOCOL_MAJOR(FrontendProtocol) < 3)
346 (errcode(ERRCODE_PROTOCOL_VIOLATION),
347 errmsg("invalid frontend message type %d", qtype)));
350 case 'd': /* copy data */
351 case 'c': /* copy done */
352 case 'f': /* copy fail */
353 doing_extended_query_message = false;
354 /* these are only legal in protocol 3 */
355 if (PG_PROTOCOL_MAJOR(FrontendProtocol) < 3)
357 (errcode(ERRCODE_PROTOCOL_VIOLATION),
358 errmsg("invalid frontend message type %d", qtype)));
364 * Otherwise we got garbage from the frontend. We treat this
365 * as fatal because we have probably lost message boundary
366 * sync, and there's no good way to recover.
369 (errcode(ERRCODE_PROTOCOL_VIOLATION),
370 errmsg("invalid frontend message type %d", qtype)));
375 * In protocol version 3, all frontend messages have a length word
376 * next after the type code; we can read the message contents
377 * independently of the type.
379 if (PG_PROTOCOL_MAJOR(FrontendProtocol) >= 3)
381 if (pq_getmessage(inBuf, 0))
382 return EOF; /* suitable message already logged */
389 * ReadCommand reads a command from either the frontend or
390 * standard input, places it in inBuf, and returns the
391 * message type code (first byte of the message).
392 * EOF is returned if end of file.
396 ReadCommand(StringInfo inBuf)
400 if (IsUnderPostmaster)
401 result = SocketBackend(inBuf);
403 result = InteractiveBackend(inBuf);
409 * Parse a query string and pass it through the rewriter.
411 * A list of Query nodes is returned, since the string might contain
412 * multiple queries and/or the rewriter might expand one query to several.
414 * NOTE: this routine is no longer used for processing interactive queries,
415 * but it is still needed for parsing of SQL function bodies.
418 pg_parse_and_rewrite(const char *query_string, /* string to execute */
419 Oid *paramTypes, /* parameter types */
420 int numParams) /* number of parameters */
422 List *raw_parsetree_list;
423 List *querytree_list;
427 * (1) parse the request string into a list of raw parse trees.
429 raw_parsetree_list = pg_parse_query(query_string);
432 * (2) Do parse analysis and rule rewrite.
434 querytree_list = NIL;
435 foreach(list_item, raw_parsetree_list)
437 Node *parsetree = (Node *) lfirst(list_item);
439 querytree_list = nconc(querytree_list,
440 pg_analyze_and_rewrite(parsetree,
445 return querytree_list;
449 * Do raw parsing (only).
451 * A list of parsetrees is returned, since there might be multiple
452 * commands in the given string.
454 * NOTE: for interactive queries, it is important to keep this routine
455 * separate from the analysis & rewrite stages. Analysis and rewriting
456 * cannot be done in an aborted transaction, since they require access to
457 * database tables. So, we rely on the raw parser to determine whether
458 * we've seen a COMMIT or ABORT command; when we are in abort state, other
459 * commands are not processed any further than the raw parse stage.
462 pg_parse_query(const char *query_string)
464 List *raw_parsetree_list;
468 (errmsg("statement: %s", query_string)));
470 if (log_parser_stats)
473 raw_parsetree_list = raw_parser(query_string);
475 if (log_parser_stats)
476 ShowUsage("PARSER STATISTICS");
478 return raw_parsetree_list;
482 * Given a raw parsetree (gram.y output), and optionally information about
483 * types of parameter symbols ($n), perform parse analysis and rule rewriting.
485 * A list of Query nodes is returned, since either the analyzer or the
486 * rewriter might expand one query to several.
488 * NOTE: for reasons mentioned above, this must be separate from raw parsing.
491 pg_analyze_and_rewrite(Node *parsetree, Oid *paramTypes, int numParams)
493 List *querytree_list;
496 * (1) Perform parse analysis.
498 if (log_parser_stats)
501 querytree_list = parse_analyze(parsetree, paramTypes, numParams);
503 if (log_parser_stats)
504 ShowUsage("PARSE ANALYSIS STATISTICS");
507 * (2) Rewrite the queries, as necessary
509 querytree_list = pg_rewrite_queries(querytree_list);
511 return querytree_list;
515 * Perform rewriting of a list of queries produced by parse analysis.
518 pg_rewrite_queries(List *querytree_list)
520 List *new_list = NIL;
523 if (log_parser_stats)
527 * rewritten queries are collected in new_list. Note there may be
528 * more or fewer than in the original list.
530 foreach(list_item, querytree_list)
532 Query *querytree = (Query *) lfirst(list_item);
534 if (Debug_print_parse)
535 elog_node_display(DEBUG1, "parse tree", querytree,
538 if (querytree->commandType == CMD_UTILITY)
540 /* don't rewrite utilities, just dump 'em into new_list */
541 new_list = lappend(new_list, querytree);
545 /* rewrite regular queries */
546 List *rewritten = QueryRewrite(querytree);
548 new_list = nconc(new_list, rewritten);
552 querytree_list = new_list;
554 if (log_parser_stats)
555 ShowUsage("REWRITER STATISTICS");
557 #ifdef COPY_PARSE_PLAN_TREES
560 * Optional debugging check: pass querytree output through
563 new_list = (List *) copyObject(querytree_list);
564 /* This checks both copyObject() and the equal() routines... */
565 if (!equal(new_list, querytree_list))
566 elog(WARNING, "copyObject() failed to produce an equal parse tree");
568 querytree_list = new_list;
571 if (Debug_print_rewritten)
572 elog_node_display(DEBUG1, "rewritten parse tree", querytree_list,
575 return querytree_list;
579 /* Generate a plan for a single already-rewritten query. */
581 pg_plan_query(Query *querytree)
585 /* Utility commands have no plans. */
586 if (querytree->commandType == CMD_UTILITY)
589 if (log_planner_stats)
592 /* call the optimizer */
593 plan = planner(querytree, false, 0);
595 if (log_planner_stats)
596 ShowUsage("PLANNER STATISTICS");
598 #ifdef COPY_PARSE_PLAN_TREES
599 /* Optional debugging check: pass plan output through copyObject() */
601 Plan *new_plan = (Plan *) copyObject(plan);
604 * equal() currently does not have routines to compare Plan nodes,
605 * so don't try to test equality here. Perhaps fix someday?
608 /* This checks both copyObject() and the equal() routines... */
609 if (!equal(new_plan, plan))
610 elog(WARNING, "copyObject() failed to produce an equal plan tree");
618 * Print plan if debugging.
620 if (Debug_print_plan)
621 elog_node_display(DEBUG1, "plan", plan, Debug_pretty_print);
627 * Generate plans for a list of already-rewritten queries.
629 * If needSnapshot is TRUE, we haven't yet set a snapshot for the current
630 * query. A snapshot must be set before invoking the planner, since it
631 * might try to evaluate user-defined functions. But we must not set a
632 * snapshot if the list contains only utility statements, because some
633 * utility statements depend on not having frozen the snapshot yet.
634 * (We assume that such statements cannot appear together with plannable
635 * statements in the rewriter's output.)
638 pg_plan_queries(List *querytrees, bool needSnapshot)
640 List *plan_list = NIL;
643 foreach(query_list, querytrees)
645 Query *query = (Query *) lfirst(query_list);
648 if (query->commandType == CMD_UTILITY)
650 /* Utility commands have no plans. */
658 needSnapshot = false;
660 plan = pg_plan_query(query);
663 plan_list = lappend(plan_list, plan);
673 * Execute a "simple Query" protocol message.
676 exec_simple_query(const char *query_string)
678 CommandDest dest = whereToSendOutput;
679 MemoryContext oldcontext;
680 List *parsetree_list,
682 struct timeval start_t,
684 bool save_log_duration = log_duration;
685 int save_log_min_duration_statement = log_min_duration_statement;
686 bool save_log_statement_stats = log_statement_stats;
689 * Report query to various monitoring facilities.
691 debug_query_string = query_string;
693 pgstat_report_activity(query_string);
696 * We use save_log_* so "SET log_duration = true" and "SET
697 * log_min_duration_statement = true" don't report incorrect time
698 * because gettimeofday() wasn't called. Similarly,
699 * log_statement_stats has to be captured once.
701 if (save_log_duration || save_log_min_duration_statement != -1)
702 gettimeofday(&start_t, NULL);
704 if (save_log_statement_stats)
708 * Start up a transaction command. All queries generated by the
709 * query_string will be in this same command block, *unless* we find a
710 * BEGIN/COMMIT/ABORT statement; we have to force a new xact command
711 * after one of those, else bad things will happen in xact.c. (Note
712 * that this will normally change current memory context.)
714 start_xact_command();
717 * Zap any pre-existing unnamed statement. (While not strictly
718 * necessary, it seems best to define simple-Query mode as if it used
719 * the unnamed statement and portal; this ensures we recover any
720 * storage used by prior unnamed operations.)
722 unnamed_stmt_pstmt = NULL;
723 if (unnamed_stmt_context)
725 DropDependentPortals(unnamed_stmt_context);
726 MemoryContextDelete(unnamed_stmt_context);
728 unnamed_stmt_context = NULL;
731 * Switch to appropriate context for constructing parsetrees.
733 oldcontext = MemoryContextSwitchTo(MessageContext);
735 QueryContext = CurrentMemoryContext;
738 * Do basic parsing of the query or queries (this should be safe even
739 * if we are in aborted transaction state!)
741 parsetree_list = pg_parse_query(query_string);
744 * Switch back to transaction context to enter the loop.
746 MemoryContextSwitchTo(oldcontext);
749 * Run through the raw parsetree(s) and process each one.
751 foreach(parsetree_item, parsetree_list)
753 Node *parsetree = (Node *) lfirst(parsetree_item);
754 const char *commandTag;
755 char completionTag[COMPLETION_TAG_BUFSIZE];
756 List *querytree_list,
759 DestReceiver *receiver;
763 * Get the command name for use in status display (it also becomes
764 * the default completion tag, down inside PortalRun). Set
765 * ps_status and do any special start-of-SQL-command processing
766 * needed by the destination.
768 commandTag = CreateCommandTag(parsetree);
770 set_ps_display(commandTag);
772 BeginCommand(commandTag, dest);
775 * If we are in an aborted transaction, reject all commands except
776 * COMMIT/ABORT. It is important that this test occur before we
777 * try to do parse analysis, rewrite, or planning, since all those
778 * phases try to do database accesses, which may fail in abort
779 * state. (It might be safe to allow some additional utility
780 * commands in this state, but not many...)
782 if (IsAbortedTransactionBlockState())
784 bool allowit = false;
786 if (IsA(parsetree, TransactionStmt))
788 TransactionStmt *stmt = (TransactionStmt *) parsetree;
790 if (stmt->kind == TRANS_STMT_COMMIT ||
791 stmt->kind == TRANS_STMT_ROLLBACK)
797 (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
798 errmsg("current transaction is aborted, "
799 "commands ignored until end of transaction block")));
802 /* Make sure we are in a transaction command */
803 start_xact_command();
805 /* If we got a cancel signal in parsing or prior command, quit */
806 CHECK_FOR_INTERRUPTS();
809 * OK to analyze, rewrite, and plan this query.
811 * Switch to appropriate context for constructing querytrees (again,
812 * these must outlive the execution context).
814 oldcontext = MemoryContextSwitchTo(MessageContext);
816 querytree_list = pg_analyze_and_rewrite(parsetree, NULL, 0);
818 plantree_list = pg_plan_queries(querytree_list, true);
820 /* If we got a cancel signal in analysis or planning, quit */
821 CHECK_FOR_INTERRUPTS();
824 * Create unnamed portal to run the query or queries in. If there
825 * already is one, silently drop it.
827 portal = CreatePortal("", true, true);
829 PortalDefineQuery(portal,
837 * Start the portal. No parameters here.
839 PortalStart(portal, NULL);
842 * Select the appropriate output format: text unless we are doing
843 * a FETCH from a binary cursor. (Pretty grotty to have to do
844 * this here --- but it avoids grottiness in other places. Ah,
845 * the joys of backward compatibility...)
847 format = 0; /* TEXT is default */
848 if (IsA(parsetree, FetchStmt))
850 FetchStmt *stmt = (FetchStmt *) parsetree;
854 Portal fportal = GetPortalByName(stmt->portalname);
856 if (PortalIsValid(fportal) &&
857 (fportal->cursorOptions & CURSOR_OPT_BINARY))
858 format = 1; /* BINARY */
861 PortalSetResultFormat(portal, 1, &format);
864 * Now we can create the destination receiver object.
866 receiver = CreateDestReceiver(dest, portal);
869 * Switch back to transaction context for execution.
871 MemoryContextSwitchTo(oldcontext);
874 * Run the portal to completion, and then drop it (and the
877 (void) PortalRun(portal,
883 (*receiver->rDestroy) (receiver);
885 PortalDrop(portal, false);
887 if (IsA(parsetree, TransactionStmt))
890 * If this was a transaction control statement, commit it. We
891 * will start a new xact command for the next command (if
894 finish_xact_command();
896 else if (lnext(parsetree_item) == NIL)
899 * If this is the last parsetree of the query string, close
900 * down transaction statement before reporting
901 * command-complete. This is so that any end-of-transaction
902 * errors are reported before the command-complete message is
903 * issued, to avoid confusing clients who will expect either a
904 * command-complete message or an error, not one and then the
905 * other. But for compatibility with historical Postgres
906 * behavior, we do not force a transaction boundary between
907 * queries appearing in a single query string.
909 finish_xact_command();
914 * We need a CommandCounterIncrement after every query, except
915 * those that start or end a transaction block.
917 CommandCounterIncrement();
921 * Tell client that we're done with this query. Note we emit
922 * exactly one EndCommand report for each raw parsetree, thus one
923 * for each SQL command the client sent, regardless of rewriting.
924 * (But a command aborted by error will not send an EndCommand
927 EndCommand(completionTag, dest);
928 } /* end loop over parsetrees */
931 * Close down transaction statement, if one is open.
933 finish_xact_command();
936 * If there were no parsetrees, return EmptyQueryResponse message.
944 * Combine processing here as we need to calculate the query duration
947 if (save_log_duration || save_log_min_duration_statement != -1)
951 gettimeofday(&stop_t, NULL);
952 if (stop_t.tv_usec < start_t.tv_usec)
955 stop_t.tv_usec += 1000000;
957 usecs = (long) (stop_t.tv_sec - start_t.tv_sec) * 1000000 + (long) (stop_t.tv_usec - start_t.tv_usec);
959 if (save_log_duration)
961 (errmsg("duration: %ld.%03ld ms",
962 (long) ((stop_t.tv_sec - start_t.tv_sec) * 1000 +
963 (stop_t.tv_usec - start_t.tv_usec) / 1000),
964 (long) (stop_t.tv_usec - start_t.tv_usec) % 1000)));
967 * Output a duration_statement to the log if the query has exceeded
968 * the min duration, or if we are to print all durations.
970 if (save_log_min_duration_statement == 0 ||
971 (save_log_min_duration_statement > 0 &&
972 usecs >= save_log_min_duration_statement * 1000))
974 (errmsg("duration: %ld.%03ld ms statement: %s",
975 (long) ((stop_t.tv_sec - start_t.tv_sec) * 1000 +
976 (stop_t.tv_usec - start_t.tv_usec) / 1000),
977 (long) (stop_t.tv_usec - start_t.tv_usec) % 1000,
981 if (save_log_statement_stats)
982 ShowUsage("QUERY STATISTICS");
984 debug_query_string = NULL;
990 * Execute a "Parse" protocol message.
993 exec_parse_message(const char *query_string, /* string to execute */
994 const char *stmt_name, /* name for prepared stmt */
995 Oid *paramTypes, /* parameter types */
996 int numParams) /* number of parameters */
998 MemoryContext oldcontext;
999 List *parsetree_list;
1000 const char *commandTag;
1001 List *querytree_list,
1005 bool save_log_statement_stats = log_statement_stats;
1008 * Report query to various monitoring facilities.
1010 debug_query_string = query_string;
1012 pgstat_report_activity(query_string);
1014 set_ps_display("PARSE");
1016 if (save_log_statement_stats)
1020 * Start up a transaction command so we can run parse analysis etc.
1021 * (Note that this will normally change current memory context.)
1022 * Nothing happens if we are already in one.
1024 start_xact_command();
1027 * Switch to appropriate context for constructing parsetrees.
1029 * We have two strategies depending on whether the prepared statement is
1030 * named or not. For a named prepared statement, we do parsing in
1031 * MessageContext and copy the finished trees into the prepared
1032 * statement's private context; then the reset of MessageContext
1033 * releases temporary space used by parsing and planning. For an
1034 * unnamed prepared statement, we assume the statement isn't going to
1035 * hang around long, so getting rid of temp space quickly is probably
1036 * not worth the costs of copying parse/plan trees. So in this case,
1037 * we set up a special context for the unnamed statement, and do all
1038 * the parsing/planning therein.
1040 is_named = (stmt_name[0] != '\0');
1043 /* Named prepared statement --- parse in MessageContext */
1044 oldcontext = MemoryContextSwitchTo(MessageContext);
1048 /* Unnamed prepared statement --- release any prior unnamed stmt */
1049 unnamed_stmt_pstmt = NULL;
1050 if (unnamed_stmt_context)
1052 DropDependentPortals(unnamed_stmt_context);
1053 MemoryContextDelete(unnamed_stmt_context);
1055 unnamed_stmt_context = NULL;
1056 /* create context for parsing/planning */
1057 unnamed_stmt_context =
1058 AllocSetContextCreate(TopMemoryContext,
1059 "unnamed prepared statement",
1060 ALLOCSET_DEFAULT_MINSIZE,
1061 ALLOCSET_DEFAULT_INITSIZE,
1062 ALLOCSET_DEFAULT_MAXSIZE);
1063 oldcontext = MemoryContextSwitchTo(unnamed_stmt_context);
1066 QueryContext = CurrentMemoryContext;
1069 * Do basic parsing of the query or queries (this should be safe even
1070 * if we are in aborted transaction state!)
1072 parsetree_list = pg_parse_query(query_string);
1075 * We only allow a single user statement in a prepared statement. This
1076 * is mainly to keep the protocol simple --- otherwise we'd need to
1077 * worry about multiple result tupdescs and things like that.
1079 if (length(parsetree_list) > 1)
1081 (errcode(ERRCODE_SYNTAX_ERROR),
1082 errmsg("cannot insert multiple commands into a prepared statement")));
1084 if (parsetree_list != NIL)
1086 Node *parsetree = (Node *) lfirst(parsetree_list);
1090 * Get the command name for possible use in status display.
1092 commandTag = CreateCommandTag(parsetree);
1095 * If we are in an aborted transaction, reject all commands except
1096 * COMMIT/ROLLBACK. It is important that this test occur before
1097 * we try to do parse analysis, rewrite, or planning, since all
1098 * those phases try to do database accesses, which may fail in
1099 * abort state. (It might be safe to allow some additional utility
1100 * commands in this state, but not many...)
1102 if (IsAbortedTransactionBlockState())
1104 bool allowit = false;
1106 if (IsA(parsetree, TransactionStmt))
1108 TransactionStmt *stmt = (TransactionStmt *) parsetree;
1110 if (stmt->kind == TRANS_STMT_COMMIT ||
1111 stmt->kind == TRANS_STMT_ROLLBACK)
1117 (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
1118 errmsg("current transaction is aborted, "
1119 "commands ignored until end of transaction block")));
1123 * OK to analyze, rewrite, and plan this query. Note that the
1124 * originally specified parameter set is not required to be
1125 * complete, so we have to use parse_analyze_varparams().
1127 if (log_parser_stats)
1130 querytree_list = parse_analyze_varparams(parsetree,
1135 * Check all parameter types got determined, and convert array
1136 * representation to a list for storage.
1139 for (i = 0; i < numParams; i++)
1141 Oid ptype = paramTypes[i];
1143 if (ptype == InvalidOid || ptype == UNKNOWNOID)
1145 (errcode(ERRCODE_INDETERMINATE_DATATYPE),
1146 errmsg("could not determine data type of parameter $%d",
1148 param_list = lappendo(param_list, ptype);
1151 if (log_parser_stats)
1152 ShowUsage("PARSE ANALYSIS STATISTICS");
1154 querytree_list = pg_rewrite_queries(querytree_list);
1156 plantree_list = pg_plan_queries(querytree_list, true);
1160 /* Empty input string. This is legal. */
1162 querytree_list = NIL;
1163 plantree_list = NIL;
1167 /* If we got a cancel signal in analysis or planning, quit */
1168 CHECK_FOR_INTERRUPTS();
1171 * Store the query as a prepared statement. See above comments.
1175 StorePreparedStatement(stmt_name,
1184 PreparedStatement *pstmt;
1186 pstmt = (PreparedStatement *) palloc0(sizeof(PreparedStatement));
1187 /* query_string needs to be copied into unnamed_stmt_context */
1188 pstmt->query_string = pstrdup(query_string);
1189 /* the rest is there already */
1190 pstmt->commandTag = commandTag;
1191 pstmt->query_list = querytree_list;
1192 pstmt->plan_list = plantree_list;
1193 pstmt->argtype_list = param_list;
1194 pstmt->context = unnamed_stmt_context;
1195 /* Now the unnamed statement is complete and valid */
1196 unnamed_stmt_pstmt = pstmt;
1199 MemoryContextSwitchTo(oldcontext);
1201 QueryContext = NULL;
1204 * We do NOT close the open transaction command here; that only
1205 * happens when the client sends Sync. Instead, do
1206 * CommandCounterIncrement just in case something happened during
1209 CommandCounterIncrement();
1212 * Send ParseComplete.
1214 if (whereToSendOutput == Remote)
1215 pq_putemptymessage('1');
1217 if (save_log_statement_stats)
1218 ShowUsage("PARSE MESSAGE STATISTICS");
1220 debug_query_string = NULL;
1226 * Process a "Bind" message to create a portal from a prepared statement
1229 exec_bind_message(StringInfo input_message)
1231 const char *portal_name;
1232 const char *stmt_name;
1234 int16 *pformats = NULL;
1237 int16 *rformats = NULL;
1239 PreparedStatement *pstmt;
1241 ParamListInfo params;
1243 pgstat_report_activity("<BIND>");
1245 set_ps_display("BIND");
1248 * Start up a transaction command so we can call functions etc. (Note
1249 * that this will normally change current memory context.) Nothing
1250 * happens if we are already in one.
1252 start_xact_command();
1254 /* Switch back to message context */
1255 MemoryContextSwitchTo(MessageContext);
1257 /* Get the fixed part of the message */
1258 portal_name = pq_getmsgstring(input_message);
1259 stmt_name = pq_getmsgstring(input_message);
1261 /* Get the parameter format codes */
1262 numPFormats = pq_getmsgint(input_message, 2);
1263 if (numPFormats > 0)
1265 pformats = (int16 *) palloc(numPFormats * sizeof(int16));
1266 for (i = 0; i < numPFormats; i++)
1267 pformats[i] = pq_getmsgint(input_message, 2);
1270 /* Get the parameter value count */
1271 numParams = pq_getmsgint(input_message, 2);
1273 if (numPFormats > 1 && numPFormats != numParams)
1275 (errcode(ERRCODE_PROTOCOL_VIOLATION),
1276 errmsg("bind message has %d parameter formats but %d parameters",
1277 numPFormats, numParams)));
1279 /* Find prepared statement */
1280 if (stmt_name[0] != '\0')
1281 pstmt = FetchPreparedStatement(stmt_name, true);
1284 /* special-case the unnamed statement */
1285 pstmt = unnamed_stmt_pstmt;
1288 (errcode(ERRCODE_UNDEFINED_PSTATEMENT),
1289 errmsg("unnamed prepared statement does not exist")));
1292 if (numParams != length(pstmt->argtype_list))
1294 (errcode(ERRCODE_PROTOCOL_VIOLATION),
1295 errmsg("bind message supplies %d parameters, but prepared statement \"%s\" requires %d",
1296 numParams, stmt_name, length(pstmt->argtype_list))));
1299 * Create the portal. Allow silent replacement of an existing portal
1300 * only if the unnamed portal is specified.
1302 if (portal_name[0] == '\0')
1303 portal = CreatePortal(portal_name, true, true);
1305 portal = CreatePortal(portal_name, false, false);
1307 PortalDefineQuery(portal,
1308 pstmt->query_string,
1315 * Fetch parameters, if any, and store in the portal's memory context.
1317 * In an aborted transaction, we can't risk calling user-defined
1318 * functions, but we can't fail to Bind either, so bind all parameters
1323 bool isaborted = IsAbortedTransactionBlockState();
1325 MemoryContext oldContext;
1327 oldContext = MemoryContextSwitchTo(PortalGetHeapMemory(portal));
1329 params = (ParamListInfo)
1330 palloc0((numParams + 1) * sizeof(ParamListInfoData));
1333 foreach(l, pstmt->argtype_list)
1335 Oid ptype = lfirsto(l);
1339 plength = pq_getmsgint(input_message, 4);
1340 isNull = (plength == -1);
1344 const char *pvalue = pq_getmsgbytes(input_message, plength);
1348 /* We don't bother to check the format in this case */
1354 StringInfoData pbuf;
1357 if (numPFormats > 1)
1358 pformat = pformats[i];
1359 else if (numPFormats > 0)
1360 pformat = pformats[0];
1362 pformat = 0; /* default = text */
1365 * Rather than copying data around, we just set up a
1366 * phony StringInfo pointing to the correct portion of
1367 * the message buffer. We assume we can scribble on
1368 * the message buffer so as to maintain the convention
1369 * that StringInfos have a trailing null. This is
1370 * grotty but is a big win when dealing with very
1371 * large parameter strings.
1373 pbuf.data = (char *) pvalue;
1374 pbuf.maxlen = plength + 1;
1378 csave = pbuf.data[plength];
1379 pbuf.data[plength] = '\0';
1387 getTypeInputInfo(ptype, &typInput, &typElem);
1390 * We have to do encoding conversion before
1391 * calling the typinput routine.
1394 pg_client_to_server((unsigned char *) pbuf.data,
1397 OidFunctionCall3(typInput,
1398 CStringGetDatum(pstring),
1399 ObjectIdGetDatum(typElem),
1401 /* Free result of encoding conversion, if any */
1402 if (pstring != pbuf.data)
1405 else if (pformat == 1)
1411 * Call the parameter type's binary input
1414 getTypeBinaryInputInfo(ptype, &typReceive, &typElem);
1417 OidFunctionCall2(typReceive,
1418 PointerGetDatum(&pbuf),
1419 ObjectIdGetDatum(typElem));
1421 /* Trouble if it didn't eat the whole buffer */
1422 if (pbuf.cursor != pbuf.len)
1424 (errcode(ERRCODE_INVALID_BINARY_REPRESENTATION),
1425 errmsg("incorrect binary data format in bind parameter %d",
1431 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1432 errmsg("unsupported format code: %d",
1436 /* Restore message buffer contents */
1437 pbuf.data[plength] = csave;
1441 params[i].kind = PARAM_NUM;
1442 params[i].id = i + 1;
1443 params[i].isnull = isNull;
1448 params[i].kind = PARAM_INVALID;
1450 MemoryContextSwitchTo(oldContext);
1455 /* Get the result format codes */
1456 numRFormats = pq_getmsgint(input_message, 2);
1457 if (numRFormats > 0)
1459 rformats = (int16 *) palloc(numRFormats * sizeof(int16));
1460 for (i = 0; i < numRFormats; i++)
1461 rformats[i] = pq_getmsgint(input_message, 2);
1464 pq_getmsgend(input_message);
1467 * Start portal execution.
1469 PortalStart(portal, params);
1472 * Apply the result format requests to the portal.
1474 PortalSetResultFormat(portal, numRFormats, rformats);
1477 * Send BindComplete.
1479 if (whereToSendOutput == Remote)
1480 pq_putemptymessage('2');
1484 * exec_execute_message
1486 * Process an "Execute" message for a portal
1489 exec_execute_message(const char *portal_name, long max_rows)
1492 DestReceiver *receiver;
1494 bool is_trans_stmt = false;
1495 bool is_trans_exit = false;
1497 char completionTag[COMPLETION_TAG_BUFSIZE];
1499 /* Adjust destination to tell printtup.c what to do */
1500 dest = whereToSendOutput;
1502 dest = RemoteExecute;
1504 portal = GetPortalByName(portal_name);
1505 if (!PortalIsValid(portal))
1507 (errcode(ERRCODE_UNDEFINED_CURSOR),
1508 errmsg("portal \"%s\" does not exist", portal_name)));
1511 * If the original query was a null string, just return
1512 * EmptyQueryResponse.
1514 if (portal->commandTag == NULL)
1516 Assert(portal->parseTrees == NIL);
1521 if (portal->sourceText)
1523 debug_query_string = portal->sourceText;
1524 pgstat_report_activity(portal->sourceText);
1528 debug_query_string = "execute message";
1529 pgstat_report_activity("<EXECUTE>");
1532 set_ps_display(portal->commandTag);
1534 BeginCommand(portal->commandTag, dest);
1536 /* Check for transaction-control commands */
1537 if (length(portal->parseTrees) == 1)
1539 Query *query = (Query *) lfirst(portal->parseTrees);
1541 if (query->commandType == CMD_UTILITY &&
1542 query->utilityStmt != NULL &&
1543 IsA(query->utilityStmt, TransactionStmt))
1545 TransactionStmt *stmt = (TransactionStmt *) query->utilityStmt;
1547 is_trans_stmt = true;
1548 if (stmt->kind == TRANS_STMT_COMMIT ||
1549 stmt->kind == TRANS_STMT_ROLLBACK)
1550 is_trans_exit = true;
1555 * Create dest receiver in MessageContext (we don't want it in
1556 * transaction context, because that may get deleted if portal
1559 receiver = CreateDestReceiver(dest, portal);
1562 * Ensure we are in a transaction command (this should normally be the
1563 * case already due to prior BIND).
1565 start_xact_command();
1568 * If we are in aborted transaction state, the only portals we can
1569 * actually run are those containing COMMIT or ROLLBACK commands.
1571 if (IsAbortedTransactionBlockState())
1575 (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
1576 errmsg("current transaction is aborted, "
1577 "commands ignored until end of transaction block")));
1580 /* Check for cancel signal before we start execution */
1581 CHECK_FOR_INTERRUPTS();
1584 * Okay to run the portal.
1587 max_rows = FETCH_ALL;
1589 completed = PortalRun(portal,
1595 (*receiver->rDestroy) (receiver);
1602 * If this was a transaction control statement, commit it. We
1603 * will start a new xact command for the next command (if
1606 finish_xact_command();
1611 * We need a CommandCounterIncrement after every query, except
1612 * those that start or end a transaction block.
1614 CommandCounterIncrement();
1617 /* Send appropriate CommandComplete to client */
1618 EndCommand(completionTag, dest);
1622 /* Portal run not complete, so send PortalSuspended */
1623 if (whereToSendOutput == Remote)
1624 pq_putemptymessage('s');
1627 debug_query_string = NULL;
1631 * exec_describe_statement_message
1633 * Process a "Describe" message for a prepared statement
1636 exec_describe_statement_message(const char *stmt_name)
1638 PreparedStatement *pstmt;
1643 /* Find prepared statement */
1644 if (stmt_name[0] != '\0')
1645 pstmt = FetchPreparedStatement(stmt_name, true);
1648 /* special-case the unnamed statement */
1649 pstmt = unnamed_stmt_pstmt;
1652 (errcode(ERRCODE_UNDEFINED_PSTATEMENT),
1653 errmsg("unnamed prepared statement does not exist")));
1656 if (whereToSendOutput != Remote)
1657 return; /* can't actually do anything... */
1660 * First describe the parameters...
1662 pq_beginmessage(&buf, 't'); /* parameter description message type */
1663 pq_sendint(&buf, length(pstmt->argtype_list), 2);
1665 foreach(l, pstmt->argtype_list)
1667 Oid ptype = lfirsto(l);
1669 pq_sendint(&buf, (int) ptype, 4);
1671 pq_endmessage(&buf);
1674 * Next send RowDescription or NoData to describe the result...
1676 tupdesc = FetchPreparedStatementResultDesc(pstmt);
1681 if (ChoosePortalStrategy(pstmt->query_list) == PORTAL_ONE_SELECT)
1682 targetlist = ((Query *) lfirst(pstmt->query_list))->targetList;
1685 SendRowDescriptionMessage(tupdesc, targetlist, NULL);
1688 pq_putemptymessage('n'); /* NoData */
1693 * exec_describe_portal_message
1695 * Process a "Describe" message for a portal
1698 exec_describe_portal_message(const char *portal_name)
1702 portal = GetPortalByName(portal_name);
1703 if (!PortalIsValid(portal))
1705 (errcode(ERRCODE_UNDEFINED_CURSOR),
1706 errmsg("portal \"%s\" does not exist", portal_name)));
1708 if (whereToSendOutput != Remote)
1709 return; /* can't actually do anything... */
1711 if (portal->tupDesc)
1715 if (portal->strategy == PORTAL_ONE_SELECT)
1716 targetlist = ((Query *) lfirst(portal->parseTrees))->targetList;
1719 SendRowDescriptionMessage(portal->tupDesc, targetlist,
1723 pq_putemptymessage('n'); /* NoData */
1728 * Convenience routines for starting/committing a single command.
1731 start_xact_command(void)
1736 (errmsg_internal("StartTransactionCommand")));
1737 StartTransactionCommand();
1739 /* Set statement timeout running, if any */
1740 if (StatementTimeout > 0)
1741 enable_sig_alarm(StatementTimeout, true);
1743 xact_started = true;
1748 finish_xact_command(void)
1752 /* Invoke IMMEDIATE constraint triggers */
1753 DeferredTriggerEndQuery();
1755 /* Cancel any active statement timeout before committing */
1756 disable_sig_alarm(true);
1758 /* Now commit the command */
1760 (errmsg_internal("CommitTransactionCommand")));
1762 CommitTransactionCommand();
1764 #ifdef MEMORY_CONTEXT_CHECKING
1765 /* Check all memory contexts that weren't freed during commit */
1766 /* (those that were, were checked before being deleted) */
1767 MemoryContextCheck(TopMemoryContext);
1770 #ifdef SHOW_MEMORY_STATS
1771 /* Print mem stats after each commit for leak tracking */
1773 MemoryContextStats(TopMemoryContext);
1776 xact_started = false;
1781 /* --------------------------------
1782 * signal handler routines used in PostgresMain()
1783 * --------------------------------
1787 * quickdie() occurs when signalled SIGQUIT by the postmaster.
1789 * Some backend has bought the farm,
1790 * so we need to stop what we're doing and exit.
1793 quickdie(SIGNAL_ARGS)
1795 PG_SETMASK(&BlockSig);
1798 * Ideally this should be ereport(FATAL), but then we'd not get
1799 * control back (perhaps could fix by doing local sigsetjmp?)
1802 (errcode(ERRCODE_CRASH_SHUTDOWN),
1803 errmsg("terminating connection because of crash of another server process"),
1804 errdetail("The postmaster has commanded this server process to roll back"
1805 " the current transaction and exit, because another"
1806 " server process exited abnormally and possibly corrupted"
1808 errhint("In a moment you should be able to reconnect to the"
1809 " database and repeat your command.")));
1812 * DO NOT proc_exit() -- we're here because shared memory may be
1813 * corrupted, so we don't want to try to clean up our transaction.
1814 * Just nail the windows shut and get out of town.
1816 * Note we do exit(1) not exit(0). This is to force the postmaster into
1817 * a system reset cycle if some idiot DBA sends a manual SIGQUIT to a
1818 * random backend. This is necessary precisely because we don't clean
1819 * up our shared memory state.
1825 * Shutdown signal from postmaster: abort transaction and exit
1826 * at soonest convenient time
1831 int save_errno = errno;
1833 /* Don't joggle the elbow of proc_exit */
1834 if (!proc_exit_inprogress)
1836 InterruptPending = true;
1837 ProcDiePending = true;
1840 * If it's safe to interrupt, and we're waiting for input or a
1841 * lock, service the interrupt immediately
1843 if (ImmediateInterruptOK && InterruptHoldoffCount == 0 &&
1844 CritSectionCount == 0)
1846 /* bump holdoff count to make ProcessInterrupts() a no-op */
1847 /* until we are done getting ready for it */
1848 InterruptHoldoffCount++;
1849 DisableNotifyInterrupt();
1850 /* Make sure CheckDeadLock won't run while shutting down... */
1852 InterruptHoldoffCount--;
1853 ProcessInterrupts();
1861 * Timeout or shutdown signal from postmaster during client authentication.
1864 * XXX: possible future improvement: try to send a message indicating
1865 * why we are disconnecting. Problem is to be sure we don't block while
1866 * doing so, nor mess up the authentication message exchange.
1869 authdie(SIGNAL_ARGS)
1875 * Query-cancel signal from postmaster: abort current transaction
1876 * at soonest convenient time
1879 StatementCancelHandler(SIGNAL_ARGS)
1881 int save_errno = errno;
1884 * Don't joggle the elbow of proc_exit, nor an already-in-progress
1887 if (!proc_exit_inprogress && !InError)
1889 InterruptPending = true;
1890 QueryCancelPending = true;
1893 * If it's safe to interrupt, and we're waiting for a lock,
1894 * service the interrupt immediately. No point in interrupting if
1895 * we're waiting for input, however.
1897 if (ImmediateInterruptOK && InterruptHoldoffCount == 0 &&
1898 CritSectionCount == 0)
1900 /* bump holdoff count to make ProcessInterrupts() a no-op */
1901 /* until we are done getting ready for it */
1902 InterruptHoldoffCount++;
1903 if (LockWaitCancel())
1905 DisableNotifyInterrupt();
1906 InterruptHoldoffCount--;
1907 ProcessInterrupts();
1910 InterruptHoldoffCount--;
1917 /* signal handler for floating point exception */
1919 FloatExceptionHandler(SIGNAL_ARGS)
1922 (errcode(ERRCODE_FLOATING_POINT_EXCEPTION),
1923 errmsg("floating-point exception"),
1924 errdetail("An invalid floating-point operation was signaled. "
1925 "This probably means an out-of-range result or an "
1926 "invalid operation, such as division by zero.")));
1929 /* SIGHUP: set flag to re-read config file at next convenient time */
1931 SigHupHandler(SIGNAL_ARGS)
1938 * ProcessInterrupts: out-of-line portion of CHECK_FOR_INTERRUPTS() macro
1940 * If an interrupt condition is pending, and it's safe to service it,
1941 * then clear the flag and accept the interrupt. Called only when
1942 * InterruptPending is true.
1945 ProcessInterrupts(void)
1947 /* OK to accept interrupt now? */
1948 if (InterruptHoldoffCount != 0 || CritSectionCount != 0)
1950 InterruptPending = false;
1953 ProcDiePending = false;
1954 QueryCancelPending = false; /* ProcDie trumps QueryCancel */
1955 ImmediateInterruptOK = false; /* not idle anymore */
1956 DisableNotifyInterrupt();
1958 (errcode(ERRCODE_ADMIN_SHUTDOWN),
1959 errmsg("terminating connection due to administrator command")));
1961 if (QueryCancelPending)
1963 QueryCancelPending = false;
1964 ImmediateInterruptOK = false; /* not idle anymore */
1965 DisableNotifyInterrupt();
1967 (errcode(ERRCODE_QUERY_CANCELED),
1968 errmsg("canceling query due to user request")));
1970 /* If we get here, do nothing (probably, QueryCancelPending was reset) */
1975 usage(char *progname)
1977 printf(gettext("%s is the PostgreSQL stand-alone backend. It is not\nintended to be used by normal users.\n\n"), progname);
1979 printf(gettext("Usage:\n %s [OPTION]... [DBNAME]\n\n"), progname);
1980 printf(gettext("Options:\n"));
1981 #ifdef USE_ASSERT_CHECKING
1982 printf(gettext(" -A 1|0 enable/disable run-time assert checking\n"));
1984 printf(gettext(" -B NBUFFERS number of shared buffers\n"));
1985 printf(gettext(" -c NAME=VALUE set run-time parameter\n"));
1986 printf(gettext(" -d 0-5 debugging level (0 is off)\n"));
1987 printf(gettext(" -D DATADIR database directory\n"));
1988 printf(gettext(" -e use European date input format (DMY)\n"));
1989 printf(gettext(" -E echo query before execution\n"));
1990 printf(gettext(" -F turn fsync off\n"));
1991 printf(gettext(" -N do not use newline as interactive query delimiter\n"));
1992 printf(gettext(" -o FILENAME send stdout and stderr to given file\n"));
1993 printf(gettext(" -P disable system indexes\n"));
1994 printf(gettext(" -s show statistics after each query\n"));
1995 printf(gettext(" -S SORT-MEM set amount of memory for sorts (in kbytes)\n"));
1996 printf(gettext(" --describe-config describe configuration parameters, then exit\n"));
1997 printf(gettext(" --help show this help, then exit\n"));
1998 printf(gettext(" --version output version information, then exit\n"));
1999 printf(gettext("\nDeveloper options:\n"));
2000 printf(gettext(" -f s|i|n|m|h forbid use of some plan types\n"));
2001 printf(gettext(" -i do not execute queries\n"));
2002 printf(gettext(" -O allow system table structure changes\n"));
2003 printf(gettext(" -t pa|pl|ex show timings after each query\n"));
2004 printf(gettext(" -W NUM wait NUM seconds to allow attach from a debugger\n"));
2005 printf(gettext("\nReport bugs to <pgsql-bugs@postgresql.org>.\n"));
2010 /* ----------------------------------------------------------------
2012 * postgres main loop -- all backends, interactive or otherwise start here
2014 * argc/argv are the command line arguments to be used. (When being forked
2015 * by the postmaster, these are not the original argv array of the process.)
2016 * username is the (possibly authenticated) PostgreSQL user name to be used
2018 * ----------------------------------------------------------------
2021 PostgresMain(int argc, char *argv[], const char *username)
2024 const char *dbname = NULL;
2025 char *potential_DataDir = NULL;
2031 GucSource gucsource;
2034 StringInfoData input_message;
2035 volatile bool send_rfq = true;
2038 * Catch standard options before doing much else. This even works on
2039 * systems without getopt_long.
2041 if (!IsUnderPostmaster && argc > 1)
2043 if (strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-?") == 0)
2048 if (strcmp(argv[1], "--version") == 0 || strcmp(argv[1], "-V") == 0)
2050 puts("postgres (PostgreSQL) " PG_VERSION);
2056 * initialize globals (already done if under postmaster, but not if
2057 * standalone; cheap enough to do over)
2059 MyProcPid = getpid();
2062 * Fire up essential subsystems: error and memory management
2064 * If we are running under the postmaster, this is done already.
2066 if (!IsUnderPostmaster || ExecBackend)
2067 MemoryContextInit();
2069 set_ps_display("startup");
2071 SetProcessingMode(InitProcessing);
2074 * Set default values for command-line options.
2079 if (!IsUnderPostmaster)
2081 InitializeGUCOptions();
2082 potential_DataDir = getenv("PGDATA");
2086 * parse command line arguments
2088 * There are now two styles of command line layout for the backend:
2090 * For interactive use (not started from postmaster) the format is
2091 * postgres [switches] [databasename]
2092 * If the databasename is omitted it is taken to be the user name.
2094 * When started from the postmaster, the format is
2095 * postgres [secure switches] -p databasename [insecure switches]
2096 * Switches appearing after -p came from the client (via "options"
2097 * field of connection request). For security reasons we restrict
2098 * what these switches can do.
2102 /* all options are allowed until '-p' */
2104 ctx = debug_context = PGC_POSTMASTER;
2105 gucsource = PGC_S_ARGV; /* initial switches came from command line */
2107 while ((flag = getopt(argc, argv, "A:B:c:CD:d:Eef:FiNOPo:p:S:st:v:W:x:-:")) != -1)
2111 #ifdef USE_ASSERT_CHECKING
2112 SetConfigOption("debug_assertions", optarg, ctx, gucsource);
2115 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2116 errmsg("assert checking is not compiled in")));
2123 * specify the size of buffer pool
2125 SetConfigOption("shared_buffers", optarg, ctx, gucsource);
2131 * don't print version string
2136 case 'D': /* PGDATA directory */
2138 potential_DataDir = optarg;
2141 case 'd': /* debug level */
2144 * Client option can't decrease debug level. We have
2145 * to do the test here because we group priv and
2146 * client set GUC calls below, after we know the final
2149 if (ctx != PGC_BACKEND || atoi(optarg) > debug_flag)
2151 debug_flag = atoi(optarg);
2152 debug_context = ctx; /* save context for use
2154 /* Set server debugging level. */
2155 if (debug_flag != 0)
2157 char *debugstr = palloc(strlen("debug") + strlen(optarg) + 1);
2159 sprintf(debugstr, "debug%s", optarg);
2160 SetConfigOption("log_min_messages", debugstr, ctx, gucsource);
2167 * -d0 allows user to prevent postmaster debug
2168 * from propagating to backend. It would be
2169 * nice to set it to the postgresql.conf value
2172 SetConfigOption("log_min_messages", "notice",
2181 * E - echo the query the user entered
2189 * Use European date input format (DMY)
2191 SetConfigOption("datestyle", "euro", ctx, gucsource);
2199 SetConfigOption("fsync", "false", ctx, gucsource);
2205 * f - forbid generation of certain plans
2210 case 's': /* seqscan */
2211 tmp = "enable_seqscan";
2213 case 'i': /* indexscan */
2214 tmp = "enable_indexscan";
2216 case 't': /* tidscan */
2217 tmp = "enable_tidscan";
2219 case 'n': /* nestloop */
2220 tmp = "enable_nestloop";
2222 case 'm': /* mergejoin */
2223 tmp = "enable_mergejoin";
2225 case 'h': /* hashjoin */
2226 tmp = "enable_hashjoin";
2232 SetConfigOption(tmp, "false", ctx, gucsource);
2238 * N - Don't use newline as a query delimiter
2246 * allow system table structure modifications
2248 if (secure) /* XXX safe to allow from client??? */
2249 allowSystemTableMods = true;
2255 * ignore system indexes
2257 * As of PG 7.4 this is safe to allow from the client,
2258 * since it only disables reading the system indexes,
2259 * not writing them. Worst case consequence is slowness.
2261 IgnoreSystemIndexes(true);
2267 * o - send output (stdout and stderr) to the given file
2270 StrNCpy(OutputFileName, optarg, MAXPGPATH);
2275 * p - special flag passed if backend was forked by a
2281 IsUnderPostmaster = true;
2283 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("log_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 = "log_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("statement-level statistics are disabled because parser, planner, or executor statistics are on")));
2467 SetConfigOption("log_statement_stats", "false", ctx, gucsource);
2470 if (!IsUnderPostmaster || ExecBackend)
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);
2486 /* Acquire configuration parameters */
2487 if (IsUnderPostmaster)
2490 Port *port =(Port*)malloc(sizeof(Port));
2493 (errcode(ERRCODE_OUT_OF_MEMORY),
2494 errmsg("insufficient memory to allocate port")));
2496 read_nondefault_variables();
2497 read_backend_variables(getpid(),port);
2499 /* FIXME: [fork/exec] Ugh */
2505 if (!BackendInit(port))
2508 dbname = port->database_name;
2511 ProcessConfigFile(PGC_POSTMASTER);
2514 * Set up signal handlers and masks.
2516 * Note that postmaster blocked all signals before forking child process,
2517 * so there is no race condition whereby we might receive a signal
2518 * before we have set up the handler.
2520 * Also note: it's best not to use any signals that are SIG_IGNored in
2521 * the postmaster. If such a signal arrives before we are able to
2522 * change the handler to non-SIG_IGN, it'll get dropped. Instead,
2523 * make a dummy handler in the postmaster to reserve the signal. (Of
2524 * course, this isn't an issue for signals that are locally generated,
2525 * such as SIGALRM and SIGPIPE.)
2527 pqsignal(SIGHUP, SigHupHandler); /* set flag to read config file */
2528 pqsignal(SIGINT, StatementCancelHandler); /* cancel current query */
2529 pqsignal(SIGTERM, die); /* cancel current query and exit */
2530 pqsignal(SIGQUIT, quickdie); /* hard crash time */
2531 pqsignal(SIGALRM, handle_sig_alarm); /* timeout conditions */
2534 * Ignore failure to write to frontend. Note: if frontend closes
2535 * connection, we will notice it and exit cleanly when control next
2536 * returns to outer loop. This seems safer than forcing exit in the
2537 * midst of output during who-knows-what operation...
2539 pqsignal(SIGPIPE, SIG_IGN);
2540 pqsignal(SIGUSR1, SIG_IGN); /* this signal available for use */
2542 pqsignal(SIGUSR2, Async_NotifyHandler); /* flush also sinval cache */
2543 pqsignal(SIGFPE, FloatExceptionHandler);
2546 * Reset some signals that are accepted by postmaster but not by
2549 pqsignal(SIGCHLD, SIG_DFL); /* system() requires this on some
2554 /* We allow SIGQUIT (quickdie) at all times */
2555 #ifdef HAVE_SIGPROCMASK
2556 sigdelset(&BlockSig, SIGQUIT);
2558 BlockSig &= ~(sigmask(SIGQUIT));
2561 PG_SETMASK(&BlockSig); /* block everything except SIGQUIT */
2564 if (IsUnderPostmaster)
2566 /* noninteractive case: nothing should be left after switches */
2567 if (errs || argc != optind || dbname == NULL)
2570 (errcode(ERRCODE_SYNTAX_ERROR),
2571 errmsg("invalid command-line arguments for server process"),
2572 errhint("Try \"%s --help\" for more information.", argv[0])));
2575 AttachSharedMemoryAndSemaphores();
2583 /* interactive case: database name can be last arg on command line */
2584 if (errs || argc - optind > 1)
2587 (errcode(ERRCODE_SYNTAX_ERROR),
2588 errmsg("%s: invalid command-line arguments",
2590 errhint("Try \"%s --help\" for more information.", argv[0])));
2592 else if (argc - optind == 1)
2593 dbname = argv[optind];
2594 else if ((dbname = username) == NULL)
2597 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
2598 errmsg("%s: no database nor user name specified",
2603 * On some systems our dynloader code needs the executable's
2604 * pathname. (If under postmaster, this was done already.)
2606 if (FindExec(pg_pathname, argv[0], "postgres") < 0)
2608 (errmsg("%s: could not locate postgres executable",
2612 * Validate we have been given a reasonable-looking DataDir (if
2613 * under postmaster, assume postmaster did this already).
2615 ValidatePgVersion(DataDir);
2618 * Create lockfile for data directory.
2620 CreateDataDirLockFile(DataDir, false);
2626 * Start up xlog for standalone backend, and register to have it
2627 * closed down at exit.
2630 on_shmem_exit(ShutdownXLOG, 0);
2633 * Read any existing FSM cache file, and register to write one out
2637 on_shmem_exit(DumpFreeSpaceMap, 0);
2641 * General initialization.
2643 * NOTE: if you are tempted to add code in this vicinity, consider
2644 * putting it inside InitPostgres() instead. In particular, anything
2645 * that involves database access should be there, not here.
2648 (errmsg_internal("InitPostgres")));
2649 InitPostgres(dbname, username);
2651 SetProcessingMode(NormalProcessing);
2654 * Send this backend's cancellation info to the frontend.
2656 if (whereToSendOutput == Remote &&
2657 PG_PROTOCOL_MAJOR(FrontendProtocol) >= 2)
2661 pq_beginmessage(&buf, 'K');
2662 pq_sendint(&buf, (int32) MyProcPid, sizeof(int32));
2663 pq_sendint(&buf, (int32) MyCancelKey, sizeof(int32));
2664 pq_endmessage(&buf);
2665 /* Need not flush since ReadyForQuery will do it. */
2668 /* Welcome banner for non-frontend case */
2669 if (!IsUnderPostmaster)
2670 printf("\nPostgreSQL stand-alone backend %s\n", PG_VERSION);
2673 * Create the memory context we will use in the main loop.
2675 * MessageContext is reset once per iteration of the main loop, ie, upon
2676 * completion of processing of each command message from the client.
2678 MessageContext = AllocSetContextCreate(TopMemoryContext,
2680 ALLOCSET_DEFAULT_MINSIZE,
2681 ALLOCSET_DEFAULT_INITSIZE,
2682 ALLOCSET_DEFAULT_MAXSIZE);
2685 * Tell the statistics collector that we're alive and
2686 * to which database we belong.
2692 * POSTGRES main processing loop begins here
2694 * If an exception is encountered, processing resumes here so we abort
2695 * the current transaction and start a new one.
2698 if (sigsetjmp(Warn_restart, 1) != 0)
2701 * NOTE: if you are tempted to add more code in this if-block,
2702 * consider the probability that it should be in
2703 * AbortTransaction() instead.
2705 * Make sure we're not interrupted while cleaning up. Also forget
2706 * any pending QueryCancel request, since we're aborting anyway.
2707 * Force InterruptHoldoffCount to a known state in case we
2708 * ereport'd from inside a holdoff section.
2710 ImmediateInterruptOK = false;
2711 QueryCancelPending = false;
2712 InterruptHoldoffCount = 1;
2713 CritSectionCount = 0; /* should be unnecessary, but... */
2714 disable_sig_alarm(true);
2715 QueryCancelPending = false; /* again in case timeout occurred */
2716 DisableNotifyInterrupt();
2717 debug_query_string = NULL;
2720 * Make sure we are in a valid memory context during recovery.
2722 * We use ErrorContext in hopes that it will have some free space
2723 * even if we're otherwise up against it...
2725 MemoryContextSwitchTo(ErrorContext);
2727 /* Do the recovery */
2729 (errmsg_internal("AbortCurrentTransaction")));
2730 AbortCurrentTransaction();
2733 * Now return to normal top-level context and clear ErrorContext
2736 MemoryContextSwitchTo(TopMemoryContext);
2737 MemoryContextResetAndDeleteChildren(ErrorContext);
2738 PortalContext = NULL;
2739 QueryContext = NULL;
2742 * Clear flag to indicate that we got out of error recovery mode
2743 * successfully. (Flag was set in elog.c before longjmp().)
2746 xact_started = false;
2749 * If we were handling an extended-query-protocol message,
2750 * initiate skip till next Sync. This also causes us not to issue
2751 * ReadyForQuery (until we get Sync).
2753 if (doing_extended_query_message)
2754 ignore_till_sync = true;
2757 * Exit interrupt holdoff section we implicitly established above.
2759 RESUME_INTERRUPTS();
2762 Warn_restart_ready = true; /* we can now handle ereport(ERROR) */
2764 PG_SETMASK(&UnBlockSig);
2766 if (!ignore_till_sync)
2767 send_rfq = true; /* initially, or after error */
2770 * Non-error queries loop here.
2776 * At top of loop, reset extended-query-message flag, so that any
2777 * errors encountered in "idle" state don't provoke skip.
2779 doing_extended_query_message = false;
2782 * Release storage left over from prior query cycle, and create a
2783 * new query input buffer in the cleared MessageContext.
2785 MemoryContextSwitchTo(MessageContext);
2786 MemoryContextResetAndDeleteChildren(MessageContext);
2788 initStringInfo(&input_message);
2791 * (1) If we've reached idle state, tell the frontend we're ready
2794 * Note: this includes fflush()'ing the last of the prior output.
2796 * This is also a good time to send collected statistics to the
2797 * collector, and to update the PS stats display. We avoid doing
2798 * those every time through the message loop because it'd slow down
2799 * processing of batched messages.
2803 pgstat_report_tabstat();
2805 if (IsTransactionOrTransactionBlock())
2807 set_ps_display("idle in transaction");
2808 pgstat_report_activity("<IDLE> in transaction");
2812 set_ps_display("idle");
2813 pgstat_report_activity("<IDLE>");
2816 ReadyForQuery(whereToSendOutput);
2821 * (2) deal with pending asynchronous NOTIFY from other backends,
2822 * and enable async.c's signal handler to execute NOTIFY directly.
2823 * Then set up other stuff needed before blocking for input.
2825 QueryCancelPending = false; /* forget any earlier CANCEL
2828 EnableNotifyInterrupt();
2830 /* Allow "die" interrupt to be processed while waiting */
2831 ImmediateInterruptOK = true;
2832 /* and don't forget to detect one that already arrived */
2833 QueryCancelPending = false;
2834 CHECK_FOR_INTERRUPTS();
2837 * (3) read a command (loop blocks here)
2839 firstchar = ReadCommand(&input_message);
2842 * (4) disable async signal conditions again.
2844 ImmediateInterruptOK = false;
2845 QueryCancelPending = false; /* forget any CANCEL signal */
2847 DisableNotifyInterrupt();
2850 * (5) check for any other interesting events that happened while
2857 read_nondefault_variables();
2859 ProcessConfigFile(PGC_SIGHUP);
2864 * (6) process the command. But ignore it if we're skipping till
2867 if (ignore_till_sync && firstchar != EOF)
2872 case 'Q': /* simple query */
2874 const char *query_string;
2876 query_string = pq_getmsgstring(&input_message);
2877 pq_getmsgend(&input_message);
2879 exec_simple_query(query_string);
2885 case 'P': /* parse */
2887 const char *stmt_name;
2888 const char *query_string;
2890 Oid *paramTypes = NULL;
2892 stmt_name = pq_getmsgstring(&input_message);
2893 query_string = pq_getmsgstring(&input_message);
2894 numParams = pq_getmsgint(&input_message, 2);
2899 paramTypes = (Oid *) palloc(numParams * sizeof(Oid));
2900 for (i = 0; i < numParams; i++)
2901 paramTypes[i] = pq_getmsgint(&input_message, 4);
2903 pq_getmsgend(&input_message);
2905 exec_parse_message(query_string, stmt_name,
2906 paramTypes, numParams);
2910 case 'B': /* bind */
2913 * this message is complex enough that it seems best to
2914 * put the field extraction out-of-line
2916 exec_bind_message(&input_message);
2919 case 'E': /* execute */
2921 const char *portal_name;
2924 portal_name = pq_getmsgstring(&input_message);
2925 max_rows = pq_getmsgint(&input_message, 4);
2926 pq_getmsgend(&input_message);
2928 exec_execute_message(portal_name, max_rows);
2932 case 'F': /* fastpath function call */
2933 /* Tell the collector what we're doing */
2934 pgstat_report_activity("<FASTPATH> function call");
2936 /* start an xact for this function invocation */
2937 start_xact_command();
2939 /* switch back to message context */
2940 MemoryContextSwitchTo(MessageContext);
2942 if (HandleFunctionRequest(&input_message) == EOF)
2944 /* lost frontend connection during F message input */
2947 * Reset whereToSendOutput to prevent ereport from
2948 * attempting to send any more messages to client.
2950 if (whereToSendOutput == Remote)
2951 whereToSendOutput = None;
2956 /* commit the function-invocation transaction */
2957 finish_xact_command();
2962 case 'C': /* close */
2965 const char *close_target;
2967 close_type = pq_getmsgbyte(&input_message);
2968 close_target = pq_getmsgstring(&input_message);
2969 pq_getmsgend(&input_message);
2974 if (close_target[0] != '\0')
2975 DropPreparedStatement(close_target, false);
2978 /* special-case the unnamed statement */
2979 unnamed_stmt_pstmt = NULL;
2980 if (unnamed_stmt_context)
2982 DropDependentPortals(unnamed_stmt_context);
2983 MemoryContextDelete(unnamed_stmt_context);
2985 unnamed_stmt_context = NULL;
2992 portal = GetPortalByName(close_target);
2993 if (PortalIsValid(portal))
2994 PortalDrop(portal, false);
2999 (errcode(ERRCODE_PROTOCOL_VIOLATION),
3000 errmsg("invalid CLOSE message subtype %d",
3005 if (whereToSendOutput == Remote)
3006 pq_putemptymessage('3'); /* CloseComplete */
3010 case 'D': /* describe */
3013 const char *describe_target;
3015 describe_type = pq_getmsgbyte(&input_message);
3016 describe_target = pq_getmsgstring(&input_message);
3017 pq_getmsgend(&input_message);
3019 switch (describe_type)
3022 exec_describe_statement_message(describe_target);
3025 exec_describe_portal_message(describe_target);
3029 (errcode(ERRCODE_PROTOCOL_VIOLATION),
3030 errmsg("invalid DESCRIBE message subtype %d",
3037 case 'H': /* flush */
3038 pq_getmsgend(&input_message);
3039 if (whereToSendOutput == Remote)
3043 case 'S': /* sync */
3044 pq_getmsgend(&input_message);
3045 finish_xact_command();
3050 * 'X' means that the frontend is closing down the socket.
3051 * EOF means unexpected loss of frontend connection.
3052 * Either way, perform normal shutdown.
3058 * Reset whereToSendOutput to prevent ereport from
3059 * attempting to send any more messages to client.
3061 if (whereToSendOutput == Remote)
3062 whereToSendOutput = None;
3065 * NOTE: if you are tempted to add more code here, DON'T!
3066 * Whatever you had in mind to do should be set up as an
3067 * on_proc_exit or on_shmem_exit callback, instead.
3068 * Otherwise it will fail to be called during other
3069 * backend-shutdown scenarios.
3073 case 'd': /* copy data */
3074 case 'c': /* copy done */
3075 case 'f': /* copy fail */
3078 * Accept but ignore these messages, per protocol spec; we
3079 * probably got here because a COPY failed, and the
3080 * frontend is still sending data.
3086 (errcode(ERRCODE_PROTOCOL_VIOLATION),
3087 errmsg("invalid frontend message type %d",
3090 } /* end of input-reading loop */
3092 /* can't get here because the above loop never exits */
3095 return 1; /* keep compiler quiet */
3098 #ifndef HAVE_GETRUSAGE
3099 #include "rusagestub.h"
3101 #include <sys/resource.h>
3102 #endif /* HAVE_GETRUSAGE */
3104 static struct rusage Save_r;
3105 static struct timeval Save_t;
3110 getrusage(RUSAGE_SELF, &Save_r);
3111 gettimeofday(&Save_t, NULL);
3113 /* ResetTupleCount(); */
3117 ShowUsage(const char *title)
3120 struct timeval user,
3122 struct timeval elapse_t;
3126 getrusage(RUSAGE_SELF, &r);
3127 gettimeofday(&elapse_t, NULL);
3128 memcpy((char *) &user, (char *) &r.ru_utime, sizeof(user));
3129 memcpy((char *) &sys, (char *) &r.ru_stime, sizeof(sys));
3130 if (elapse_t.tv_usec < Save_t.tv_usec)
3133 elapse_t.tv_usec += 1000000;
3135 if (r.ru_utime.tv_usec < Save_r.ru_utime.tv_usec)
3137 r.ru_utime.tv_sec--;
3138 r.ru_utime.tv_usec += 1000000;
3140 if (r.ru_stime.tv_usec < Save_r.ru_stime.tv_usec)
3142 r.ru_stime.tv_sec--;
3143 r.ru_stime.tv_usec += 1000000;
3147 * the only stats we don't show here are for memory usage -- i can't
3148 * figure out how to interpret the relevant fields in the rusage
3149 * struct, and they change names across o/s platforms, anyway. if you
3150 * can figure out what the entries mean, you can somehow extract
3151 * resident set size, shared text size, and unshared data and stack
3154 initStringInfo(&str);
3156 appendStringInfo(&str, "! system usage stats:\n");
3157 appendStringInfo(&str,
3158 "!\t%ld.%06ld elapsed %ld.%06ld user %ld.%06ld system sec\n",
3159 (long) (elapse_t.tv_sec - Save_t.tv_sec),
3160 (long) (elapse_t.tv_usec - Save_t.tv_usec),
3161 (long) (r.ru_utime.tv_sec - Save_r.ru_utime.tv_sec),
3162 (long) (r.ru_utime.tv_usec - Save_r.ru_utime.tv_usec),
3163 (long) (r.ru_stime.tv_sec - Save_r.ru_stime.tv_sec),
3164 (long) (r.ru_stime.tv_usec - Save_r.ru_stime.tv_usec));
3165 appendStringInfo(&str,
3166 "!\t[%ld.%06ld user %ld.%06ld sys total]\n",
3168 (long) user.tv_usec,
3170 (long) sys.tv_usec);
3171 /* BeOS has rusage but only has some fields, and not these... */
3172 #if defined(HAVE_GETRUSAGE)
3173 appendStringInfo(&str,
3174 "!\t%ld/%ld [%ld/%ld] filesystem blocks in/out\n",
3175 r.ru_inblock - Save_r.ru_inblock,
3176 /* they only drink coffee at dec */
3177 r.ru_oublock - Save_r.ru_oublock,
3178 r.ru_inblock, r.ru_oublock);
3179 appendStringInfo(&str,
3180 "!\t%ld/%ld [%ld/%ld] page faults/reclaims, %ld [%ld] swaps\n",
3181 r.ru_majflt - Save_r.ru_majflt,
3182 r.ru_minflt - Save_r.ru_minflt,
3183 r.ru_majflt, r.ru_minflt,
3184 r.ru_nswap - Save_r.ru_nswap,
3186 appendStringInfo(&str,
3187 "!\t%ld [%ld] signals rcvd, %ld/%ld [%ld/%ld] messages rcvd/sent\n",
3188 r.ru_nsignals - Save_r.ru_nsignals,
3190 r.ru_msgrcv - Save_r.ru_msgrcv,
3191 r.ru_msgsnd - Save_r.ru_msgsnd,
3192 r.ru_msgrcv, r.ru_msgsnd);
3193 appendStringInfo(&str,
3194 "!\t%ld/%ld [%ld/%ld] voluntary/involuntary context switches\n",
3195 r.ru_nvcsw - Save_r.ru_nvcsw,
3196 r.ru_nivcsw - Save_r.ru_nivcsw,
3197 r.ru_nvcsw, r.ru_nivcsw);
3198 #endif /* HAVE_GETRUSAGE */
3200 bufusage = ShowBufferUsage();
3201 appendStringInfo(&str, "! buffer usage stats:\n%s", bufusage);
3204 /* remove trailing newline */
3205 if (str.data[str.len - 1] == '\n')
3206 str.data[--str.len] = '\0';
3209 (errmsg_internal("%s", title),
3210 errdetail("%s", str.data)));