1 /*-------------------------------------------------------------------------
4 * POSTGRES C Backend Interface
6 * Portions Copyright (c) 1996-2002, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
11 * $Header: /cvsroot/pgsql/src/backend/tcop/postgres.c,v 1.325 2003/04/27 20:09:44 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/xlog.h"
37 #include "commands/async.h"
38 #include "commands/trigger.h"
39 #include "libpq/libpq.h"
40 #include "libpq/pqformat.h"
41 #include "libpq/pqsignal.h"
42 #include "miscadmin.h"
43 #include "nodes/print.h"
44 #include "optimizer/cost.h"
45 #include "optimizer/planner.h"
46 #include "parser/analyze.h"
47 #include "parser/parser.h"
48 #include "rewrite/rewriteHandler.h"
49 #include "storage/freespace.h"
50 #include "storage/ipc.h"
51 #include "storage/proc.h"
52 #include "tcop/fastpath.h"
53 #include "tcop/pquery.h"
54 #include "tcop/tcopprot.h"
55 #include "tcop/utility.h"
56 #include "utils/guc.h"
57 #include "utils/memutils.h"
58 #include "utils/ps_status.h"
59 #include "mb/pg_wchar.h"
71 const char *debug_query_string; /* for pgmonitor and
72 * log_min_error_statement */
74 /* Note: whereToSendOutput is initialized for the bootstrap/standalone case */
75 CommandDest whereToSendOutput = Debug;
77 static bool dontExecute = false;
79 /* note: these declarations had better match tcopprot.h */
80 sigjmp_buf Warn_restart;
82 bool Warn_restart_ready = false;
85 extern bool autocommit;
87 static bool EchoQuery = false; /* default don't echo */
90 * Flag to mark SIGHUP. Whenever the main loop comes around it
91 * will reread the configuration file. (Better than doing the
92 * reading in the signal handler, ey?)
94 static volatile bool got_SIGHUP = false;
97 * people who want to use EOF should #define DONTUSENEWLINE in
101 #ifndef TCOP_DONTUSENEWLINE
102 int UseNewLine = 1; /* Use newlines query delimiters (the
106 int UseNewLine = 0; /* Use EOF as query delimiters */
107 #endif /* TCOP_DONTUSENEWLINE */
110 ** Flags for expensive function optimization -- JMH 3/9/92
114 /* ----------------------------------------------------------------
115 * decls for routines only used in this file
116 * ----------------------------------------------------------------
118 static int InteractiveBackend(StringInfo inBuf);
119 static int SocketBackend(StringInfo inBuf);
120 static int ReadCommand(StringInfo inBuf);
121 static void start_xact_command(void);
122 static void finish_xact_command(bool forceCommit);
123 static void SigHupHandler(SIGNAL_ARGS);
124 static void FloatExceptionHandler(SIGNAL_ARGS);
125 static const char *CreateCommandTag(Node *parsetree);
128 /* ----------------------------------------------------------------
129 * routines to obtain user input
130 * ----------------------------------------------------------------
134 * InteractiveBackend() is called for user interactive connections
136 * the string entered by the user is placed in its parameter inBuf,
137 * and we act like a Q message was received.
139 * EOF is returned if end-of-file input is seen; time to shut down.
144 InteractiveBackend(StringInfo inBuf)
146 int c; /* character read from getc() */
147 bool end = false; /* end-of-input flag */
148 bool backslashSeen = false; /* have we seen a \ ? */
151 * display a prompt and obtain input from the user
156 /* Reset inBuf to empty */
158 inBuf->data[0] = '\0';
166 * if we are using \n as a delimiter, then read characters
169 while ((c = getc(stdin)) != EOF)
175 /* discard backslash from inBuf */
176 inBuf->data[--inBuf->len] = '\0';
177 backslashSeen = false;
182 /* keep the newline character */
183 appendStringInfoChar(inBuf, '\n');
188 backslashSeen = true;
190 backslashSeen = false;
192 appendStringInfoChar(inBuf, (char) c);
201 * otherwise read characters until EOF.
203 while ((c = getc(stdin)) != EOF)
204 appendStringInfoChar(inBuf, (char) c);
214 * otherwise we have a user query so process it.
219 /* Add '\0' to make it look the same as message case. */
220 appendStringInfoChar(inBuf, (char) '\0');
223 * if the query echo flag was given, print the query..
226 printf("statement: %s\n", inBuf->data);
233 * SocketBackend() Is called for frontend-backend connections
235 * Returns the message type code, and loads message body data into inBuf.
237 * EOF is returned if the connection is lost.
241 SocketBackend(StringInfo inBuf)
246 * Get message type code from the frontend.
248 qtype = pq_getbyte();
250 if (qtype == EOF) /* frontend disconnected */
252 elog(COMMERROR, "unexpected EOF on client connection");
257 * Validate message type code before trying to read body; if we have
258 * lost sync, better to say "command unknown" than to run out of memory
259 * because we used garbage as a length word.
263 case 'Q': /* simple query */
264 if (PG_PROTOCOL_MAJOR(FrontendProtocol) < 3)
266 /* old style without length word; convert */
267 if (pq_getstring(inBuf))
269 elog(COMMERROR, "unexpected EOF on client connection");
275 case 'F': /* fastpath function call */
278 case 'X': /* terminate */
281 case 'd': /* copy data */
282 case 'c': /* copy done */
283 case 'f': /* copy fail */
284 /* Accept but ignore these messages, per protocol spec */
289 * Otherwise we got garbage from the frontend. We treat this
290 * as fatal because we have probably lost message boundary sync,
291 * and there's no good way to recover.
293 elog(FATAL, "Socket command type %c unknown", qtype);
298 * In protocol version 3, all frontend messages have a length word
299 * next after the type code; we can read the message contents
300 * independently of the type.
302 if (PG_PROTOCOL_MAJOR(FrontendProtocol) >= 3)
304 if (pq_getmessage(inBuf, 0))
305 return EOF; /* suitable message already logged */
312 * ReadCommand reads a command from either the frontend or
313 * standard input, places it in inBuf, and returns a char
314 * representing whether the string is a 'Q'uery or a 'F'astpath
315 * call. EOF is returned if end of file.
319 ReadCommand(StringInfo inBuf)
323 if (IsUnderPostmaster)
324 result = SocketBackend(inBuf);
326 result = InteractiveBackend(inBuf);
332 * Parse a query string and pass it through the rewriter.
334 * A list of Query nodes is returned, since the string might contain
335 * multiple queries and/or the rewriter might expand one query to several.
337 * NOTE: this routine is no longer used for processing interactive queries,
338 * but it is still needed for parsing of SQL function bodies.
341 pg_parse_and_rewrite(const char *query_string, /* string to execute */
342 Oid *typev, /* parameter types */
343 int nargs) /* number of parameters */
345 List *raw_parsetree_list;
346 List *querytree_list;
350 * (1) parse the request string into a list of raw parse trees.
352 raw_parsetree_list = pg_parse_query(query_string, typev, nargs);
355 * (2) Do parse analysis and rule rewrite.
357 querytree_list = NIL;
358 foreach(list_item, raw_parsetree_list)
360 Node *parsetree = (Node *) lfirst(list_item);
362 querytree_list = nconc(querytree_list,
363 pg_analyze_and_rewrite(parsetree));
366 return querytree_list;
370 * Do raw parsing (only).
372 * A list of parsetrees is returned, since there might be multiple
373 * commands in the given string.
375 * NOTE: for interactive queries, it is important to keep this routine
376 * separate from the analysis & rewrite stages. Analysis and rewriting
377 * cannot be done in an aborted transaction, since they require access to
378 * database tables. So, we rely on the raw parser to determine whether
379 * we've seen a COMMIT or ABORT command; when we are in abort state, other
380 * commands are not processed any further than the raw parse stage.
383 pg_parse_query(const char *query_string, Oid *typev, int nargs)
385 List *raw_parsetree_list;
388 elog(LOG, "query: %s", query_string);
390 if (log_parser_stats)
393 raw_parsetree_list = parser(query_string, typev, nargs);
395 if (log_parser_stats)
396 ShowUsage("PARSER STATISTICS");
398 return raw_parsetree_list;
402 * Given a raw parsetree (gram.y output), perform parse analysis and
405 * A list of Query nodes is returned, since either the analyzer or the
406 * rewriter might expand one query to several.
408 * NOTE: for reasons mentioned above, this must be separate from raw parsing.
411 pg_analyze_and_rewrite(Node *parsetree)
413 List *querytree_list;
419 * (1) Perform parse analysis.
421 if (log_parser_stats)
424 querytree_list = parse_analyze(parsetree, NULL);
426 if (log_parser_stats)
428 ShowUsage("PARSE ANALYSIS STATISTICS");
433 * (2) Rewrite the queries, as necessary
435 * rewritten queries are collected in new_list. Note there may be more
436 * or fewer than in the original list.
439 foreach(list_item, querytree_list)
441 querytree = (Query *) lfirst(list_item);
443 if (Debug_print_parse)
444 elog_node_display(LOG, "parse tree", querytree,
447 if (querytree->commandType == CMD_UTILITY)
449 /* don't rewrite utilities, just dump 'em into new_list */
450 new_list = lappend(new_list, querytree);
454 /* rewrite regular queries */
455 List *rewritten = QueryRewrite(querytree);
457 new_list = nconc(new_list, rewritten);
461 querytree_list = new_list;
463 if (log_parser_stats)
464 ShowUsage("REWRITER STATISTICS");
466 #ifdef COPY_PARSE_PLAN_TREES
469 * Optional debugging check: pass querytree output through
472 new_list = (List *) copyObject(querytree_list);
473 /* This checks both copyObject() and the equal() routines... */
474 if (!equal(new_list, querytree_list))
475 elog(WARNING, "pg_analyze_and_rewrite: copyObject failed on parse tree");
477 querytree_list = new_list;
480 if (Debug_print_rewritten)
481 elog_node_display(LOG, "rewritten parse tree", querytree_list,
484 return querytree_list;
488 /* Generate a plan for a single query. */
490 pg_plan_query(Query *querytree)
494 /* Utility commands have no plans. */
495 if (querytree->commandType == CMD_UTILITY)
498 if (log_planner_stats)
501 /* call the optimizer */
502 plan = planner(querytree, false, 0);
504 if (log_planner_stats)
505 ShowUsage("PLANNER STATISTICS");
507 #ifdef COPY_PARSE_PLAN_TREES
508 /* Optional debugging check: pass plan output through copyObject() */
510 Plan *new_plan = (Plan *) copyObject(plan);
513 * equal() currently does not have routines to compare Plan nodes,
514 * so don't try to test equality here. Perhaps fix someday?
517 /* This checks both copyObject() and the equal() routines... */
518 if (!equal(new_plan, plan))
519 elog(WARNING, "pg_plan_query: copyObject failed on plan tree");
527 * Print plan if debugging.
529 if (Debug_print_plan)
530 elog_node_display(LOG, "plan", plan, Debug_pretty_print);
536 /* ----------------------------------------------------------------
537 * pg_exec_query_string()
539 * Takes a querystring, runs the parser/utilities or
540 * parser/planner/executor over it as necessary.
544 * At call, we are not inside a transaction command.
546 * The CurrentMemoryContext after starting a transaction command must be
547 * appropriate for execution of individual queries (typically this will be
548 * TransactionCommandContext). Note that this routine resets that context
549 * after each individual query, so don't store anything there that
550 * must outlive the call!
552 * parse_context references a context suitable for holding the
553 * parse/rewrite trees (typically this will be QueryContext).
554 * This context *must* be longer-lived than the transaction context!
555 * In fact, if the query string might contain BEGIN/COMMIT commands,
556 * parse_context had better outlive TopTransactionContext!
558 * We could have hard-wired knowledge about QueryContext and
559 * TransactionCommandContext into this routine, but it seems better
560 * not to, in case callers from outside this module need to use some
563 * ----------------------------------------------------------------
567 pg_exec_query_string(const char *query_string, /* string to execute */
568 CommandDest dest, /* where results should go */
569 MemoryContext parse_context) /* context for
573 MemoryContext oldcontext;
574 List *parsetree_list,
576 struct timeval start_t,
578 bool save_log_duration = log_duration;
580 debug_query_string = query_string;
583 * We use save_log_duration so "SET log_duration = true" doesn't
584 * report incorrect time because gettimeofday() wasn't called.
586 if (save_log_duration)
587 gettimeofday(&start_t, NULL);
590 * Start up a transaction command. All queries generated by the
591 * query_string will be in this same command block, *unless* we find a
592 * BEGIN/COMMIT/ABORT statement; we have to force a new xact command
593 * after one of those, else bad things will happen in xact.c. (Note
594 * that this will possibly change current memory context.)
596 start_xact_command();
600 * parse_context *must* be different from the execution memory
601 * context, else the context reset at the bottom of the loop will
602 * destroy the parsetree list. (We really ought to check that
603 * parse_context isn't a child of CurrentMemoryContext either, but
604 * that would take more cycles than it's likely to be worth.)
606 Assert(parse_context != CurrentMemoryContext);
609 * Switch to appropriate context for constructing parsetrees.
611 oldcontext = MemoryContextSwitchTo(parse_context);
614 * Do basic parsing of the query or queries (this should be safe even
615 * if we are in aborted transaction state!)
617 parsetree_list = pg_parse_query(query_string, NULL, 0);
620 * Switch back to execution context to enter the loop.
622 MemoryContextSwitchTo(oldcontext);
625 * Run through the parsetree(s) and process each one.
627 foreach(parsetree_item, parsetree_list)
629 Node *parsetree = (Node *) lfirst(parsetree_item);
630 const char *commandTag;
631 char completionTag[COMPLETION_TAG_BUFSIZE];
633 bool foundOriginalQuery = false;
634 List *querytree_list,
638 * First we set the command-completion tag to the main query (as
639 * opposed to each of the others that may be generated by analyze
640 * and rewrite). Also set ps_status and do any special
641 * start-of-SQL-command processing needed by the destination.
643 commandTag = CreateCommandTag(parsetree);
645 switch (nodeTag(parsetree))
648 origCmdType = CMD_INSERT;
651 origCmdType = CMD_DELETE;
654 origCmdType = CMD_UPDATE;
657 origCmdType = CMD_SELECT;
660 /* Otherwise, never match commandType */
661 origCmdType = CMD_UNKNOWN;
665 set_ps_display(commandTag);
667 BeginCommand(commandTag, dest);
670 * If we are in an aborted transaction, ignore all commands except
671 * COMMIT/ABORT. It is important that this test occur before we
672 * try to do parse analysis, rewrite, or planning, since all those
673 * phases try to do database accesses, which may fail in abort
674 * state. (It might be safe to allow some additional utility
675 * commands in this state, but not many...)
677 if (IsAbortedTransactionBlockState())
679 bool allowit = false;
681 if (IsA(parsetree, TransactionStmt))
683 TransactionStmt *stmt = (TransactionStmt *) parsetree;
685 if (stmt->kind == TRANS_STMT_COMMIT ||
686 stmt->kind == TRANS_STMT_ROLLBACK)
691 elog(ERROR, "current transaction is aborted, "
692 "queries ignored until end of transaction block");
695 /* Make sure we are in a transaction command */
698 start_xact_command();
702 /* If we got a cancel signal in parsing or prior command, quit */
703 CHECK_FOR_INTERRUPTS();
706 * OK to analyze and rewrite this query.
708 * Switch to appropriate context for constructing querytrees (again,
709 * these must outlive the execution context).
711 oldcontext = MemoryContextSwitchTo(parse_context);
713 querytree_list = pg_analyze_and_rewrite(parsetree);
716 * Switch back to execution context for planning and execution.
718 MemoryContextSwitchTo(oldcontext);
721 * Inner loop handles the individual queries generated from a
722 * single parsetree by analysis and rewrite.
724 foreach(querytree_item, querytree_list)
726 Query *querytree = (Query *) lfirst(querytree_item);
727 bool endTransactionBlock = false;
730 /* Make sure we are in a transaction command */
733 start_xact_command();
738 * If we got a cancel signal in analysis or prior command,
741 CHECK_FOR_INTERRUPTS();
744 * This query can set the completion tag if it is the original
745 * query, or if it is an INSTEAD query of the same kind as the
746 * original and we haven't yet seen the original query.
748 if (querytree->querySource == QSRC_ORIGINAL)
751 foundOriginalQuery = true;
753 else if (!foundOriginalQuery &&
754 querytree->commandType == origCmdType &&
755 (querytree->querySource == QSRC_INSTEAD_RULE ||
756 querytree->querySource == QSRC_QUAL_INSTEAD_RULE))
761 if (querytree->commandType == CMD_UTILITY)
764 * process utility functions (create, destroy, etc..)
766 Node *utilityStmt = querytree->utilityStmt;
768 elog(DEBUG2, "ProcessUtility");
771 * Set snapshot if utility stmt needs one. Most reliable
772 * way to do this seems to be to enumerate those that do not
773 * need one; this is a short list. Transaction control,
774 * LOCK, and SET must *not* set a snapshot since they need
775 * to be executable at the start of a serializable transaction
776 * without freezing a snapshot. By extension we allow SHOW
777 * not to set a snapshot. The other stmts listed are just
778 * efficiency hacks. Beware of listing anything that can
779 * modify the database --- if, say, it has to update a
780 * functional index, then it had better have a snapshot.
782 if (! (IsA(utilityStmt, TransactionStmt) ||
783 IsA(utilityStmt, LockStmt) ||
784 IsA(utilityStmt, VariableSetStmt) ||
785 IsA(utilityStmt, VariableShowStmt) ||
786 IsA(utilityStmt, VariableResetStmt) ||
787 IsA(utilityStmt, ConstraintsSetStmt) ||
788 /* efficiency hacks from here down */
789 IsA(utilityStmt, FetchStmt) ||
790 IsA(utilityStmt, ListenStmt) ||
791 IsA(utilityStmt, NotifyStmt) ||
792 IsA(utilityStmt, UnlistenStmt) ||
793 IsA(utilityStmt, CheckPointStmt)))
796 /* end transaction block if transaction or variable stmt */
797 if (IsA(utilityStmt, TransactionStmt) ||
798 IsA(utilityStmt, VariableSetStmt) ||
799 IsA(utilityStmt, VariableShowStmt) ||
800 IsA(utilityStmt, VariableResetStmt))
801 endTransactionBlock = true;
805 /* utility statement can override default tag string */
806 ProcessUtility(utilityStmt, dest, completionTag);
807 if (completionTag[0])
808 commandTag = completionTag;
812 /* utility added by rewrite cannot override tag */
813 ProcessUtility(utilityStmt, dest, NULL);
819 * process a plannable query.
824 * Initialize snapshot state for query. This has to
825 * be done before running the planner, because it might
826 * try to evaluate immutable or stable functions, which
827 * in turn might run queries.
832 plan = pg_plan_query(querytree);
834 /* if we got a cancel signal whilst planning, quit */
835 CHECK_FOR_INTERRUPTS();
840 if (log_executor_stats)
845 /* don't execute it, just show the query plan */
846 print_plan(plan, querytree);
850 elog(DEBUG2, "ProcessQuery");
854 /* statement can override default tag string */
855 ProcessQuery(querytree, plan, dest, completionTag);
856 commandTag = completionTag;
860 /* stmt added by rewrite cannot override tag */
861 ProcessQuery(querytree, plan, dest, NULL);
865 if (log_executor_stats)
866 ShowUsage("EXECUTOR STATISTICS");
870 * In a query block, we want to increment the command counter
871 * between queries so that the effects of early queries are
872 * visible to subsequent ones. In particular we'd better do
873 * so before checking constraints.
875 if (!endTransactionBlock)
876 CommandCounterIncrement();
879 * Clear the execution context to recover temporary memory
880 * used by the query. NOTE: if query string contains
881 * BEGIN/COMMIT transaction commands, execution context may
882 * now be different from what we were originally passed; so be
883 * careful to clear current context not "oldcontext".
885 Assert(parse_context != CurrentMemoryContext);
887 MemoryContextResetAndDeleteChildren(CurrentMemoryContext);
890 * If this was a transaction control statement or a variable
891 * set/show/reset statement, commit it and arrange to start a
892 * new xact command for the next command (if any).
894 if (endTransactionBlock)
896 finish_xact_command(true);
897 xact_started = false;
899 } /* end loop over queries generated from a
903 * If this is the last parsetree of the query string, close down
904 * transaction statement before reporting command-complete. This
905 * is so that any end-of-transaction errors are reported before
906 * the command-complete message is issued, to avoid confusing
907 * clients who will expect either a command-complete message or an
908 * error, not one and then the other. But for compatibility with
909 * historical Postgres behavior, we do not force a transaction
910 * boundary between queries appearing in a single query string.
912 if ((lnext(parsetree_item) == NIL || !autocommit) && xact_started)
914 finish_xact_command(false);
915 xact_started = false;
919 * It is possible that the original query was removed due to a DO
920 * INSTEAD rewrite rule. If so, and if we found no INSTEAD query
921 * matching the command type, we will still have the default
922 * completion tag. This is fine for most purposes, but it
923 * may confuse clients if it's INSERT/UPDATE/DELETE. Clients
924 * expect those tags to have counts after them (cf. ProcessQuery).
926 if (!foundOriginalQuery)
928 if (strcmp(commandTag, "INSERT") == 0)
929 commandTag = "INSERT 0 0";
930 else if (strcmp(commandTag, "UPDATE") == 0)
931 commandTag = "UPDATE 0";
932 else if (strcmp(commandTag, "DELETE") == 0)
933 commandTag = "DELETE 0";
937 * Tell client that we're done with this query. Note we emit
938 * exactly one EndCommand report for each raw parsetree, thus one
939 * for each SQL command the client sent, regardless of rewriting.
940 * (But a command aborted by error will not send an EndCommand
943 EndCommand(commandTag, dest);
944 } /* end loop over parsetrees */
946 /* No parsetree - return empty result */
951 * Close down transaction statement, if one is open. (Note that this
952 * will only happen if the querystring was empty.)
955 finish_xact_command(false);
957 if (save_log_duration)
959 gettimeofday(&stop_t, NULL);
960 if (stop_t.tv_usec < start_t.tv_usec)
963 stop_t.tv_usec += 1000000;
965 elog(LOG, "duration: %ld.%06ld sec",
966 (long) (stop_t.tv_sec - start_t.tv_sec),
967 (long) (stop_t.tv_usec - start_t.tv_usec));
970 debug_query_string = NULL;
974 * Convenience routines for starting/committing a single command.
977 start_xact_command(void)
979 elog(DEBUG1, "StartTransactionCommand");
980 StartTransactionCommand(false);
982 /* Set statement timeout running, if any */
983 if (StatementTimeout > 0)
984 enable_sig_alarm(StatementTimeout, true);
988 finish_xact_command(bool forceCommit)
990 /* Invoke IMMEDIATE constraint triggers */
991 DeferredTriggerEndQuery();
993 /* Cancel any active statement timeout before committing */
994 disable_sig_alarm(true);
996 /* Now commit the command */
997 elog(DEBUG1, "CommitTransactionCommand");
999 CommitTransactionCommand(forceCommit);
1001 #ifdef SHOW_MEMORY_STATS
1002 /* Print mem stats at each commit for leak tracking */
1004 MemoryContextStats(TopMemoryContext);
1009 /* --------------------------------
1010 * signal handler routines used in PostgresMain()
1011 * --------------------------------
1015 * quickdie() occurs when signalled SIGQUIT by the postmaster.
1017 * Some backend has bought the farm,
1018 * so we need to stop what we're doing and exit.
1021 quickdie(SIGNAL_ARGS)
1023 PG_SETMASK(&BlockSig);
1024 elog(WARNING, "Message from PostgreSQL backend:"
1025 "\n\tThe Postmaster has informed me that some other backend"
1026 "\n\tdied abnormally and possibly corrupted shared memory."
1027 "\n\tI have rolled back the current transaction and am"
1028 "\n\tgoing to terminate your database system connection and exit."
1029 "\n\tPlease reconnect to the database system and repeat your query.");
1032 * DO NOT proc_exit() -- we're here because shared memory may be
1033 * corrupted, so we don't want to try to clean up our transaction.
1034 * Just nail the windows shut and get out of town.
1036 * Note we do exit(1) not exit(0). This is to force the postmaster into
1037 * a system reset cycle if some idiot DBA sends a manual SIGQUIT to a
1038 * random backend. This is necessary precisely because we don't clean
1039 * up our shared memory state.
1046 * Shutdown signal from postmaster: abort transaction and exit
1047 * at soonest convenient time
1052 int save_errno = errno;
1054 /* Don't joggle the elbow of proc_exit */
1055 if (!proc_exit_inprogress)
1057 InterruptPending = true;
1058 ProcDiePending = true;
1061 * If it's safe to interrupt, and we're waiting for input or a
1062 * lock, service the interrupt immediately
1064 if (ImmediateInterruptOK && InterruptHoldoffCount == 0 &&
1065 CritSectionCount == 0)
1067 /* bump holdoff count to make ProcessInterrupts() a no-op */
1068 /* until we are done getting ready for it */
1069 InterruptHoldoffCount++;
1070 DisableNotifyInterrupt();
1071 /* Make sure CheckDeadLock won't run while shutting down... */
1073 InterruptHoldoffCount--;
1074 ProcessInterrupts();
1082 * Timeout or shutdown signal from postmaster during client authentication.
1085 * XXX: possible future improvement: try to send a message indicating
1086 * why we are disconnecting. Problem is to be sure we don't block while
1087 * doing so, nor mess up the authentication message exchange.
1090 authdie(SIGNAL_ARGS)
1096 * Query-cancel signal from postmaster: abort current transaction
1097 * at soonest convenient time
1100 StatementCancelHandler(SIGNAL_ARGS)
1102 int save_errno = errno;
1105 * Don't joggle the elbow of proc_exit, nor an already-in-progress
1108 if (!proc_exit_inprogress && !InError)
1110 InterruptPending = true;
1111 QueryCancelPending = true;
1114 * If it's safe to interrupt, and we're waiting for a lock,
1115 * service the interrupt immediately. No point in interrupting if
1116 * we're waiting for input, however.
1118 if (ImmediateInterruptOK && InterruptHoldoffCount == 0 &&
1119 CritSectionCount == 0)
1121 /* bump holdoff count to make ProcessInterrupts() a no-op */
1122 /* until we are done getting ready for it */
1123 InterruptHoldoffCount++;
1124 if (LockWaitCancel())
1126 DisableNotifyInterrupt();
1127 InterruptHoldoffCount--;
1128 ProcessInterrupts();
1131 InterruptHoldoffCount--;
1138 /* signal handler for floating point exception */
1140 FloatExceptionHandler(SIGNAL_ARGS)
1142 elog(ERROR, "floating point exception!"
1143 " The last floating point operation either exceeded legal ranges"
1144 " or was a divide by zero");
1147 /* SIGHUP: set flag to re-read config file at next convenient time */
1149 SigHupHandler(SIGNAL_ARGS)
1156 * ProcessInterrupts: out-of-line portion of CHECK_FOR_INTERRUPTS() macro
1158 * If an interrupt condition is pending, and it's safe to service it,
1159 * then clear the flag and accept the interrupt. Called only when
1160 * InterruptPending is true.
1163 ProcessInterrupts(void)
1165 /* OK to accept interrupt now? */
1166 if (InterruptHoldoffCount != 0 || CritSectionCount != 0)
1168 InterruptPending = false;
1171 ProcDiePending = false;
1172 QueryCancelPending = false; /* ProcDie trumps QueryCancel */
1173 ImmediateInterruptOK = false; /* not idle anymore */
1174 DisableNotifyInterrupt();
1175 elog(FATAL, "This connection has been terminated by the administrator.");
1177 if (QueryCancelPending)
1179 QueryCancelPending = false;
1180 ImmediateInterruptOK = false; /* not idle anymore */
1181 DisableNotifyInterrupt();
1182 elog(ERROR, "Query was canceled.");
1184 /* If we get here, do nothing (probably, QueryCancelPending was reset) */
1189 usage(char *progname)
1191 printf("%s is the PostgreSQL stand-alone backend. It is not\nintended to be used by normal users.\n\n", progname);
1193 printf("Usage:\n %s [OPTION]... [DBNAME]\n\n", progname);
1194 printf("Options:\n");
1195 #ifdef USE_ASSERT_CHECKING
1196 printf(" -A 1|0 enable/disable run-time assert checking\n");
1198 printf(" -B NBUFFERS number of shared buffers (default %d)\n", DEF_NBUFFERS);
1199 printf(" -c NAME=VALUE set run-time parameter\n");
1200 printf(" -d 0-5 debugging level (0 is off)\n");
1201 printf(" -D DATADIR database directory\n");
1202 printf(" -e use European date format\n");
1203 printf(" -E echo query before execution\n");
1204 printf(" -F turn fsync off\n");
1205 printf(" -N do not use newline as interactive query delimiter\n");
1206 printf(" -o FILENAME send stdout and stderr to given file\n");
1207 printf(" -P disable system indexes\n");
1208 printf(" -s show statistics after each query\n");
1209 printf(" -S SORT-MEM set amount of memory for sorts (in kbytes)\n");
1210 printf(" --help show this help, then exit\n");
1211 printf(" --version output version information, then exit\n");
1212 printf("\nDeveloper options:\n");
1213 printf(" -f s|i|n|m|h forbid use of some plan types\n");
1214 printf(" -i do not execute queries\n");
1215 printf(" -O allow system table structure changes\n");
1216 printf(" -t pa|pl|ex show timings after each query\n");
1217 printf(" -W NUM wait NUM seconds to allow attach from a debugger\n");
1218 printf("\nReport bugs to <pgsql-bugs@postgresql.org>.\n");
1223 /* ----------------------------------------------------------------
1225 * postgres main loop -- all backends, interactive or otherwise start here
1227 * argc/argv are the command line arguments to be used. (When being forked
1228 * by the postmaster, these are not the original argv array of the process.)
1229 * username is the (possibly authenticated) PostgreSQL user name to be used
1231 * ----------------------------------------------------------------
1234 PostgresMain(int argc, char *argv[], const char *username)
1237 const char *DBName = NULL;
1238 char *potential_DataDir = NULL;
1243 GucSource gucsource;
1246 StringInfo input_message;
1250 * Catch standard options before doing much else. This even works on
1251 * systems without getopt_long.
1253 if (!IsUnderPostmaster && argc > 1)
1255 if (strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-?") == 0)
1260 if (strcmp(argv[1], "--version") == 0 || strcmp(argv[1], "-V") == 0)
1262 puts("postgres (PostgreSQL) " PG_VERSION);
1268 * initialize globals (already done if under postmaster, but not if
1269 * standalone; cheap enough to do over)
1272 MyProcPid = getpid();
1275 * Fire up essential subsystems: error and memory management
1277 * If we are running under the postmaster, this is done already.
1279 if (!IsUnderPostmaster)
1280 MemoryContextInit();
1282 set_ps_display("startup");
1284 SetProcessingMode(InitProcessing);
1287 * Set default values for command-line options.
1292 if (!IsUnderPostmaster)
1294 InitializeGUCOptions();
1295 potential_DataDir = getenv("PGDATA");
1299 * parse command line arguments
1301 * There are now two styles of command line layout for the backend:
1303 * For interactive use (not started from postmaster) the format is
1304 * postgres [switches] [databasename]
1305 * If the databasename is omitted it is taken to be the user name.
1307 * When started from the postmaster, the format is
1308 * postgres [secure switches] -p databasename [insecure switches]
1309 * Switches appearing after -p came from the client (via "options"
1310 * field of connection request). For security reasons we restrict
1311 * what these switches can do.
1315 /* all options are allowed until '-p' */
1317 ctx = PGC_POSTMASTER;
1318 gucsource = PGC_S_ARGV; /* initial switches came from command line */
1320 while ((flag = getopt(argc, argv, "A:B:c:CD:d:Eef:FiNOPo:p:S:st:v:W:x:-:")) != -1)
1324 #ifdef USE_ASSERT_CHECKING
1325 SetConfigOption("debug_assertions", optarg, ctx, gucsource);
1327 elog(WARNING, "Assert checking is not compiled in");
1334 * specify the size of buffer pool
1336 SetConfigOption("shared_buffers", optarg, ctx, gucsource);
1342 * don't print version string
1347 case 'D': /* PGDATA directory */
1349 potential_DataDir = optarg;
1352 case 'd': /* debug level */
1354 debug_flag = atoi(optarg);
1355 /* Set server debugging level. */
1356 if (atoi(optarg) != 0)
1358 char *debugstr = palloc(strlen("debug") + strlen(optarg) + 1);
1360 sprintf(debugstr, "debug%s", optarg);
1361 SetConfigOption("log_min_messages", debugstr, ctx, gucsource);
1367 * -d0 allows user to prevent postmaster debug
1368 * from propagating to backend. It would be nice
1369 * to set it to the postgresql.conf value here.
1371 SetConfigOption("log_min_messages", "notice",
1379 * E - echo the query the user entered
1387 * Use european date formats.
1389 SetConfigOption("datestyle", "euro", ctx, gucsource);
1397 SetConfigOption("fsync", "false", ctx, gucsource);
1403 * f - forbid generation of certain plans
1408 case 's': /* seqscan */
1409 tmp = "enable_seqscan";
1411 case 'i': /* indexscan */
1412 tmp = "enable_indexscan";
1414 case 't': /* tidscan */
1415 tmp = "enable_tidscan";
1417 case 'n': /* nestloop */
1418 tmp = "enable_nestloop";
1420 case 'm': /* mergejoin */
1421 tmp = "enable_mergejoin";
1423 case 'h': /* hashjoin */
1424 tmp = "enable_hashjoin";
1430 SetConfigOption(tmp, "false", ctx, gucsource);
1440 * N - Don't use newline as a query delimiter
1448 * allow system table structure modifications
1450 if (secure) /* XXX safe to allow from client??? */
1451 allowSystemTableMods = true;
1457 * ignore system indexes
1459 if (secure) /* XXX safe to allow from client??? */
1460 IgnoreSystemIndexes(true);
1466 * o - send output (stdout and stderr) to the given file
1469 StrNCpy(OutputFileName, optarg, MAXPGPATH);
1475 * p - special flag passed if backend was forked by a
1480 DBName = strdup(optarg);
1481 secure = false; /* subsequent switches are NOT
1484 gucsource = PGC_S_CLIENT;
1491 * S - amount of sort memory to use in 1k bytes
1493 SetConfigOption("sort_mem", optarg, ctx, gucsource);
1499 * s - report usage statistics (timings) after each query
1501 SetConfigOption("show_statement_stats", "true", ctx, gucsource);
1506 * tell postgres to report usage statistics (timings) for
1509 * -tpa[rser] = print stats for parser time of each query
1510 * -tpl[anner] = print stats for planner time of each query
1511 * -te[xecutor] = print stats for executor time of each query
1512 * caution: -s can not be used together with -t.
1519 if (optarg[1] == 'a')
1520 tmp = "log_parser_stats";
1521 else if (optarg[1] == 'l')
1522 tmp = "log_planner_stats";
1527 tmp = "show_executor_stats";
1534 SetConfigOption(tmp, "true", ctx, gucsource);
1539 FrontendProtocol = (ProtocolVersion) atoi(optarg);
1545 * wait N seconds to allow attach from a debugger
1547 sleep(atoi(optarg));
1551 #ifdef NOT_USED /* planner/xfunc.h */
1554 * control joey hellerstein's expensive function
1559 elog(WARNING, "only one -x flag is allowed");
1563 if (strcmp(optarg, "off") == 0)
1564 XfuncMode = XFUNC_OFF;
1565 else if (strcmp(optarg, "nor") == 0)
1566 XfuncMode = XFUNC_NOR;
1567 else if (strcmp(optarg, "nopull") == 0)
1568 XfuncMode = XFUNC_NOPULL;
1569 else if (strcmp(optarg, "nopm") == 0)
1570 XfuncMode = XFUNC_NOPM;
1571 else if (strcmp(optarg, "pullall") == 0)
1572 XfuncMode = XFUNC_PULLALL;
1573 else if (strcmp(optarg, "wait") == 0)
1574 XfuncMode = XFUNC_WAIT;
1577 elog(WARNING, "use -x {off,nor,nopull,nopm,pullall,wait}");
1589 ParseLongOption(optarg, &name, &value);
1593 elog(ERROR, "--%s requires argument", optarg);
1595 elog(ERROR, "-c %s requires argument", optarg);
1598 SetConfigOption(name, value, ctx, gucsource);
1611 * -d is not the same as setting
1612 * log_min_messages because it enables other
1615 if (debug_flag >= 1)
1616 SetConfigOption("log_connections", "true", ctx, gucsource);
1617 if (debug_flag >= 2)
1618 SetConfigOption("log_statement", "true", ctx, gucsource);
1619 if (debug_flag >= 3)
1620 SetConfigOption("debug_print_parse", "true", ctx, gucsource);
1621 if (debug_flag >= 4)
1622 SetConfigOption("debug_print_plan", "true", ctx, gucsource);
1623 if (debug_flag >= 5)
1624 SetConfigOption("debug_print_rewritten", "true", ctx, gucsource);
1627 * Process any additional GUC variable settings passed in startup packet.
1629 if (MyProcPort != NULL)
1631 List *gucopts = MyProcPort->guc_options;
1638 name = lfirst(gucopts);
1639 gucopts = lnext(gucopts);
1640 value = lfirst(gucopts);
1641 gucopts = lnext(gucopts);
1642 SetConfigOption(name, value, PGC_BACKEND, PGC_S_CLIENT);
1647 * Post-processing for command line options.
1649 if (log_statement_stats &&
1650 (log_parser_stats || log_planner_stats || log_executor_stats))
1652 elog(WARNING, "Query statistics are disabled because parser, planner, or executor statistics are on.");
1653 SetConfigOption("show_statement_stats", "false", ctx, gucsource);
1656 if (!IsUnderPostmaster)
1658 if (!potential_DataDir)
1660 fprintf(stderr, "%s does not know where to find the database system "
1661 "data. You must specify the directory that contains the "
1662 "database system either by specifying the -D invocation "
1663 "option or by setting the PGDATA environment variable.\n\n",
1667 SetDataDir(potential_DataDir);
1672 * Set up signal handlers and masks.
1674 * Note that postmaster blocked all signals before forking child process,
1675 * so there is no race condition whereby we might receive a signal
1676 * before we have set up the handler.
1678 * Also note: it's best not to use any signals that are SIG_IGNored in
1679 * the postmaster. If such a signal arrives before we are able to
1680 * change the handler to non-SIG_IGN, it'll get dropped. Instead,
1681 * make a dummy handler in the postmaster to reserve the signal. (Of
1682 * course, this isn't an issue for signals that are locally generated,
1683 * such as SIGALRM and SIGPIPE.)
1686 pqsignal(SIGHUP, SigHupHandler); /* set flag to read config file */
1687 pqsignal(SIGINT, StatementCancelHandler); /* cancel current query */
1688 pqsignal(SIGTERM, die); /* cancel current query and exit */
1689 pqsignal(SIGQUIT, quickdie); /* hard crash time */
1690 pqsignal(SIGALRM, handle_sig_alarm); /* timeout conditions */
1693 * Ignore failure to write to frontend. Note: if frontend closes
1694 * connection, we will notice it and exit cleanly when control next
1695 * returns to outer loop. This seems safer than forcing exit in the
1696 * midst of output during who-knows-what operation...
1698 pqsignal(SIGPIPE, SIG_IGN);
1699 pqsignal(SIGUSR1, SIG_IGN); /* this signal available for use */
1701 pqsignal(SIGUSR2, Async_NotifyHandler); /* flush also sinval cache */
1702 pqsignal(SIGFPE, FloatExceptionHandler);
1705 * Reset some signals that are accepted by postmaster but not by
1708 pqsignal(SIGCHLD, SIG_DFL); /* system() requires this on some
1713 /* We allow SIGQUIT (quickdie) at all times */
1714 #ifdef HAVE_SIGPROCMASK
1715 sigdelset(&BlockSig, SIGQUIT);
1717 BlockSig &= ~(sigmask(SIGQUIT));
1720 PG_SETMASK(&BlockSig); /* block everything except SIGQUIT */
1723 if (IsUnderPostmaster)
1725 /* noninteractive case: nothing should be left after switches */
1726 if (errs || argc != optind || DBName == NULL)
1728 elog(WARNING, "%s: invalid command line arguments\nTry -? for help.",
1730 proc_exit(0); /* not 1, that causes system-wide
1737 /* interactive case: database name can be last arg on command line */
1738 if (errs || argc - optind > 1)
1740 elog(WARNING, "%s: invalid command line arguments\nTry -? for help.",
1744 else if (argc - optind == 1)
1745 DBName = argv[optind];
1746 else if ((DBName = username) == NULL)
1748 elog(WARNING, "%s: user name undefined and no database specified",
1754 * On some systems our dynloader code needs the executable's
1755 * pathname. (If under postmaster, this was done already.)
1757 if (FindExec(pg_pathname, argv[0], "postgres") < 0)
1758 elog(FATAL, "%s: could not locate executable, bailing out...",
1762 * Validate we have been given a reasonable-looking DataDir (if
1763 * under postmaster, assume postmaster did this already).
1765 ValidatePgVersion(DataDir);
1768 * Create lockfile for data directory.
1770 if (!CreateDataDirLockFile(DataDir, false))
1777 * Start up xlog for standalone backend, and register to have it
1778 * closed down at exit.
1781 on_shmem_exit(ShutdownXLOG, 0);
1784 * Read any existing FSM cache file, and register to write one out
1788 on_shmem_exit(DumpFreeSpaceMap, 0);
1792 * Set up additional info.
1800 * General initialization.
1802 * NOTE: if you are tempted to add code in this vicinity, consider
1803 * putting it inside InitPostgres() instead. In particular, anything
1804 * that involves database access should be there, not here.
1806 elog(DEBUG2, "InitPostgres");
1807 InitPostgres(DBName, username);
1809 SetProcessingMode(NormalProcessing);
1812 * Send this backend's cancellation info to the frontend.
1814 if (whereToSendOutput == Remote &&
1815 PG_PROTOCOL_MAJOR(FrontendProtocol) >= 2)
1819 pq_beginmessage(&buf, 'K');
1820 pq_sendint(&buf, (int32) MyProcPid, sizeof(int32));
1821 pq_sendint(&buf, (int32) MyCancelKey, sizeof(int32));
1822 pq_endmessage(&buf);
1823 /* Need not flush since ReadyForQuery will do it. */
1826 if (!IsUnderPostmaster)
1828 puts("\nPOSTGRES backend interactive interface ");
1829 puts("$Revision: 1.325 $ $Date: 2003/04/27 20:09:44 $\n");
1833 * Create the memory context we will use in the main loop.
1835 * QueryContext is reset once per iteration of the main loop, ie, upon
1836 * completion of processing of each supplied query string. It can
1837 * therefore be used for any data that should live just as long as the
1838 * query string --- parse trees, for example.
1840 QueryContext = AllocSetContextCreate(TopMemoryContext,
1842 ALLOCSET_DEFAULT_MINSIZE,
1843 ALLOCSET_DEFAULT_INITSIZE,
1844 ALLOCSET_DEFAULT_MAXSIZE);
1847 * Tell the statistics collector that we're alive and
1848 * to which database we belong.
1854 * POSTGRES main processing loop begins here
1856 * If an exception is encountered, processing resumes here so we abort
1857 * the current transaction and start a new one.
1860 if (sigsetjmp(Warn_restart, 1) != 0)
1863 * NOTE: if you are tempted to add more code in this if-block,
1864 * consider the probability that it should be in
1865 * AbortTransaction() instead.
1867 * Make sure we're not interrupted while cleaning up. Also forget
1868 * any pending QueryCancel request, since we're aborting anyway.
1869 * Force InterruptHoldoffCount to a known state in case we elog'd
1870 * from inside a holdoff section.
1872 ImmediateInterruptOK = false;
1873 QueryCancelPending = false;
1874 InterruptHoldoffCount = 1;
1875 CritSectionCount = 0; /* should be unnecessary, but... */
1876 disable_sig_alarm(true);
1877 QueryCancelPending = false; /* again in case timeout occurred */
1878 DisableNotifyInterrupt();
1879 debug_query_string = NULL;
1882 * Make sure we are in a valid memory context during recovery.
1884 * We use ErrorContext in hopes that it will have some free space
1885 * even if we're otherwise up against it...
1887 MemoryContextSwitchTo(ErrorContext);
1889 /* Do the recovery */
1890 elog(DEBUG1, "AbortCurrentTransaction");
1891 AbortCurrentTransaction();
1894 * Now return to normal top-level context and clear ErrorContext
1897 MemoryContextSwitchTo(TopMemoryContext);
1898 MemoryContextResetAndDeleteChildren(ErrorContext);
1901 * Clear flag to indicate that we got out of error recovery mode
1902 * successfully. (Flag was set in elog.c before longjmp().)
1907 * Exit interrupt holdoff section we implicitly established above.
1909 RESUME_INTERRUPTS();
1912 Warn_restart_ready = true; /* we can now handle elog(ERROR) */
1914 PG_SETMASK(&UnBlockSig);
1916 send_rfq = true; /* initially, or after error */
1919 * Non-error queries loop here.
1925 * Release storage left over from prior query cycle, and create a
1926 * new query input buffer in the cleared QueryContext.
1928 MemoryContextSwitchTo(QueryContext);
1929 MemoryContextResetAndDeleteChildren(QueryContext);
1931 input_message = makeStringInfo();
1934 * (1) tell the frontend we're ready for a new query.
1936 * Note: this includes fflush()'ing the last of the prior output.
1940 ReadyForQuery(whereToSendOutput);
1945 * Tell the statistics collector what we've collected
1949 pgstat_report_tabstat();
1951 if (IsTransactionBlock())
1953 set_ps_display("idle in transaction");
1954 pgstat_report_activity("<IDLE> in transaction");
1958 set_ps_display("idle");
1959 pgstat_report_activity("<IDLE>");
1963 * (2) deal with pending asynchronous NOTIFY from other backends,
1964 * and enable async.c's signal handler to execute NOTIFY directly.
1965 * Then set up other stuff needed before blocking for input.
1967 QueryCancelPending = false; /* forget any earlier CANCEL
1970 EnableNotifyInterrupt();
1972 /* Allow "die" interrupt to be processed while waiting */
1973 ImmediateInterruptOK = true;
1974 /* and don't forget to detect one that already arrived */
1975 QueryCancelPending = false;
1976 CHECK_FOR_INTERRUPTS();
1979 * (3) read a command (loop blocks here)
1981 firstchar = ReadCommand(input_message);
1984 * (4) disable async signal conditions again.
1986 ImmediateInterruptOK = false;
1987 QueryCancelPending = false; /* forget any CANCEL signal */
1989 DisableNotifyInterrupt();
1992 * (5) check for any other interesting events that happened while
1998 ProcessConfigFile(PGC_SIGHUP);
2002 * (6) process the command.
2006 case 'Q': /* simple query */
2009 * Process the query string.
2011 * Note: transaction command start/end is now done within
2012 * pg_exec_query_string(), not here.
2014 const char *query_string = pq_getmsgstring(input_message);
2016 if (log_statement_stats)
2019 pgstat_report_activity(query_string);
2021 pg_exec_query_string(query_string,
2025 if (log_statement_stats)
2026 ShowUsage("QUERY STATISTICS");
2032 case 'F': /* fastpath function call */
2033 /* Tell the collector what we're doing */
2034 pgstat_report_activity("<FASTPATH> function call");
2036 /* start an xact for this function invocation */
2037 start_xact_command();
2039 if (HandleFunctionRequest(input_message) == EOF)
2041 /* lost frontend connection during F message input */
2044 * Reset whereToSendOutput to prevent elog from
2045 * attempting to send any more messages to client.
2047 if (whereToSendOutput == Remote)
2048 whereToSendOutput = None;
2053 /* commit the function-invocation transaction */
2054 finish_xact_command(false);
2060 * 'X' means that the frontend is closing down the socket.
2061 * EOF means unexpected loss of frontend connection.
2062 * Either way, perform normal shutdown.
2068 * Reset whereToSendOutput to prevent elog from attempting
2069 * to send any more messages to client.
2071 if (whereToSendOutput == Remote)
2072 whereToSendOutput = None;
2075 * NOTE: if you are tempted to add more code here, DON'T!
2076 * Whatever you had in mind to do should be set up as an
2077 * on_proc_exit or on_shmem_exit callback, instead.
2078 * Otherwise it will fail to be called during other
2079 * backend-shutdown scenarios.
2083 case 'd': /* copy data */
2084 case 'c': /* copy done */
2085 case 'f': /* copy fail */
2087 * Accept but ignore these messages, per protocol spec;
2088 * we probably got here because a COPY failed, and the
2089 * frontend is still sending data.
2094 elog(FATAL, "Socket command type %c unknown", firstchar);
2097 #ifdef MEMORY_CONTEXT_CHECKING
2100 * Check all memory after each backend loop. This is a rather
2101 * weird place to do it, perhaps.
2103 MemoryContextCheck(TopMemoryContext);
2105 } /* end of input-reading loop */
2107 /* can't get here because the above loop never exits */
2110 return 1; /* keep compiler quiet */
2113 #ifndef HAVE_GETRUSAGE
2114 #include "rusagestub.h"
2116 #include <sys/resource.h>
2117 #endif /* HAVE_GETRUSAGE */
2119 struct rusage Save_r;
2120 struct timeval Save_t;
2125 getrusage(RUSAGE_SELF, &Save_r);
2126 gettimeofday(&Save_t, NULL);
2128 /* ResetTupleCount(); */
2132 ShowUsage(const char *title)
2135 struct timeval user,
2137 struct timeval elapse_t;
2141 getrusage(RUSAGE_SELF, &r);
2142 gettimeofday(&elapse_t, NULL);
2143 memcpy((char *) &user, (char *) &r.ru_utime, sizeof(user));
2144 memcpy((char *) &sys, (char *) &r.ru_stime, sizeof(sys));
2145 if (elapse_t.tv_usec < Save_t.tv_usec)
2148 elapse_t.tv_usec += 1000000;
2150 if (r.ru_utime.tv_usec < Save_r.ru_utime.tv_usec)
2152 r.ru_utime.tv_sec--;
2153 r.ru_utime.tv_usec += 1000000;
2155 if (r.ru_stime.tv_usec < Save_r.ru_stime.tv_usec)
2157 r.ru_stime.tv_sec--;
2158 r.ru_stime.tv_usec += 1000000;
2162 * the only stats we don't show here are for memory usage -- i can't
2163 * figure out how to interpret the relevant fields in the rusage
2164 * struct, and they change names across o/s platforms, anyway. if you
2165 * can figure out what the entries mean, you can somehow extract
2166 * resident set size, shared text size, and unshared data and stack
2169 initStringInfo(&str);
2171 appendStringInfo(&str, "! system usage stats:\n");
2172 appendStringInfo(&str,
2173 "!\t%ld.%06ld elapsed %ld.%06ld user %ld.%06ld system sec\n",
2174 (long) (elapse_t.tv_sec - Save_t.tv_sec),
2175 (long) (elapse_t.tv_usec - Save_t.tv_usec),
2176 (long) (r.ru_utime.tv_sec - Save_r.ru_utime.tv_sec),
2177 (long) (r.ru_utime.tv_usec - Save_r.ru_utime.tv_usec),
2178 (long) (r.ru_stime.tv_sec - Save_r.ru_stime.tv_sec),
2179 (long) (r.ru_stime.tv_usec - Save_r.ru_stime.tv_usec));
2180 appendStringInfo(&str,
2181 "!\t[%ld.%06ld user %ld.%06ld sys total]\n",
2183 (long) user.tv_usec,
2185 (long) sys.tv_usec);
2186 /* BeOS has rusage but only has some fields, and not these... */
2187 #if defined(HAVE_GETRUSAGE)
2188 appendStringInfo(&str,
2189 "!\t%ld/%ld [%ld/%ld] filesystem blocks in/out\n",
2190 r.ru_inblock - Save_r.ru_inblock,
2191 /* they only drink coffee at dec */
2192 r.ru_oublock - Save_r.ru_oublock,
2193 r.ru_inblock, r.ru_oublock);
2194 appendStringInfo(&str,
2195 "!\t%ld/%ld [%ld/%ld] page faults/reclaims, %ld [%ld] swaps\n",
2196 r.ru_majflt - Save_r.ru_majflt,
2197 r.ru_minflt - Save_r.ru_minflt,
2198 r.ru_majflt, r.ru_minflt,
2199 r.ru_nswap - Save_r.ru_nswap,
2201 appendStringInfo(&str,
2202 "!\t%ld [%ld] signals rcvd, %ld/%ld [%ld/%ld] messages rcvd/sent\n",
2203 r.ru_nsignals - Save_r.ru_nsignals,
2205 r.ru_msgrcv - Save_r.ru_msgrcv,
2206 r.ru_msgsnd - Save_r.ru_msgsnd,
2207 r.ru_msgrcv, r.ru_msgsnd);
2208 appendStringInfo(&str,
2209 "!\t%ld/%ld [%ld/%ld] voluntary/involuntary context switches\n",
2210 r.ru_nvcsw - Save_r.ru_nvcsw,
2211 r.ru_nivcsw - Save_r.ru_nivcsw,
2212 r.ru_nvcsw, r.ru_nivcsw);
2213 #endif /* HAVE_GETRUSAGE */
2215 bufusage = ShowBufferUsage();
2216 appendStringInfo(&str, "! buffer usage stats:\n%s", bufusage);
2219 /* remove trailing newline */
2220 if (str.data[str.len - 1] == '\n')
2221 str.data[--str.len] = '\0';
2223 elog(LOG, "%s\n%s", title, str.data);
2228 /* ----------------------------------------------------------------
2231 * utility to get a string representation of the
2232 * command operation.
2233 * ----------------------------------------------------------------
2236 CreateCommandTag(Node *parsetree)
2240 switch (nodeTag(parsetree))
2258 case T_TransactionStmt:
2260 TransactionStmt *stmt = (TransactionStmt *) parsetree;
2264 case TRANS_STMT_BEGIN:
2268 case TRANS_STMT_START:
2269 tag = "START TRANSACTION";
2272 case TRANS_STMT_COMMIT:
2276 case TRANS_STMT_ROLLBACK:
2287 case T_DeclareCursorStmt:
2288 tag = "DECLARE CURSOR";
2291 case T_ClosePortalStmt:
2292 tag = "CLOSE CURSOR";
2297 FetchStmt *stmt = (FetchStmt *) parsetree;
2299 tag = (stmt->ismove) ? "MOVE" : "FETCH";
2303 case T_CreateDomainStmt:
2304 tag = "CREATE DOMAIN";
2307 case T_CreateSchemaStmt:
2308 tag = "CREATE SCHEMA";
2312 tag = "CREATE TABLE";
2316 switch (((DropStmt *) parsetree)->removeType)
2322 tag = "DROP SEQUENCE";
2334 tag = "DROP DOMAIN";
2336 case DROP_CONVERSION:
2337 tag = "DROP CONVERSION";
2340 tag = "DROP SCHEMA";
2347 case T_TruncateStmt:
2348 tag = "TRUNCATE TABLE";
2360 if (((RenameStmt *) parsetree)->renameType == RENAME_TRIGGER)
2361 tag = "ALTER TRIGGER";
2363 tag = "ALTER TABLE";
2366 case T_AlterTableStmt:
2367 tag = "ALTER TABLE";
2370 case T_AlterDomainStmt:
2371 tag = "ALTER DOMAIN";
2376 GrantStmt *stmt = (GrantStmt *) parsetree;
2378 tag = (stmt->is_grant) ? "GRANT" : "REVOKE";
2383 switch (((DefineStmt *) parsetree)->kind)
2385 case DEFINE_STMT_AGGREGATE:
2386 tag = "CREATE AGGREGATE";
2388 case DEFINE_STMT_OPERATOR:
2389 tag = "CREATE OPERATOR";
2391 case DEFINE_STMT_TYPE:
2392 tag = "CREATE TYPE";
2399 case T_CompositeTypeStmt:
2400 tag = "CREATE TYPE";
2404 tag = "CREATE VIEW";
2407 case T_CreateFunctionStmt:
2408 tag = "CREATE FUNCTION";
2412 tag = "CREATE INDEX";
2416 tag = "CREATE RULE";
2419 case T_CreateSeqStmt:
2420 tag = "CREATE SEQUENCE";
2423 case T_AlterSeqStmt:
2424 tag = "ALTER SEQUENCE";
2427 case T_RemoveAggrStmt:
2428 tag = "DROP AGGREGATE";
2431 case T_RemoveFuncStmt:
2432 tag = "DROP FUNCTION";
2435 case T_RemoveOperStmt:
2436 tag = "DROP OPERATOR";
2439 case T_CreatedbStmt:
2440 tag = "CREATE DATABASE";
2443 case T_AlterDatabaseSetStmt:
2444 tag = "ALTER DATABASE";
2448 tag = "DROP DATABASE";
2459 case T_UnlistenStmt:
2472 if (((VacuumStmt *) parsetree)->vacuum)
2482 case T_VariableSetStmt:
2486 case T_VariableShowStmt:
2490 case T_VariableResetStmt:
2494 case T_CreateTrigStmt:
2495 tag = "CREATE TRIGGER";
2498 case T_DropPropertyStmt:
2499 switch (((DropPropertyStmt *) parsetree)->removeType)
2502 tag = "DROP TRIGGER";
2512 case T_CreatePLangStmt:
2513 tag = "CREATE LANGUAGE";
2516 case T_DropPLangStmt:
2517 tag = "DROP LANGUAGE";
2520 case T_CreateUserStmt:
2521 tag = "CREATE USER";
2524 case T_AlterUserStmt:
2528 case T_AlterUserSetStmt:
2532 case T_DropUserStmt:
2540 case T_ConstraintsSetStmt:
2541 tag = "SET CONSTRAINTS";
2544 case T_CreateGroupStmt:
2545 tag = "CREATE GROUP";
2548 case T_AlterGroupStmt:
2549 tag = "ALTER GROUP";
2552 case T_DropGroupStmt:
2556 case T_CheckPointStmt:
2564 case T_CreateConversionStmt:
2565 tag = "CREATE CONVERSION";
2568 case T_CreateCastStmt:
2569 tag = "CREATE CAST";
2572 case T_DropCastStmt:
2576 case T_CreateOpClassStmt:
2577 tag = "CREATE OPERATOR CLASS";
2580 case T_RemoveOpClassStmt:
2581 tag = "DROP OPERATOR CLASS";
2592 case T_DeallocateStmt:
2597 elog(LOG, "CreateCommandTag: unknown parse node type %d",
2598 nodeTag(parsetree));