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.388 2004/02/03 17:34:03 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"
75 const char *debug_query_string; /* for pgmonitor and
76 * log_min_error_statement */
78 /* Note: whereToSendOutput is initialized for the bootstrap/standalone case */
79 CommandDest whereToSendOutput = Debug;
81 /* note: these declarations had better match tcopprot.h */
82 sigjmp_buf Warn_restart;
84 bool Warn_restart_ready = false;
88 * Flags for expensive function optimization -- JMH 3/9/92
98 * Flag to mark SIGHUP. Whenever the main loop comes around it
99 * will reread the configuration file. (Better than doing the
100 * reading in the signal handler, ey?)
102 static volatile bool got_SIGHUP = false;
105 * Flag to keep track of whether we have started a transaction.
106 * For extended query protocol this has to be remembered across messages.
108 static bool xact_started = false;
111 * Flags to implement skip-till-Sync-after-error behavior for messages of
112 * the extended query protocol.
114 static bool doing_extended_query_message = false;
115 static bool ignore_till_sync = false;
118 * If an unnamed prepared statement exists, it's stored here.
119 * We keep it separate from the hashtable kept by commands/prepare.c
120 * in order to reduce overhead for short-lived queries.
122 static MemoryContext unnamed_stmt_context = NULL;
123 static PreparedStatement *unnamed_stmt_pstmt = NULL;
126 static bool EchoQuery = false; /* default don't echo */
129 * people who want to use EOF should #define DONTUSENEWLINE in
132 #ifndef TCOP_DONTUSENEWLINE
133 static int UseNewLine = 1; /* Use newlines query delimiters (the
137 static int UseNewLine = 0; /* Use EOF as query delimiters */
138 #endif /* TCOP_DONTUSENEWLINE */
141 /* ----------------------------------------------------------------
142 * decls for routines only used in this file
143 * ----------------------------------------------------------------
145 static int InteractiveBackend(StringInfo inBuf);
146 static int SocketBackend(StringInfo inBuf);
147 static int ReadCommand(StringInfo inBuf);
148 static void start_xact_command(void);
149 static void finish_xact_command(void);
150 static void SigHupHandler(SIGNAL_ARGS);
151 static void FloatExceptionHandler(SIGNAL_ARGS);
154 /* ----------------------------------------------------------------
155 * routines to obtain user input
156 * ----------------------------------------------------------------
160 * InteractiveBackend() is called for user interactive connections
162 * the string entered by the user is placed in its parameter inBuf,
163 * and we act like a Q message was received.
165 * EOF is returned if end-of-file input is seen; time to shut down.
170 InteractiveBackend(StringInfo inBuf)
172 int c; /* character read from getc() */
173 bool end = false; /* end-of-input flag */
174 bool backslashSeen = false; /* have we seen a \ ? */
177 * display a prompt and obtain input from the user
182 /* Reset inBuf to empty */
184 inBuf->data[0] = '\0';
192 * if we are using \n as a delimiter, then read characters
195 while ((c = getc(stdin)) != EOF)
201 /* discard backslash from inBuf */
202 inBuf->data[--inBuf->len] = '\0';
203 backslashSeen = false;
208 /* keep the newline character */
209 appendStringInfoChar(inBuf, '\n');
214 backslashSeen = true;
216 backslashSeen = false;
218 appendStringInfoChar(inBuf, (char) c);
227 * otherwise read characters until EOF.
229 while ((c = getc(stdin)) != EOF)
230 appendStringInfoChar(inBuf, (char) c);
240 * otherwise we have a user query so process it.
245 /* Add '\0' to make it look the same as message case. */
246 appendStringInfoChar(inBuf, (char) '\0');
249 * if the query echo flag was given, print the query..
252 printf("statement: %s\n", inBuf->data);
259 * SocketBackend() Is called for frontend-backend connections
261 * Returns the message type code, and loads message body data into inBuf.
263 * EOF is returned if the connection is lost.
267 SocketBackend(StringInfo inBuf)
272 * Get message type code from the frontend.
274 qtype = pq_getbyte();
276 if (qtype == EOF) /* frontend disconnected */
279 (errcode(ERRCODE_PROTOCOL_VIOLATION),
280 errmsg("unexpected EOF on client connection")));
285 * Validate message type code before trying to read body; if we have
286 * lost sync, better to say "command unknown" than to run out of
287 * memory because we used garbage as a length word.
289 * This also gives us a place to set the doing_extended_query_message
290 * flag as soon as possible.
294 case 'Q': /* simple query */
295 doing_extended_query_message = false;
296 if (PG_PROTOCOL_MAJOR(FrontendProtocol) < 3)
298 /* old style without length word; convert */
299 if (pq_getstring(inBuf))
302 (errcode(ERRCODE_PROTOCOL_VIOLATION),
303 errmsg("unexpected EOF on client connection")));
309 case 'F': /* fastpath function call */
310 /* we let fastpath.c cope with old-style input of this */
311 doing_extended_query_message = false;
314 case 'X': /* terminate */
315 doing_extended_query_message = false;
316 ignore_till_sync = false;
320 case 'C': /* close */
321 case 'D': /* describe */
322 case 'E': /* execute */
323 case 'H': /* flush */
324 case 'P': /* parse */
325 doing_extended_query_message = true;
326 /* these are only legal in protocol 3 */
327 if (PG_PROTOCOL_MAJOR(FrontendProtocol) < 3)
329 (errcode(ERRCODE_PROTOCOL_VIOLATION),
330 errmsg("invalid frontend message type %d", qtype)));
334 /* stop any active skip-till-Sync */
335 ignore_till_sync = false;
336 /* mark not-extended, so that a new error doesn't begin skip */
337 doing_extended_query_message = false;
338 /* only legal in protocol 3 */
339 if (PG_PROTOCOL_MAJOR(FrontendProtocol) < 3)
341 (errcode(ERRCODE_PROTOCOL_VIOLATION),
342 errmsg("invalid frontend message type %d", qtype)));
345 case 'd': /* copy data */
346 case 'c': /* copy done */
347 case 'f': /* copy fail */
348 doing_extended_query_message = false;
349 /* these are only legal in protocol 3 */
350 if (PG_PROTOCOL_MAJOR(FrontendProtocol) < 3)
352 (errcode(ERRCODE_PROTOCOL_VIOLATION),
353 errmsg("invalid frontend message type %d", qtype)));
359 * Otherwise we got garbage from the frontend. We treat this
360 * as fatal because we have probably lost message boundary
361 * sync, and there's no good way to recover.
364 (errcode(ERRCODE_PROTOCOL_VIOLATION),
365 errmsg("invalid frontend message type %d", qtype)));
370 * In protocol version 3, all frontend messages have a length word
371 * next after the type code; we can read the message contents
372 * independently of the type.
374 if (PG_PROTOCOL_MAJOR(FrontendProtocol) >= 3)
376 if (pq_getmessage(inBuf, 0))
377 return EOF; /* suitable message already logged */
384 * ReadCommand reads a command from either the frontend or
385 * standard input, places it in inBuf, and returns the
386 * message type code (first byte of the message).
387 * EOF is returned if end of file.
391 ReadCommand(StringInfo inBuf)
395 if (whereToSendOutput == Remote)
396 result = SocketBackend(inBuf);
398 result = InteractiveBackend(inBuf);
404 * Parse a query string and pass it through the rewriter.
406 * A list of Query nodes is returned, since the string might contain
407 * multiple queries and/or the rewriter might expand one query to several.
409 * NOTE: this routine is no longer used for processing interactive queries,
410 * but it is still needed for parsing of SQL function bodies.
413 pg_parse_and_rewrite(const char *query_string, /* string to execute */
414 Oid *paramTypes, /* parameter types */
415 int numParams) /* number of parameters */
417 List *raw_parsetree_list;
418 List *querytree_list;
422 * (1) parse the request string into a list of raw parse trees.
424 raw_parsetree_list = pg_parse_query(query_string);
427 * (2) Do parse analysis and rule rewrite.
429 querytree_list = NIL;
430 foreach(list_item, raw_parsetree_list)
432 Node *parsetree = (Node *) lfirst(list_item);
434 querytree_list = nconc(querytree_list,
435 pg_analyze_and_rewrite(parsetree,
440 return querytree_list;
444 * Do raw parsing (only).
446 * A list of parsetrees is returned, since there might be multiple
447 * commands in the given string.
449 * NOTE: for interactive queries, it is important to keep this routine
450 * separate from the analysis & rewrite stages. Analysis and rewriting
451 * cannot be done in an aborted transaction, since they require access to
452 * database tables. So, we rely on the raw parser to determine whether
453 * we've seen a COMMIT or ABORT command; when we are in abort state, other
454 * commands are not processed any further than the raw parse stage.
457 pg_parse_query(const char *query_string)
459 List *raw_parsetree_list;
463 (errmsg("statement: %s", query_string)));
465 if (log_parser_stats)
468 raw_parsetree_list = raw_parser(query_string);
470 if (log_parser_stats)
471 ShowUsage("PARSER STATISTICS");
473 return raw_parsetree_list;
477 * Given a raw parsetree (gram.y output), and optionally information about
478 * types of parameter symbols ($n), perform parse analysis and rule rewriting.
480 * A list of Query nodes is returned, since either the analyzer or the
481 * rewriter might expand one query to several.
483 * NOTE: for reasons mentioned above, this must be separate from raw parsing.
486 pg_analyze_and_rewrite(Node *parsetree, Oid *paramTypes, int numParams)
488 List *querytree_list;
491 * (1) Perform parse analysis.
493 if (log_parser_stats)
496 querytree_list = parse_analyze(parsetree, paramTypes, numParams);
498 if (log_parser_stats)
499 ShowUsage("PARSE ANALYSIS STATISTICS");
502 * (2) Rewrite the queries, as necessary
504 querytree_list = pg_rewrite_queries(querytree_list);
506 return querytree_list;
510 * Perform rewriting of a list of queries produced by parse analysis.
513 pg_rewrite_queries(List *querytree_list)
515 List *new_list = NIL;
518 if (log_parser_stats)
522 * rewritten queries are collected in new_list. Note there may be
523 * more or fewer than in the original list.
525 foreach(list_item, querytree_list)
527 Query *querytree = (Query *) lfirst(list_item);
529 if (Debug_print_parse)
530 elog_node_display(DEBUG1, "parse tree", querytree,
533 if (querytree->commandType == CMD_UTILITY)
535 /* don't rewrite utilities, just dump 'em into new_list */
536 new_list = lappend(new_list, querytree);
540 /* rewrite regular queries */
541 List *rewritten = QueryRewrite(querytree);
543 new_list = nconc(new_list, rewritten);
547 querytree_list = new_list;
549 if (log_parser_stats)
550 ShowUsage("REWRITER STATISTICS");
552 #ifdef COPY_PARSE_PLAN_TREES
555 * Optional debugging check: pass querytree output through
558 new_list = (List *) copyObject(querytree_list);
559 /* This checks both copyObject() and the equal() routines... */
560 if (!equal(new_list, querytree_list))
561 elog(WARNING, "copyObject() failed to produce an equal parse tree");
563 querytree_list = new_list;
566 if (Debug_print_rewritten)
567 elog_node_display(DEBUG1, "rewritten parse tree", querytree_list,
570 return querytree_list;
574 /* Generate a plan for a single already-rewritten query. */
576 pg_plan_query(Query *querytree)
580 /* Utility commands have no plans. */
581 if (querytree->commandType == CMD_UTILITY)
584 if (log_planner_stats)
587 /* call the optimizer */
588 plan = planner(querytree, false, 0);
590 if (log_planner_stats)
591 ShowUsage("PLANNER STATISTICS");
593 #ifdef COPY_PARSE_PLAN_TREES
594 /* Optional debugging check: pass plan output through copyObject() */
596 Plan *new_plan = (Plan *) copyObject(plan);
599 * equal() currently does not have routines to compare Plan nodes,
600 * so don't try to test equality here. Perhaps fix someday?
603 /* This checks both copyObject() and the equal() routines... */
604 if (!equal(new_plan, plan))
605 elog(WARNING, "copyObject() failed to produce an equal plan tree");
613 * Print plan if debugging.
615 if (Debug_print_plan)
616 elog_node_display(DEBUG1, "plan", plan, Debug_pretty_print);
622 * Generate plans for a list of already-rewritten queries.
624 * If needSnapshot is TRUE, we haven't yet set a snapshot for the current
625 * query. A snapshot must be set before invoking the planner, since it
626 * might try to evaluate user-defined functions. But we must not set a
627 * snapshot if the list contains only utility statements, because some
628 * utility statements depend on not having frozen the snapshot yet.
629 * (We assume that such statements cannot appear together with plannable
630 * statements in the rewriter's output.)
633 pg_plan_queries(List *querytrees, bool needSnapshot)
635 List *plan_list = NIL;
638 foreach(query_list, querytrees)
640 Query *query = (Query *) lfirst(query_list);
643 if (query->commandType == CMD_UTILITY)
645 /* Utility commands have no plans. */
653 needSnapshot = false;
655 plan = pg_plan_query(query);
658 plan_list = lappend(plan_list, plan);
668 * Execute a "simple Query" protocol message.
671 exec_simple_query(const char *query_string)
673 CommandDest dest = whereToSendOutput;
674 MemoryContext oldcontext;
675 List *parsetree_list,
677 struct timeval start_t,
679 bool save_log_duration = log_duration;
680 int save_log_min_duration_statement = log_min_duration_statement;
681 bool save_log_statement_stats = log_statement_stats;
684 * Report query to various monitoring facilities.
686 debug_query_string = query_string;
688 pgstat_report_activity(query_string);
691 * We use save_log_* so "SET log_duration = true" and "SET
692 * log_min_duration_statement = true" don't report incorrect time
693 * because gettimeofday() wasn't called. Similarly,
694 * log_statement_stats has to be captured once.
696 if (save_log_duration || save_log_min_duration_statement != -1)
697 gettimeofday(&start_t, NULL);
699 if (save_log_statement_stats)
703 * Start up a transaction command. All queries generated by the
704 * query_string will be in this same command block, *unless* we find a
705 * BEGIN/COMMIT/ABORT statement; we have to force a new xact command
706 * after one of those, else bad things will happen in xact.c. (Note
707 * that this will normally change current memory context.)
709 start_xact_command();
712 * Zap any pre-existing unnamed statement. (While not strictly
713 * necessary, it seems best to define simple-Query mode as if it used
714 * the unnamed statement and portal; this ensures we recover any
715 * storage used by prior unnamed operations.)
717 unnamed_stmt_pstmt = NULL;
718 if (unnamed_stmt_context)
720 DropDependentPortals(unnamed_stmt_context);
721 MemoryContextDelete(unnamed_stmt_context);
723 unnamed_stmt_context = NULL;
726 * Switch to appropriate context for constructing parsetrees.
728 oldcontext = MemoryContextSwitchTo(MessageContext);
730 QueryContext = CurrentMemoryContext;
733 * Do basic parsing of the query or queries (this should be safe even
734 * if we are in aborted transaction state!)
736 parsetree_list = pg_parse_query(query_string);
739 * Switch back to transaction context to enter the loop.
741 MemoryContextSwitchTo(oldcontext);
744 * Run through the raw parsetree(s) and process each one.
746 foreach(parsetree_item, parsetree_list)
748 Node *parsetree = (Node *) lfirst(parsetree_item);
749 const char *commandTag;
750 char completionTag[COMPLETION_TAG_BUFSIZE];
751 List *querytree_list,
754 DestReceiver *receiver;
758 * Get the command name for use in status display (it also becomes
759 * the default completion tag, down inside PortalRun). Set
760 * ps_status and do any special start-of-SQL-command processing
761 * needed by the destination.
763 commandTag = CreateCommandTag(parsetree);
765 set_ps_display(commandTag);
767 BeginCommand(commandTag, dest);
770 * If we are in an aborted transaction, reject all commands except
771 * COMMIT/ABORT. It is important that this test occur before we
772 * try to do parse analysis, rewrite, or planning, since all those
773 * phases try to do database accesses, which may fail in abort
774 * state. (It might be safe to allow some additional utility
775 * commands in this state, but not many...)
777 if (IsAbortedTransactionBlockState())
779 bool allowit = false;
781 if (IsA(parsetree, TransactionStmt))
783 TransactionStmt *stmt = (TransactionStmt *) parsetree;
785 if (stmt->kind == TRANS_STMT_COMMIT ||
786 stmt->kind == TRANS_STMT_ROLLBACK)
792 (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
793 errmsg("current transaction is aborted, "
794 "commands ignored until end of transaction block")));
797 /* Make sure we are in a transaction command */
798 start_xact_command();
800 /* If we got a cancel signal in parsing or prior command, quit */
801 CHECK_FOR_INTERRUPTS();
804 * OK to analyze, rewrite, and plan this query.
806 * Switch to appropriate context for constructing querytrees (again,
807 * these must outlive the execution context).
809 oldcontext = MemoryContextSwitchTo(MessageContext);
811 querytree_list = pg_analyze_and_rewrite(parsetree, NULL, 0);
813 plantree_list = pg_plan_queries(querytree_list, true);
815 /* If we got a cancel signal in analysis or planning, quit */
816 CHECK_FOR_INTERRUPTS();
819 * Create unnamed portal to run the query or queries in. If there
820 * already is one, silently drop it.
822 portal = CreatePortal("", true, true);
824 PortalDefineQuery(portal,
832 * Start the portal. No parameters here.
834 PortalStart(portal, NULL);
837 * Select the appropriate output format: text unless we are doing
838 * a FETCH from a binary cursor. (Pretty grotty to have to do
839 * this here --- but it avoids grottiness in other places. Ah,
840 * the joys of backward compatibility...)
842 format = 0; /* TEXT is default */
843 if (IsA(parsetree, FetchStmt))
845 FetchStmt *stmt = (FetchStmt *) parsetree;
849 Portal fportal = GetPortalByName(stmt->portalname);
851 if (PortalIsValid(fportal) &&
852 (fportal->cursorOptions & CURSOR_OPT_BINARY))
853 format = 1; /* BINARY */
856 PortalSetResultFormat(portal, 1, &format);
859 * Now we can create the destination receiver object.
861 receiver = CreateDestReceiver(dest, portal);
864 * Switch back to transaction context for execution.
866 MemoryContextSwitchTo(oldcontext);
869 * Run the portal to completion, and then drop it (and the
872 (void) PortalRun(portal,
878 (*receiver->rDestroy) (receiver);
880 PortalDrop(portal, false);
882 if (IsA(parsetree, TransactionStmt))
885 * If this was a transaction control statement, commit it. We
886 * will start a new xact command for the next command (if
889 finish_xact_command();
891 else if (lnext(parsetree_item) == NIL)
894 * If this is the last parsetree of the query string, close
895 * down transaction statement before reporting
896 * command-complete. This is so that any end-of-transaction
897 * errors are reported before the command-complete message is
898 * issued, to avoid confusing clients who will expect either a
899 * command-complete message or an error, not one and then the
900 * other. But for compatibility with historical Postgres
901 * behavior, we do not force a transaction boundary between
902 * queries appearing in a single query string.
904 finish_xact_command();
909 * We need a CommandCounterIncrement after every query, except
910 * those that start or end a transaction block.
912 CommandCounterIncrement();
916 * Tell client that we're done with this query. Note we emit
917 * exactly one EndCommand report for each raw parsetree, thus one
918 * for each SQL command the client sent, regardless of rewriting.
919 * (But a command aborted by error will not send an EndCommand
922 EndCommand(completionTag, dest);
923 } /* end loop over parsetrees */
926 * Close down transaction statement, if one is open.
928 finish_xact_command();
931 * If there were no parsetrees, return EmptyQueryResponse message.
939 * Combine processing here as we need to calculate the query duration
942 if (save_log_duration || save_log_min_duration_statement != -1)
946 gettimeofday(&stop_t, NULL);
947 if (stop_t.tv_usec < start_t.tv_usec)
950 stop_t.tv_usec += 1000000;
952 usecs = (long) (stop_t.tv_sec - start_t.tv_sec) * 1000000 + (long) (stop_t.tv_usec - start_t.tv_usec);
954 if (save_log_duration)
956 (errmsg("duration: %ld.%03ld ms",
957 (long) ((stop_t.tv_sec - start_t.tv_sec) * 1000 +
958 (stop_t.tv_usec - start_t.tv_usec) / 1000),
959 (long) (stop_t.tv_usec - start_t.tv_usec) % 1000)));
962 * Output a duration_statement to the log if the query has exceeded
963 * the min duration, or if we are to print all durations.
965 if (save_log_min_duration_statement == 0 ||
966 (save_log_min_duration_statement > 0 &&
967 usecs >= save_log_min_duration_statement * 1000))
969 (errmsg("duration: %ld.%03ld ms statement: %s",
970 (long) ((stop_t.tv_sec - start_t.tv_sec) * 1000 +
971 (stop_t.tv_usec - start_t.tv_usec) / 1000),
972 (long) (stop_t.tv_usec - start_t.tv_usec) % 1000,
976 if (save_log_statement_stats)
977 ShowUsage("QUERY STATISTICS");
979 debug_query_string = NULL;
985 * Execute a "Parse" protocol message.
988 exec_parse_message(const char *query_string, /* string to execute */
989 const char *stmt_name, /* name for prepared stmt */
990 Oid *paramTypes, /* parameter types */
991 int numParams) /* number of parameters */
993 MemoryContext oldcontext;
994 List *parsetree_list;
995 const char *commandTag;
996 List *querytree_list,
1000 bool save_log_statement_stats = log_statement_stats;
1003 * Report query to various monitoring facilities.
1005 debug_query_string = query_string;
1007 pgstat_report_activity(query_string);
1009 set_ps_display("PARSE");
1011 if (save_log_statement_stats)
1015 * Start up a transaction command so we can run parse analysis etc.
1016 * (Note that this will normally change current memory context.)
1017 * Nothing happens if we are already in one.
1019 start_xact_command();
1022 * Switch to appropriate context for constructing parsetrees.
1024 * We have two strategies depending on whether the prepared statement is
1025 * named or not. For a named prepared statement, we do parsing in
1026 * MessageContext and copy the finished trees into the prepared
1027 * statement's private context; then the reset of MessageContext
1028 * releases temporary space used by parsing and planning. For an
1029 * unnamed prepared statement, we assume the statement isn't going to
1030 * hang around long, so getting rid of temp space quickly is probably
1031 * not worth the costs of copying parse/plan trees. So in this case,
1032 * we set up a special context for the unnamed statement, and do all
1033 * the parsing/planning therein.
1035 is_named = (stmt_name[0] != '\0');
1038 /* Named prepared statement --- parse in MessageContext */
1039 oldcontext = MemoryContextSwitchTo(MessageContext);
1043 /* Unnamed prepared statement --- release any prior unnamed stmt */
1044 unnamed_stmt_pstmt = NULL;
1045 if (unnamed_stmt_context)
1047 DropDependentPortals(unnamed_stmt_context);
1048 MemoryContextDelete(unnamed_stmt_context);
1050 unnamed_stmt_context = NULL;
1051 /* create context for parsing/planning */
1052 unnamed_stmt_context =
1053 AllocSetContextCreate(TopMemoryContext,
1054 "unnamed prepared statement",
1055 ALLOCSET_DEFAULT_MINSIZE,
1056 ALLOCSET_DEFAULT_INITSIZE,
1057 ALLOCSET_DEFAULT_MAXSIZE);
1058 oldcontext = MemoryContextSwitchTo(unnamed_stmt_context);
1061 QueryContext = CurrentMemoryContext;
1064 * Do basic parsing of the query or queries (this should be safe even
1065 * if we are in aborted transaction state!)
1067 parsetree_list = pg_parse_query(query_string);
1070 * We only allow a single user statement in a prepared statement. This
1071 * is mainly to keep the protocol simple --- otherwise we'd need to
1072 * worry about multiple result tupdescs and things like that.
1074 if (length(parsetree_list) > 1)
1076 (errcode(ERRCODE_SYNTAX_ERROR),
1077 errmsg("cannot insert multiple commands into a prepared statement")));
1079 if (parsetree_list != NIL)
1081 Node *parsetree = (Node *) lfirst(parsetree_list);
1085 * Get the command name for possible use in status display.
1087 commandTag = CreateCommandTag(parsetree);
1090 * If we are in an aborted transaction, reject all commands except
1091 * COMMIT/ROLLBACK. It is important that this test occur before
1092 * we try to do parse analysis, rewrite, or planning, since all
1093 * those phases try to do database accesses, which may fail in
1094 * abort state. (It might be safe to allow some additional utility
1095 * commands in this state, but not many...)
1097 if (IsAbortedTransactionBlockState())
1099 bool allowit = false;
1101 if (IsA(parsetree, TransactionStmt))
1103 TransactionStmt *stmt = (TransactionStmt *) parsetree;
1105 if (stmt->kind == TRANS_STMT_COMMIT ||
1106 stmt->kind == TRANS_STMT_ROLLBACK)
1112 (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
1113 errmsg("current transaction is aborted, "
1114 "commands ignored until end of transaction block")));
1118 * OK to analyze, rewrite, and plan this query. Note that the
1119 * originally specified parameter set is not required to be
1120 * complete, so we have to use parse_analyze_varparams().
1122 if (log_parser_stats)
1125 querytree_list = parse_analyze_varparams(parsetree,
1130 * Check all parameter types got determined, and convert array
1131 * representation to a list for storage.
1134 for (i = 0; i < numParams; i++)
1136 Oid ptype = paramTypes[i];
1138 if (ptype == InvalidOid || ptype == UNKNOWNOID)
1140 (errcode(ERRCODE_INDETERMINATE_DATATYPE),
1141 errmsg("could not determine data type of parameter $%d",
1143 param_list = lappendo(param_list, ptype);
1146 if (log_parser_stats)
1147 ShowUsage("PARSE ANALYSIS STATISTICS");
1149 querytree_list = pg_rewrite_queries(querytree_list);
1151 plantree_list = pg_plan_queries(querytree_list, true);
1155 /* Empty input string. This is legal. */
1157 querytree_list = NIL;
1158 plantree_list = NIL;
1162 /* If we got a cancel signal in analysis or planning, quit */
1163 CHECK_FOR_INTERRUPTS();
1166 * Store the query as a prepared statement. See above comments.
1170 StorePreparedStatement(stmt_name,
1179 PreparedStatement *pstmt;
1181 pstmt = (PreparedStatement *) palloc0(sizeof(PreparedStatement));
1182 /* query_string needs to be copied into unnamed_stmt_context */
1183 pstmt->query_string = pstrdup(query_string);
1184 /* the rest is there already */
1185 pstmt->commandTag = commandTag;
1186 pstmt->query_list = querytree_list;
1187 pstmt->plan_list = plantree_list;
1188 pstmt->argtype_list = param_list;
1189 pstmt->context = unnamed_stmt_context;
1190 /* Now the unnamed statement is complete and valid */
1191 unnamed_stmt_pstmt = pstmt;
1194 MemoryContextSwitchTo(oldcontext);
1196 QueryContext = NULL;
1199 * We do NOT close the open transaction command here; that only
1200 * happens when the client sends Sync. Instead, do
1201 * CommandCounterIncrement just in case something happened during
1204 CommandCounterIncrement();
1207 * Send ParseComplete.
1209 if (whereToSendOutput == Remote)
1210 pq_putemptymessage('1');
1212 if (save_log_statement_stats)
1213 ShowUsage("PARSE MESSAGE STATISTICS");
1215 debug_query_string = NULL;
1221 * Process a "Bind" message to create a portal from a prepared statement
1224 exec_bind_message(StringInfo input_message)
1226 const char *portal_name;
1227 const char *stmt_name;
1229 int16 *pformats = NULL;
1232 int16 *rformats = NULL;
1234 PreparedStatement *pstmt;
1236 ParamListInfo params;
1238 pgstat_report_activity("<BIND>");
1240 set_ps_display("BIND");
1243 * Start up a transaction command so we can call functions etc. (Note
1244 * that this will normally change current memory context.) Nothing
1245 * happens if we are already in one.
1247 start_xact_command();
1249 /* Switch back to message context */
1250 MemoryContextSwitchTo(MessageContext);
1252 /* Get the fixed part of the message */
1253 portal_name = pq_getmsgstring(input_message);
1254 stmt_name = pq_getmsgstring(input_message);
1256 /* Get the parameter format codes */
1257 numPFormats = pq_getmsgint(input_message, 2);
1258 if (numPFormats > 0)
1260 pformats = (int16 *) palloc(numPFormats * sizeof(int16));
1261 for (i = 0; i < numPFormats; i++)
1262 pformats[i] = pq_getmsgint(input_message, 2);
1265 /* Get the parameter value count */
1266 numParams = pq_getmsgint(input_message, 2);
1268 if (numPFormats > 1 && numPFormats != numParams)
1270 (errcode(ERRCODE_PROTOCOL_VIOLATION),
1271 errmsg("bind message has %d parameter formats but %d parameters",
1272 numPFormats, numParams)));
1274 /* Find prepared statement */
1275 if (stmt_name[0] != '\0')
1276 pstmt = FetchPreparedStatement(stmt_name, true);
1279 /* special-case the unnamed statement */
1280 pstmt = unnamed_stmt_pstmt;
1283 (errcode(ERRCODE_UNDEFINED_PSTATEMENT),
1284 errmsg("unnamed prepared statement does not exist")));
1287 if (numParams != length(pstmt->argtype_list))
1289 (errcode(ERRCODE_PROTOCOL_VIOLATION),
1290 errmsg("bind message supplies %d parameters, but prepared statement \"%s\" requires %d",
1291 numParams, stmt_name, length(pstmt->argtype_list))));
1294 * Create the portal. Allow silent replacement of an existing portal
1295 * only if the unnamed portal is specified.
1297 if (portal_name[0] == '\0')
1298 portal = CreatePortal(portal_name, true, true);
1300 portal = CreatePortal(portal_name, false, false);
1302 PortalDefineQuery(portal,
1303 pstmt->query_string,
1310 * Fetch parameters, if any, and store in the portal's memory context.
1312 * In an aborted transaction, we can't risk calling user-defined
1313 * functions, but we can't fail to Bind either, so bind all parameters
1318 bool isaborted = IsAbortedTransactionBlockState();
1320 MemoryContext oldContext;
1322 oldContext = MemoryContextSwitchTo(PortalGetHeapMemory(portal));
1324 params = (ParamListInfo)
1325 palloc0((numParams + 1) * sizeof(ParamListInfoData));
1328 foreach(l, pstmt->argtype_list)
1330 Oid ptype = lfirsto(l);
1334 plength = pq_getmsgint(input_message, 4);
1335 isNull = (plength == -1);
1339 const char *pvalue = pq_getmsgbytes(input_message, plength);
1343 /* We don't bother to check the format in this case */
1349 StringInfoData pbuf;
1352 if (numPFormats > 1)
1353 pformat = pformats[i];
1354 else if (numPFormats > 0)
1355 pformat = pformats[0];
1357 pformat = 0; /* default = text */
1360 * Rather than copying data around, we just set up a
1361 * phony StringInfo pointing to the correct portion of
1362 * the message buffer. We assume we can scribble on
1363 * the message buffer so as to maintain the convention
1364 * that StringInfos have a trailing null. This is
1365 * grotty but is a big win when dealing with very
1366 * large parameter strings.
1368 pbuf.data = (char *) pvalue;
1369 pbuf.maxlen = plength + 1;
1373 csave = pbuf.data[plength];
1374 pbuf.data[plength] = '\0';
1382 getTypeInputInfo(ptype, &typInput, &typElem);
1385 * We have to do encoding conversion before
1386 * calling the typinput routine.
1389 pg_client_to_server((unsigned char *) pbuf.data,
1392 OidFunctionCall3(typInput,
1393 CStringGetDatum(pstring),
1394 ObjectIdGetDatum(typElem),
1396 /* Free result of encoding conversion, if any */
1397 if (pstring != pbuf.data)
1400 else if (pformat == 1)
1406 * Call the parameter type's binary input
1409 getTypeBinaryInputInfo(ptype, &typReceive, &typElem);
1412 OidFunctionCall2(typReceive,
1413 PointerGetDatum(&pbuf),
1414 ObjectIdGetDatum(typElem));
1416 /* Trouble if it didn't eat the whole buffer */
1417 if (pbuf.cursor != pbuf.len)
1419 (errcode(ERRCODE_INVALID_BINARY_REPRESENTATION),
1420 errmsg("incorrect binary data format in bind parameter %d",
1426 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1427 errmsg("unsupported format code: %d",
1431 /* Restore message buffer contents */
1432 pbuf.data[plength] = csave;
1436 params[i].kind = PARAM_NUM;
1437 params[i].id = i + 1;
1438 params[i].isnull = isNull;
1443 params[i].kind = PARAM_INVALID;
1445 MemoryContextSwitchTo(oldContext);
1450 /* Get the result format codes */
1451 numRFormats = pq_getmsgint(input_message, 2);
1452 if (numRFormats > 0)
1454 rformats = (int16 *) palloc(numRFormats * sizeof(int16));
1455 for (i = 0; i < numRFormats; i++)
1456 rformats[i] = pq_getmsgint(input_message, 2);
1459 pq_getmsgend(input_message);
1462 * Start portal execution.
1464 PortalStart(portal, params);
1467 * Apply the result format requests to the portal.
1469 PortalSetResultFormat(portal, numRFormats, rformats);
1472 * Send BindComplete.
1474 if (whereToSendOutput == Remote)
1475 pq_putemptymessage('2');
1479 * exec_execute_message
1481 * Process an "Execute" message for a portal
1484 exec_execute_message(const char *portal_name, long max_rows)
1487 DestReceiver *receiver;
1489 bool is_trans_stmt = false;
1490 bool is_trans_exit = false;
1492 char completionTag[COMPLETION_TAG_BUFSIZE];
1494 /* Adjust destination to tell printtup.c what to do */
1495 dest = whereToSendOutput;
1497 dest = RemoteExecute;
1499 portal = GetPortalByName(portal_name);
1500 if (!PortalIsValid(portal))
1502 (errcode(ERRCODE_UNDEFINED_CURSOR),
1503 errmsg("portal \"%s\" does not exist", portal_name)));
1506 * If the original query was a null string, just return
1507 * EmptyQueryResponse.
1509 if (portal->commandTag == NULL)
1511 Assert(portal->parseTrees == NIL);
1516 if (portal->sourceText)
1518 debug_query_string = portal->sourceText;
1519 pgstat_report_activity(portal->sourceText);
1523 debug_query_string = "execute message";
1524 pgstat_report_activity("<EXECUTE>");
1527 set_ps_display(portal->commandTag);
1529 BeginCommand(portal->commandTag, dest);
1531 /* Check for transaction-control commands */
1532 if (length(portal->parseTrees) == 1)
1534 Query *query = (Query *) lfirst(portal->parseTrees);
1536 if (query->commandType == CMD_UTILITY &&
1537 query->utilityStmt != NULL &&
1538 IsA(query->utilityStmt, TransactionStmt))
1540 TransactionStmt *stmt = (TransactionStmt *) query->utilityStmt;
1542 is_trans_stmt = true;
1543 if (stmt->kind == TRANS_STMT_COMMIT ||
1544 stmt->kind == TRANS_STMT_ROLLBACK)
1545 is_trans_exit = true;
1550 * Create dest receiver in MessageContext (we don't want it in
1551 * transaction context, because that may get deleted if portal
1554 receiver = CreateDestReceiver(dest, portal);
1557 * Ensure we are in a transaction command (this should normally be the
1558 * case already due to prior BIND).
1560 start_xact_command();
1563 * If we are in aborted transaction state, the only portals we can
1564 * actually run are those containing COMMIT or ROLLBACK commands.
1566 if (IsAbortedTransactionBlockState())
1570 (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
1571 errmsg("current transaction is aborted, "
1572 "commands ignored until end of transaction block")));
1575 /* Check for cancel signal before we start execution */
1576 CHECK_FOR_INTERRUPTS();
1579 * Okay to run the portal.
1582 max_rows = FETCH_ALL;
1584 completed = PortalRun(portal,
1590 (*receiver->rDestroy) (receiver);
1597 * If this was a transaction control statement, commit it. We
1598 * will start a new xact command for the next command (if
1601 finish_xact_command();
1606 * We need a CommandCounterIncrement after every query, except
1607 * those that start or end a transaction block.
1609 CommandCounterIncrement();
1612 /* Send appropriate CommandComplete to client */
1613 EndCommand(completionTag, dest);
1617 /* Portal run not complete, so send PortalSuspended */
1618 if (whereToSendOutput == Remote)
1619 pq_putemptymessage('s');
1622 debug_query_string = NULL;
1626 * exec_describe_statement_message
1628 * Process a "Describe" message for a prepared statement
1631 exec_describe_statement_message(const char *stmt_name)
1633 PreparedStatement *pstmt;
1638 /* Find prepared statement */
1639 if (stmt_name[0] != '\0')
1640 pstmt = FetchPreparedStatement(stmt_name, true);
1643 /* special-case the unnamed statement */
1644 pstmt = unnamed_stmt_pstmt;
1647 (errcode(ERRCODE_UNDEFINED_PSTATEMENT),
1648 errmsg("unnamed prepared statement does not exist")));
1651 if (whereToSendOutput != Remote)
1652 return; /* can't actually do anything... */
1655 * First describe the parameters...
1657 pq_beginmessage(&buf, 't'); /* parameter description message type */
1658 pq_sendint(&buf, length(pstmt->argtype_list), 2);
1660 foreach(l, pstmt->argtype_list)
1662 Oid ptype = lfirsto(l);
1664 pq_sendint(&buf, (int) ptype, 4);
1666 pq_endmessage(&buf);
1669 * Next send RowDescription or NoData to describe the result...
1671 tupdesc = FetchPreparedStatementResultDesc(pstmt);
1676 if (ChoosePortalStrategy(pstmt->query_list) == PORTAL_ONE_SELECT)
1677 targetlist = ((Query *) lfirst(pstmt->query_list))->targetList;
1680 SendRowDescriptionMessage(tupdesc, targetlist, NULL);
1683 pq_putemptymessage('n'); /* NoData */
1688 * exec_describe_portal_message
1690 * Process a "Describe" message for a portal
1693 exec_describe_portal_message(const char *portal_name)
1697 portal = GetPortalByName(portal_name);
1698 if (!PortalIsValid(portal))
1700 (errcode(ERRCODE_UNDEFINED_CURSOR),
1701 errmsg("portal \"%s\" does not exist", portal_name)));
1703 if (whereToSendOutput != Remote)
1704 return; /* can't actually do anything... */
1706 if (portal->tupDesc)
1710 if (portal->strategy == PORTAL_ONE_SELECT)
1711 targetlist = ((Query *) lfirst(portal->parseTrees))->targetList;
1714 SendRowDescriptionMessage(portal->tupDesc, targetlist,
1718 pq_putemptymessage('n'); /* NoData */
1723 * Convenience routines for starting/committing a single command.
1726 start_xact_command(void)
1731 (errmsg_internal("StartTransactionCommand")));
1732 StartTransactionCommand();
1734 /* Set statement timeout running, if any */
1735 if (StatementTimeout > 0)
1736 enable_sig_alarm(StatementTimeout, true);
1738 xact_started = true;
1743 finish_xact_command(void)
1747 /* Invoke IMMEDIATE constraint triggers */
1748 DeferredTriggerEndQuery();
1750 /* Cancel any active statement timeout before committing */
1751 disable_sig_alarm(true);
1753 /* Now commit the command */
1755 (errmsg_internal("CommitTransactionCommand")));
1757 CommitTransactionCommand();
1759 #ifdef MEMORY_CONTEXT_CHECKING
1760 /* Check all memory contexts that weren't freed during commit */
1761 /* (those that were, were checked before being deleted) */
1762 MemoryContextCheck(TopMemoryContext);
1765 #ifdef SHOW_MEMORY_STATS
1766 /* Print mem stats after each commit for leak tracking */
1768 MemoryContextStats(TopMemoryContext);
1771 xact_started = false;
1776 /* --------------------------------
1777 * signal handler routines used in PostgresMain()
1778 * --------------------------------
1782 * quickdie() occurs when signalled SIGQUIT by the postmaster.
1784 * Some backend has bought the farm,
1785 * so we need to stop what we're doing and exit.
1788 quickdie(SIGNAL_ARGS)
1790 PG_SETMASK(&BlockSig);
1793 * Ideally this should be ereport(FATAL), but then we'd not get
1794 * control back (perhaps could fix by doing local sigsetjmp?)
1797 (errcode(ERRCODE_CRASH_SHUTDOWN),
1798 errmsg("terminating connection because of crash of another server process"),
1799 errdetail("The postmaster has commanded this server process to roll back"
1800 " the current transaction and exit, because another"
1801 " server process exited abnormally and possibly corrupted"
1803 errhint("In a moment you should be able to reconnect to the"
1804 " database and repeat your command.")));
1807 * DO NOT proc_exit() -- we're here because shared memory may be
1808 * corrupted, so we don't want to try to clean up our transaction.
1809 * Just nail the windows shut and get out of town.
1811 * Note we do exit(1) not exit(0). This is to force the postmaster into
1812 * a system reset cycle if some idiot DBA sends a manual SIGQUIT to a
1813 * random backend. This is necessary precisely because we don't clean
1814 * up our shared memory state.
1820 * Shutdown signal from postmaster: abort transaction and exit
1821 * at soonest convenient time
1826 int save_errno = errno;
1828 /* Don't joggle the elbow of proc_exit */
1829 if (!proc_exit_inprogress)
1831 InterruptPending = true;
1832 ProcDiePending = true;
1835 * If it's safe to interrupt, and we're waiting for input or a
1836 * lock, service the interrupt immediately
1838 if (ImmediateInterruptOK && InterruptHoldoffCount == 0 &&
1839 CritSectionCount == 0)
1841 /* bump holdoff count to make ProcessInterrupts() a no-op */
1842 /* until we are done getting ready for it */
1843 InterruptHoldoffCount++;
1844 DisableNotifyInterrupt();
1845 /* Make sure CheckDeadLock won't run while shutting down... */
1847 InterruptHoldoffCount--;
1848 ProcessInterrupts();
1856 * Timeout or shutdown signal from postmaster during client authentication.
1859 * XXX: possible future improvement: try to send a message indicating
1860 * why we are disconnecting. Problem is to be sure we don't block while
1861 * doing so, nor mess up the authentication message exchange.
1864 authdie(SIGNAL_ARGS)
1870 * Query-cancel signal from postmaster: abort current transaction
1871 * at soonest convenient time
1874 StatementCancelHandler(SIGNAL_ARGS)
1876 int save_errno = errno;
1879 * Don't joggle the elbow of proc_exit, nor an already-in-progress
1882 if (!proc_exit_inprogress && !InError)
1884 InterruptPending = true;
1885 QueryCancelPending = true;
1888 * If it's safe to interrupt, and we're waiting for a lock,
1889 * service the interrupt immediately. No point in interrupting if
1890 * we're waiting for input, however.
1892 if (ImmediateInterruptOK && InterruptHoldoffCount == 0 &&
1893 CritSectionCount == 0)
1895 /* bump holdoff count to make ProcessInterrupts() a no-op */
1896 /* until we are done getting ready for it */
1897 InterruptHoldoffCount++;
1898 if (LockWaitCancel())
1900 DisableNotifyInterrupt();
1901 InterruptHoldoffCount--;
1902 ProcessInterrupts();
1905 InterruptHoldoffCount--;
1912 /* signal handler for floating point exception */
1914 FloatExceptionHandler(SIGNAL_ARGS)
1917 (errcode(ERRCODE_FLOATING_POINT_EXCEPTION),
1918 errmsg("floating-point exception"),
1919 errdetail("An invalid floating-point operation was signaled. "
1920 "This probably means an out-of-range result or an "
1921 "invalid operation, such as division by zero.")));
1924 /* SIGHUP: set flag to re-read config file at next convenient time */
1926 SigHupHandler(SIGNAL_ARGS)
1933 * ProcessInterrupts: out-of-line portion of CHECK_FOR_INTERRUPTS() macro
1935 * If an interrupt condition is pending, and it's safe to service it,
1936 * then clear the flag and accept the interrupt. Called only when
1937 * InterruptPending is true.
1940 ProcessInterrupts(void)
1942 /* OK to accept interrupt now? */
1943 if (InterruptHoldoffCount != 0 || CritSectionCount != 0)
1945 InterruptPending = false;
1948 ProcDiePending = false;
1949 QueryCancelPending = false; /* ProcDie trumps QueryCancel */
1950 ImmediateInterruptOK = false; /* not idle anymore */
1951 DisableNotifyInterrupt();
1953 (errcode(ERRCODE_ADMIN_SHUTDOWN),
1954 errmsg("terminating connection due to administrator command")));
1956 if (QueryCancelPending)
1958 QueryCancelPending = false;
1959 ImmediateInterruptOK = false; /* not idle anymore */
1960 DisableNotifyInterrupt();
1962 (errcode(ERRCODE_QUERY_CANCELED),
1963 errmsg("canceling query due to user request")));
1965 /* If we get here, do nothing (probably, QueryCancelPending was reset) */
1970 usage(char *progname)
1972 printf(gettext("%s is the PostgreSQL stand-alone backend. It is not\nintended to be used by normal users.\n\n"), progname);
1974 printf(gettext("Usage:\n %s [OPTION]... [DBNAME]\n\n"), progname);
1975 printf(gettext("Options:\n"));
1976 #ifdef USE_ASSERT_CHECKING
1977 printf(gettext(" -A 1|0 enable/disable run-time assert checking\n"));
1979 printf(gettext(" -B NBUFFERS number of shared buffers\n"));
1980 printf(gettext(" -c NAME=VALUE set run-time parameter\n"));
1981 printf(gettext(" -d 0-5 debugging level (0 is off)\n"));
1982 printf(gettext(" -D DATADIR database directory\n"));
1983 printf(gettext(" -e use European date input format (DMY)\n"));
1984 printf(gettext(" -E echo query before execution\n"));
1985 printf(gettext(" -F turn fsync off\n"));
1986 printf(gettext(" -N do not use newline as interactive query delimiter\n"));
1987 printf(gettext(" -o FILENAME send stdout and stderr to given file\n"));
1988 printf(gettext(" -P disable system indexes\n"));
1989 printf(gettext(" -s show statistics after each query\n"));
1990 printf(gettext(" -S WORK-MEM set amount of memory for sorts (in kbytes)\n"));
1991 printf(gettext(" --describe-config describe configuration parameters, then exit\n"));
1992 printf(gettext(" --help show this help, then exit\n"));
1993 printf(gettext(" --version output version information, then exit\n"));
1994 printf(gettext("\nDeveloper options:\n"));
1995 printf(gettext(" -f s|i|n|m|h forbid use of some plan types\n"));
1996 printf(gettext(" -i do not execute queries\n"));
1997 printf(gettext(" -O allow system table structure changes\n"));
1998 printf(gettext(" -t pa|pl|ex show timings after each query\n"));
1999 printf(gettext(" -W NUM wait NUM seconds to allow attach from a debugger\n"));
2000 printf(gettext("\nReport bugs to <pgsql-bugs@postgresql.org>.\n"));
2005 /* ----------------------------------------------------------------
2007 * postgres main loop -- all backends, interactive or otherwise start here
2009 * argc/argv are the command line arguments to be used. (When being forked
2010 * by the postmaster, these are not the original argv array of the process.)
2011 * username is the (possibly authenticated) PostgreSQL user name to be used
2013 * ----------------------------------------------------------------
2016 PostgresMain(int argc, char *argv[], const char *username)
2019 const char *dbname = NULL;
2020 char *potential_DataDir = NULL;
2026 GucSource gucsource;
2029 StringInfoData input_message;
2030 volatile bool send_rfq = true;
2033 * Catch standard options before doing much else. This even works on
2034 * systems without getopt_long.
2036 if (!IsUnderPostmaster && argc > 1)
2038 if (strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-?") == 0)
2043 if (strcmp(argv[1], "--version") == 0 || strcmp(argv[1], "-V") == 0)
2045 puts("postgres (PostgreSQL) " PG_VERSION);
2051 * initialize globals (already done if under postmaster, but not if
2052 * standalone; cheap enough to do over)
2054 MyProcPid = getpid();
2057 * Fire up essential subsystems: error and memory management
2059 * If we are running under the postmaster, this is done already.
2061 if (!IsUnderPostmaster)
2062 MemoryContextInit();
2064 set_ps_display("startup");
2066 SetProcessingMode(InitProcessing);
2069 * Set default values for command-line options.
2073 if (!IsUnderPostmaster)
2075 InitializeGUCOptions();
2076 potential_DataDir = getenv("PGDATA");
2080 * parse command line arguments
2082 * There are now two styles of command line layout for the backend:
2084 * For interactive use (not started from postmaster) the format is
2085 * postgres [switches] [databasename]
2086 * If the databasename is omitted it is taken to be the user name.
2088 * When started from the postmaster, the format is
2089 * postgres [secure switches] -p databasename [insecure switches]
2090 * Switches appearing after -p came from the client (via "options"
2091 * field of connection request). For security reasons we restrict
2092 * what these switches can do.
2096 /* all options are allowed until '-p' */
2098 ctx = debug_context = PGC_POSTMASTER;
2099 gucsource = PGC_S_ARGV; /* initial switches came from command line */
2101 while ((flag = getopt(argc, argv, "A:B:c:D:d:Eef:FiNOPo:p:S:st:v:W:x:-:")) != -1)
2105 #ifdef USE_ASSERT_CHECKING
2106 SetConfigOption("debug_assertions", optarg, ctx, gucsource);
2109 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2110 errmsg("assert checking is not compiled in")));
2117 * specify the size of buffer pool
2119 SetConfigOption("shared_buffers", optarg, ctx, gucsource);
2122 case 'D': /* PGDATA directory */
2124 potential_DataDir = optarg;
2127 case 'd': /* debug level */
2130 * Client option can't decrease debug level. We have
2131 * to do the test here because we group priv and
2132 * client set GUC calls below, after we know the final
2135 if (ctx != PGC_BACKEND || atoi(optarg) > debug_flag)
2137 debug_flag = atoi(optarg);
2138 debug_context = ctx; /* save context for use
2140 /* Set server debugging level. */
2141 if (debug_flag != 0)
2143 char *debugstr = palloc(strlen("debug") + strlen(optarg) + 1);
2145 sprintf(debugstr, "debug%s", optarg);
2146 SetConfigOption("log_min_messages", debugstr, ctx, gucsource);
2153 * -d0 allows user to prevent postmaster debug
2154 * from propagating to backend. It would be
2155 * nice to set it to the postgresql.conf value
2158 SetConfigOption("log_min_messages", "notice",
2167 * E - echo the query the user entered
2175 * Use European date input format (DMY)
2177 SetConfigOption("datestyle", "euro", ctx, gucsource);
2185 SetConfigOption("fsync", "false", ctx, gucsource);
2191 * f - forbid generation of certain plans
2196 case 's': /* seqscan */
2197 tmp = "enable_seqscan";
2199 case 'i': /* indexscan */
2200 tmp = "enable_indexscan";
2202 case 't': /* tidscan */
2203 tmp = "enable_tidscan";
2205 case 'n': /* nestloop */
2206 tmp = "enable_nestloop";
2208 case 'm': /* mergejoin */
2209 tmp = "enable_mergejoin";
2211 case 'h': /* hashjoin */
2212 tmp = "enable_hashjoin";
2218 SetConfigOption(tmp, "false", ctx, gucsource);
2224 * N - Don't use newline as a query delimiter
2232 * allow system table structure modifications
2234 if (secure) /* XXX safe to allow from client??? */
2235 allowSystemTableMods = true;
2241 * ignore system indexes
2243 * As of PG 7.4 this is safe to allow from the client,
2244 * since it only disables reading the system indexes,
2245 * not writing them. Worst case consequence is slowness.
2247 IgnoreSystemIndexes(true);
2253 * o - send output (stdout and stderr) to the given file
2256 StrNCpy(OutputFileName, optarg, MAXPGPATH);
2261 * p - special flag passed if backend was forked by a
2266 dbname = strdup(optarg);
2268 secure = false; /* subsequent switches are NOT
2271 gucsource = PGC_S_CLIENT;
2278 * S - amount of sort memory to use in 1k bytes
2280 SetConfigOption("work_mem", optarg, ctx, gucsource);
2286 * s - report usage statistics (timings) after each query
2288 SetConfigOption("log_statement_stats", "true", ctx, gucsource);
2293 * tell postgres to report usage statistics (timings) for
2296 * -tpa[rser] = print stats for parser time of each query
2297 * -tpl[anner] = print stats for planner time of each query
2298 * -te[xecutor] = print stats for executor time of each query
2299 * caution: -s can not be used together with -t.
2306 if (optarg[1] == 'a')
2307 tmp = "log_parser_stats";
2308 else if (optarg[1] == 'l')
2309 tmp = "log_planner_stats";
2314 tmp = "log_executor_stats";
2321 SetConfigOption(tmp, "true", ctx, gucsource);
2326 FrontendProtocol = (ProtocolVersion) atoi(optarg);
2332 * wait N seconds to allow attach from a debugger
2334 sleep(atoi(optarg));
2338 #ifdef NOT_USED /* planner/xfunc.h */
2341 * control joey hellerstein's expensive function
2346 elog(WARNING, "only one -x flag is allowed");
2350 if (strcmp(optarg, "off") == 0)
2351 XfuncMode = XFUNC_OFF;
2352 else if (strcmp(optarg, "nor") == 0)
2353 XfuncMode = XFUNC_NOR;
2354 else if (strcmp(optarg, "nopull") == 0)
2355 XfuncMode = XFUNC_NOPULL;
2356 else if (strcmp(optarg, "nopm") == 0)
2357 XfuncMode = XFUNC_NOPM;
2358 else if (strcmp(optarg, "pullall") == 0)
2359 XfuncMode = XFUNC_PULLALL;
2360 else if (strcmp(optarg, "wait") == 0)
2361 XfuncMode = XFUNC_WAIT;
2364 elog(WARNING, "use -x {off,nor,nopull,nopm,pullall,wait}");
2376 ParseLongOption(optarg, &name, &value);
2381 (errcode(ERRCODE_SYNTAX_ERROR),
2382 errmsg("--%s requires a value",
2386 (errcode(ERRCODE_SYNTAX_ERROR),
2387 errmsg("-c %s requires a value",
2391 SetConfigOption(name, value, ctx, gucsource);
2405 * -d is not the same as setting log_min_messages because it enables
2406 * other output options.
2408 if (debug_flag >= 1)
2409 SetConfigOption("log_connections", "true", debug_context, gucsource);
2410 if (debug_flag >= 2)
2411 SetConfigOption("log_statement", "true", debug_context, gucsource);
2412 if (debug_flag >= 3)
2413 SetConfigOption("debug_print_parse", "true", debug_context, gucsource);
2414 if (debug_flag >= 4)
2415 SetConfigOption("debug_print_plan", "true", debug_context, gucsource);
2416 if (debug_flag >= 5)
2417 SetConfigOption("debug_print_rewritten", "true", debug_context, gucsource);
2420 * Process any additional GUC variable settings passed in startup
2423 if (MyProcPort != NULL)
2425 List *gucopts = MyProcPort->guc_options;
2432 name = lfirst(gucopts);
2433 gucopts = lnext(gucopts);
2434 value = lfirst(gucopts);
2435 gucopts = lnext(gucopts);
2436 SetConfigOption(name, value, PGC_BACKEND, PGC_S_CLIENT);
2441 * Post-processing for command line options.
2443 if (log_statement_stats &&
2444 (log_parser_stats || log_planner_stats || log_executor_stats))
2447 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
2448 errmsg("statement-level statistics are disabled because parser, planner, or executor statistics are on")));
2449 SetConfigOption("log_statement_stats", "false", ctx, gucsource);
2452 if (!IsUnderPostmaster || ExecBackend)
2454 if (!potential_DataDir)
2457 gettext("%s does not know where to find the database system data.\n"
2458 "You must specify the directory that contains the database system\n"
2459 "either by specifying the -D invocation option or by setting the\n"
2460 "PGDATA environment variable.\n"),
2464 SetDataDir(potential_DataDir);
2468 /* Acquire configuration parameters */
2469 if (IsUnderPostmaster)
2472 read_nondefault_variables();
2475 ProcessConfigFile(PGC_POSTMASTER);
2478 * Set up signal handlers and masks.
2480 * Note that postmaster blocked all signals before forking child process,
2481 * so there is no race condition whereby we might receive a signal
2482 * before we have set up the handler.
2484 * Also note: it's best not to use any signals that are SIG_IGNored in
2485 * the postmaster. If such a signal arrives before we are able to
2486 * change the handler to non-SIG_IGN, it'll get dropped. Instead,
2487 * make a dummy handler in the postmaster to reserve the signal. (Of
2488 * course, this isn't an issue for signals that are locally generated,
2489 * such as SIGALRM and SIGPIPE.)
2491 pqsignal(SIGHUP, SigHupHandler); /* set flag to read config file */
2492 pqsignal(SIGINT, StatementCancelHandler); /* cancel current query */
2493 pqsignal(SIGTERM, die); /* cancel current query and exit */
2494 pqsignal(SIGQUIT, quickdie); /* hard crash time */
2495 pqsignal(SIGALRM, handle_sig_alarm); /* timeout conditions */
2498 * Ignore failure to write to frontend. Note: if frontend closes
2499 * connection, we will notice it and exit cleanly when control next
2500 * returns to outer loop. This seems safer than forcing exit in the
2501 * midst of output during who-knows-what operation...
2503 pqsignal(SIGPIPE, SIG_IGN);
2504 pqsignal(SIGUSR1, SIG_IGN); /* this signal available for use */
2506 pqsignal(SIGUSR2, Async_NotifyHandler); /* flush also sinval cache */
2507 pqsignal(SIGFPE, FloatExceptionHandler);
2510 * Reset some signals that are accepted by postmaster but not by
2513 pqsignal(SIGCHLD, SIG_DFL); /* system() requires this on some
2518 /* We allow SIGQUIT (quickdie) at all times */
2519 #ifdef HAVE_SIGPROCMASK
2520 sigdelset(&BlockSig, SIGQUIT);
2522 BlockSig &= ~(sigmask(SIGQUIT));
2525 PG_SETMASK(&BlockSig); /* block everything except SIGQUIT */
2528 if (IsUnderPostmaster)
2530 /* noninteractive case: nothing should be left after switches */
2531 if (errs || argc != optind || dbname == NULL)
2534 (errcode(ERRCODE_SYNTAX_ERROR),
2535 errmsg("invalid command-line arguments for server process"),
2536 errhint("Try \"%s --help\" for more information.", argv[0])));
2545 /* interactive case: database name can be last arg on command line */
2546 if (errs || argc - optind > 1)
2549 (errcode(ERRCODE_SYNTAX_ERROR),
2550 errmsg("%s: invalid command-line arguments",
2552 errhint("Try \"%s --help\" for more information.", argv[0])));
2554 else if (argc - optind == 1)
2555 dbname = argv[optind];
2556 else if ((dbname = username) == NULL)
2559 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
2560 errmsg("%s: no database nor user name specified",
2565 * On some systems our dynloader code needs the executable's
2566 * pathname. (If under postmaster, this was done already.)
2568 if (FindExec(pg_pathname, argv[0], "postgres") < 0)
2570 (errmsg("%s: could not locate postgres executable",
2574 * Validate we have been given a reasonable-looking DataDir (if
2575 * under postmaster, assume postmaster did this already).
2577 ValidatePgVersion(DataDir);
2580 * Create lockfile for data directory.
2582 CreateDataDirLockFile(DataDir, false);
2588 * Start up xlog for standalone backend, and register to have it
2589 * closed down at exit.
2592 on_shmem_exit(ShutdownXLOG, 0);
2595 * Read any existing FSM cache file, and register to write one out
2599 on_shmem_exit(DumpFreeSpaceMap, 0);
2603 * General initialization.
2605 * NOTE: if you are tempted to add code in this vicinity, consider
2606 * putting it inside InitPostgres() instead. In particular, anything
2607 * that involves database access should be there, not here.
2610 (errmsg_internal("InitPostgres")));
2611 InitPostgres(dbname, username);
2613 SetProcessingMode(NormalProcessing);
2616 * Send this backend's cancellation info to the frontend.
2618 if (whereToSendOutput == Remote &&
2619 PG_PROTOCOL_MAJOR(FrontendProtocol) >= 2)
2623 pq_beginmessage(&buf, 'K');
2624 pq_sendint(&buf, (int32) MyProcPid, sizeof(int32));
2625 pq_sendint(&buf, (int32) MyCancelKey, sizeof(int32));
2626 pq_endmessage(&buf);
2627 /* Need not flush since ReadyForQuery will do it. */
2630 /* Welcome banner for standalone case */
2631 if (whereToSendOutput == Debug)
2632 printf("\nPostgreSQL stand-alone backend %s\n", PG_VERSION);
2635 * Create the memory context we will use in the main loop.
2637 * MessageContext is reset once per iteration of the main loop, ie, upon
2638 * completion of processing of each command message from the client.
2640 MessageContext = AllocSetContextCreate(TopMemoryContext,
2642 ALLOCSET_DEFAULT_MINSIZE,
2643 ALLOCSET_DEFAULT_INITSIZE,
2644 ALLOCSET_DEFAULT_MAXSIZE);
2647 * Tell the statistics collector that we're alive and
2648 * to which database we belong.
2654 * POSTGRES main processing loop begins here
2656 * If an exception is encountered, processing resumes here so we abort
2657 * the current transaction and start a new one.
2660 if (sigsetjmp(Warn_restart, 1) != 0)
2663 * NOTE: if you are tempted to add more code in this if-block,
2664 * consider the probability that it should be in
2665 * AbortTransaction() instead.
2667 * Make sure we're not interrupted while cleaning up. Also forget
2668 * any pending QueryCancel request, since we're aborting anyway.
2669 * Force InterruptHoldoffCount to a known state in case we
2670 * ereport'd from inside a holdoff section.
2672 ImmediateInterruptOK = false;
2673 QueryCancelPending = false;
2674 InterruptHoldoffCount = 1;
2675 CritSectionCount = 0; /* should be unnecessary, but... */
2676 disable_sig_alarm(true);
2677 QueryCancelPending = false; /* again in case timeout occurred */
2678 DisableNotifyInterrupt();
2679 debug_query_string = NULL;
2682 * Make sure we are in a valid memory context during recovery.
2684 * We use ErrorContext in hopes that it will have some free space
2685 * even if we're otherwise up against it...
2687 MemoryContextSwitchTo(ErrorContext);
2689 /* Do the recovery */
2691 (errmsg_internal("AbortCurrentTransaction")));
2692 AbortCurrentTransaction();
2695 * Now return to normal top-level context and clear ErrorContext
2698 MemoryContextSwitchTo(TopMemoryContext);
2699 MemoryContextResetAndDeleteChildren(ErrorContext);
2700 PortalContext = NULL;
2701 QueryContext = NULL;
2704 * Clear flag to indicate that we got out of error recovery mode
2705 * successfully. (Flag was set in elog.c before longjmp().)
2708 xact_started = false;
2711 * If we were handling an extended-query-protocol message,
2712 * initiate skip till next Sync. This also causes us not to issue
2713 * ReadyForQuery (until we get Sync).
2715 if (doing_extended_query_message)
2716 ignore_till_sync = true;
2719 * Exit interrupt holdoff section we implicitly established above.
2721 RESUME_INTERRUPTS();
2724 Warn_restart_ready = true; /* we can now handle ereport(ERROR) */
2726 PG_SETMASK(&UnBlockSig);
2728 if (!ignore_till_sync)
2729 send_rfq = true; /* initially, or after error */
2732 * Non-error queries loop here.
2738 * At top of loop, reset extended-query-message flag, so that any
2739 * errors encountered in "idle" state don't provoke skip.
2741 doing_extended_query_message = false;
2744 * Release storage left over from prior query cycle, and create a
2745 * new query input buffer in the cleared MessageContext.
2747 MemoryContextSwitchTo(MessageContext);
2748 MemoryContextResetAndDeleteChildren(MessageContext);
2750 initStringInfo(&input_message);
2753 * (1) If we've reached idle state, tell the frontend we're ready
2756 * Note: this includes fflush()'ing the last of the prior output.
2758 * This is also a good time to send collected statistics to the
2759 * collector, and to update the PS stats display. We avoid doing
2760 * those every time through the message loop because it'd slow down
2761 * processing of batched messages.
2765 pgstat_report_tabstat();
2767 if (IsTransactionOrTransactionBlock())
2769 set_ps_display("idle in transaction");
2770 pgstat_report_activity("<IDLE> in transaction");
2774 set_ps_display("idle");
2775 pgstat_report_activity("<IDLE>");
2778 ReadyForQuery(whereToSendOutput);
2783 * (2) deal with pending asynchronous NOTIFY from other backends,
2784 * and enable async.c's signal handler to execute NOTIFY directly.
2785 * Then set up other stuff needed before blocking for input.
2787 QueryCancelPending = false; /* forget any earlier CANCEL
2790 EnableNotifyInterrupt();
2792 /* Allow "die" interrupt to be processed while waiting */
2793 ImmediateInterruptOK = true;
2794 /* and don't forget to detect one that already arrived */
2795 QueryCancelPending = false;
2796 CHECK_FOR_INTERRUPTS();
2799 * (3) read a command (loop blocks here)
2801 firstchar = ReadCommand(&input_message);
2804 * (4) disable async signal conditions again.
2806 ImmediateInterruptOK = false;
2807 QueryCancelPending = false; /* forget any CANCEL signal */
2809 DisableNotifyInterrupt();
2812 * (5) check for any other interesting events that happened while
2819 read_nondefault_variables();
2821 ProcessConfigFile(PGC_SIGHUP);
2826 * (6) process the command. But ignore it if we're skipping till
2829 if (ignore_till_sync && firstchar != EOF)
2834 case 'Q': /* simple query */
2836 const char *query_string;
2838 query_string = pq_getmsgstring(&input_message);
2839 pq_getmsgend(&input_message);
2841 exec_simple_query(query_string);
2847 case 'P': /* parse */
2849 const char *stmt_name;
2850 const char *query_string;
2852 Oid *paramTypes = NULL;
2854 stmt_name = pq_getmsgstring(&input_message);
2855 query_string = pq_getmsgstring(&input_message);
2856 numParams = pq_getmsgint(&input_message, 2);
2861 paramTypes = (Oid *) palloc(numParams * sizeof(Oid));
2862 for (i = 0; i < numParams; i++)
2863 paramTypes[i] = pq_getmsgint(&input_message, 4);
2865 pq_getmsgend(&input_message);
2867 exec_parse_message(query_string, stmt_name,
2868 paramTypes, numParams);
2872 case 'B': /* bind */
2875 * this message is complex enough that it seems best to
2876 * put the field extraction out-of-line
2878 exec_bind_message(&input_message);
2881 case 'E': /* execute */
2883 const char *portal_name;
2886 portal_name = pq_getmsgstring(&input_message);
2887 max_rows = pq_getmsgint(&input_message, 4);
2888 pq_getmsgend(&input_message);
2890 exec_execute_message(portal_name, max_rows);
2894 case 'F': /* fastpath function call */
2895 /* Tell the collector what we're doing */
2896 pgstat_report_activity("<FASTPATH> function call");
2898 /* start an xact for this function invocation */
2899 start_xact_command();
2901 /* switch back to message context */
2902 MemoryContextSwitchTo(MessageContext);
2904 if (HandleFunctionRequest(&input_message) == EOF)
2906 /* lost frontend connection during F message input */
2909 * Reset whereToSendOutput to prevent ereport from
2910 * attempting to send any more messages to client.
2912 if (whereToSendOutput == Remote)
2913 whereToSendOutput = None;
2918 /* commit the function-invocation transaction */
2919 finish_xact_command();
2924 case 'C': /* close */
2927 const char *close_target;
2929 close_type = pq_getmsgbyte(&input_message);
2930 close_target = pq_getmsgstring(&input_message);
2931 pq_getmsgend(&input_message);
2936 if (close_target[0] != '\0')
2937 DropPreparedStatement(close_target, false);
2940 /* special-case the unnamed statement */
2941 unnamed_stmt_pstmt = NULL;
2942 if (unnamed_stmt_context)
2944 DropDependentPortals(unnamed_stmt_context);
2945 MemoryContextDelete(unnamed_stmt_context);
2947 unnamed_stmt_context = NULL;
2954 portal = GetPortalByName(close_target);
2955 if (PortalIsValid(portal))
2956 PortalDrop(portal, false);
2961 (errcode(ERRCODE_PROTOCOL_VIOLATION),
2962 errmsg("invalid CLOSE message subtype %d",
2967 if (whereToSendOutput == Remote)
2968 pq_putemptymessage('3'); /* CloseComplete */
2972 case 'D': /* describe */
2975 const char *describe_target;
2977 describe_type = pq_getmsgbyte(&input_message);
2978 describe_target = pq_getmsgstring(&input_message);
2979 pq_getmsgend(&input_message);
2981 switch (describe_type)
2984 exec_describe_statement_message(describe_target);
2987 exec_describe_portal_message(describe_target);
2991 (errcode(ERRCODE_PROTOCOL_VIOLATION),
2992 errmsg("invalid DESCRIBE message subtype %d",
2999 case 'H': /* flush */
3000 pq_getmsgend(&input_message);
3001 if (whereToSendOutput == Remote)
3005 case 'S': /* sync */
3006 pq_getmsgend(&input_message);
3007 finish_xact_command();
3012 * 'X' means that the frontend is closing down the socket.
3013 * EOF means unexpected loss of frontend connection.
3014 * Either way, perform normal shutdown.
3020 * Reset whereToSendOutput to prevent ereport from
3021 * attempting to send any more messages to client.
3023 if (whereToSendOutput == Remote)
3024 whereToSendOutput = None;
3027 * NOTE: if you are tempted to add more code here, DON'T!
3028 * Whatever you had in mind to do should be set up as an
3029 * on_proc_exit or on_shmem_exit callback, instead.
3030 * Otherwise it will fail to be called during other
3031 * backend-shutdown scenarios.
3035 case 'd': /* copy data */
3036 case 'c': /* copy done */
3037 case 'f': /* copy fail */
3040 * Accept but ignore these messages, per protocol spec; we
3041 * probably got here because a COPY failed, and the
3042 * frontend is still sending data.
3048 (errcode(ERRCODE_PROTOCOL_VIOLATION),
3049 errmsg("invalid frontend message type %d",
3052 } /* end of input-reading loop */
3054 /* can't get here because the above loop never exits */
3057 return 1; /* keep compiler quiet */
3060 #ifndef HAVE_GETRUSAGE
3061 #include "rusagestub.h"
3063 #include <sys/resource.h>
3064 #endif /* HAVE_GETRUSAGE */
3066 static struct rusage Save_r;
3067 static struct timeval Save_t;
3072 getrusage(RUSAGE_SELF, &Save_r);
3073 gettimeofday(&Save_t, NULL);
3075 /* ResetTupleCount(); */
3079 ShowUsage(const char *title)
3082 struct timeval user,
3084 struct timeval elapse_t;
3088 getrusage(RUSAGE_SELF, &r);
3089 gettimeofday(&elapse_t, NULL);
3090 memcpy((char *) &user, (char *) &r.ru_utime, sizeof(user));
3091 memcpy((char *) &sys, (char *) &r.ru_stime, sizeof(sys));
3092 if (elapse_t.tv_usec < Save_t.tv_usec)
3095 elapse_t.tv_usec += 1000000;
3097 if (r.ru_utime.tv_usec < Save_r.ru_utime.tv_usec)
3099 r.ru_utime.tv_sec--;
3100 r.ru_utime.tv_usec += 1000000;
3102 if (r.ru_stime.tv_usec < Save_r.ru_stime.tv_usec)
3104 r.ru_stime.tv_sec--;
3105 r.ru_stime.tv_usec += 1000000;
3109 * the only stats we don't show here are for memory usage -- i can't
3110 * figure out how to interpret the relevant fields in the rusage
3111 * struct, and they change names across o/s platforms, anyway. if you
3112 * can figure out what the entries mean, you can somehow extract
3113 * resident set size, shared text size, and unshared data and stack
3116 initStringInfo(&str);
3118 appendStringInfo(&str, "! system usage stats:\n");
3119 appendStringInfo(&str,
3120 "!\t%ld.%06ld elapsed %ld.%06ld user %ld.%06ld system sec\n",
3121 (long) (elapse_t.tv_sec - Save_t.tv_sec),
3122 (long) (elapse_t.tv_usec - Save_t.tv_usec),
3123 (long) (r.ru_utime.tv_sec - Save_r.ru_utime.tv_sec),
3124 (long) (r.ru_utime.tv_usec - Save_r.ru_utime.tv_usec),
3125 (long) (r.ru_stime.tv_sec - Save_r.ru_stime.tv_sec),
3126 (long) (r.ru_stime.tv_usec - Save_r.ru_stime.tv_usec));
3127 appendStringInfo(&str,
3128 "!\t[%ld.%06ld user %ld.%06ld sys total]\n",
3130 (long) user.tv_usec,
3132 (long) sys.tv_usec);
3133 /* BeOS has rusage but only has some fields, and not these... */
3134 #if defined(HAVE_GETRUSAGE)
3135 appendStringInfo(&str,
3136 "!\t%ld/%ld [%ld/%ld] filesystem blocks in/out\n",
3137 r.ru_inblock - Save_r.ru_inblock,
3138 /* they only drink coffee at dec */
3139 r.ru_oublock - Save_r.ru_oublock,
3140 r.ru_inblock, r.ru_oublock);
3141 appendStringInfo(&str,
3142 "!\t%ld/%ld [%ld/%ld] page faults/reclaims, %ld [%ld] swaps\n",
3143 r.ru_majflt - Save_r.ru_majflt,
3144 r.ru_minflt - Save_r.ru_minflt,
3145 r.ru_majflt, r.ru_minflt,
3146 r.ru_nswap - Save_r.ru_nswap,
3148 appendStringInfo(&str,
3149 "!\t%ld [%ld] signals rcvd, %ld/%ld [%ld/%ld] messages rcvd/sent\n",
3150 r.ru_nsignals - Save_r.ru_nsignals,
3152 r.ru_msgrcv - Save_r.ru_msgrcv,
3153 r.ru_msgsnd - Save_r.ru_msgsnd,
3154 r.ru_msgrcv, r.ru_msgsnd);
3155 appendStringInfo(&str,
3156 "!\t%ld/%ld [%ld/%ld] voluntary/involuntary context switches\n",
3157 r.ru_nvcsw - Save_r.ru_nvcsw,
3158 r.ru_nivcsw - Save_r.ru_nivcsw,
3159 r.ru_nvcsw, r.ru_nivcsw);
3160 #endif /* HAVE_GETRUSAGE */
3162 bufusage = ShowBufferUsage();
3163 appendStringInfo(&str, "! buffer usage stats:\n%s", bufusage);
3166 /* remove trailing newline */
3167 if (str.data[str.len - 1] == '\n')
3168 str.data[--str.len] = '\0';
3171 (errmsg_internal("%s", title),
3172 errdetail("%s", str.data)));