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.333 2003/05/06 00:20:33 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/proc.h"
55 #include "tcop/fastpath.h"
56 #include "tcop/pquery.h"
57 #include "tcop/tcopprot.h"
58 #include "tcop/utility.h"
59 #include "utils/guc.h"
60 #include "utils/lsyscache.h"
61 #include "utils/memutils.h"
62 #include "utils/ps_status.h"
63 #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;
87 extern bool autocommit;
90 * Flags for expensive function optimization -- JMH 3/9/92
100 * Flag to mark SIGHUP. Whenever the main loop comes around it
101 * will reread the configuration file. (Better than doing the
102 * reading in the signal handler, ey?)
104 static volatile bool got_SIGHUP = false;
107 * Flag to keep track of whether we have started a transaction.
108 * For extended query protocol this has to be remembered across messages.
110 static bool xact_started = false;
113 * Flags to implement skip-till-Sync-after-error behavior for messages of
114 * the extended query protocol.
116 static bool doing_extended_query_message = false;
117 static bool ignore_till_sync = false;
120 * If an unnamed prepared statement exists, it's stored here.
121 * We keep it separate from the hashtable kept by commands/prepare.c
122 * in order to reduce overhead for short-lived queries.
124 static MemoryContext unnamed_stmt_context = NULL;
125 static PreparedStatement *unnamed_stmt_pstmt = NULL;
128 static bool EchoQuery = false; /* default don't echo */
131 * people who want to use EOF should #define DONTUSENEWLINE in
134 #ifndef TCOP_DONTUSENEWLINE
135 static int UseNewLine = 1; /* Use newlines query delimiters (the
138 static int UseNewLine = 0; /* Use EOF as query delimiters */
139 #endif /* TCOP_DONTUSENEWLINE */
142 /* ----------------------------------------------------------------
143 * decls for routines only used in this file
144 * ----------------------------------------------------------------
146 static int InteractiveBackend(StringInfo inBuf);
147 static int SocketBackend(StringInfo inBuf);
148 static int ReadCommand(StringInfo inBuf);
149 static void start_xact_command(void);
150 static void finish_xact_command(bool forceCommit);
151 static void SigHupHandler(SIGNAL_ARGS);
152 static void FloatExceptionHandler(SIGNAL_ARGS);
155 /* ----------------------------------------------------------------
156 * routines to obtain user input
157 * ----------------------------------------------------------------
161 * InteractiveBackend() is called for user interactive connections
163 * the string entered by the user is placed in its parameter inBuf,
164 * and we act like a Q message was received.
166 * EOF is returned if end-of-file input is seen; time to shut down.
171 InteractiveBackend(StringInfo inBuf)
173 int c; /* character read from getc() */
174 bool end = false; /* end-of-input flag */
175 bool backslashSeen = false; /* have we seen a \ ? */
178 * display a prompt and obtain input from the user
183 /* Reset inBuf to empty */
185 inBuf->data[0] = '\0';
193 * if we are using \n as a delimiter, then read characters
196 while ((c = getc(stdin)) != EOF)
202 /* discard backslash from inBuf */
203 inBuf->data[--inBuf->len] = '\0';
204 backslashSeen = false;
209 /* keep the newline character */
210 appendStringInfoChar(inBuf, '\n');
215 backslashSeen = true;
217 backslashSeen = false;
219 appendStringInfoChar(inBuf, (char) c);
228 * otherwise read characters until EOF.
230 while ((c = getc(stdin)) != EOF)
231 appendStringInfoChar(inBuf, (char) c);
241 * otherwise we have a user query so process it.
246 /* Add '\0' to make it look the same as message case. */
247 appendStringInfoChar(inBuf, (char) '\0');
250 * if the query echo flag was given, print the query..
253 printf("statement: %s\n", inBuf->data);
260 * SocketBackend() Is called for frontend-backend connections
262 * Returns the message type code, and loads message body data into inBuf.
264 * EOF is returned if the connection is lost.
268 SocketBackend(StringInfo inBuf)
273 * Get message type code from the frontend.
275 qtype = pq_getbyte();
277 if (qtype == EOF) /* frontend disconnected */
279 elog(COMMERROR, "unexpected EOF on client connection");
284 * Validate message type code before trying to read body; if we have
285 * lost sync, better to say "command unknown" than to run out of memory
286 * because we used garbage as a length word.
288 * This also gives us a place to set the doing_extended_query_message
289 * flag as soon as possible.
293 case 'Q': /* simple query */
294 doing_extended_query_message = false;
295 if (PG_PROTOCOL_MAJOR(FrontendProtocol) < 3)
297 /* old style without length word; convert */
298 if (pq_getstring(inBuf))
300 elog(COMMERROR, "unexpected EOF on client connection");
306 case 'F': /* fastpath function call */
307 /* we let fastpath.c cope with old-style input of this */
308 doing_extended_query_message = false;
311 case 'X': /* terminate */
312 doing_extended_query_message = false;
316 case 'C': /* close */
317 case 'D': /* describe */
318 case 'E': /* execute */
319 case 'H': /* flush */
320 case 'P': /* parse */
321 doing_extended_query_message = true;
322 /* these are only legal in protocol 3 */
323 if (PG_PROTOCOL_MAJOR(FrontendProtocol) < 3)
324 elog(FATAL, "Socket command type %c unknown", qtype);
328 /* stop any active skip-till-Sync */
329 ignore_till_sync = false;
330 /* mark not-extended, so that a new error doesn't begin skip */
331 doing_extended_query_message = false;
332 /* only legal in protocol 3 */
333 if (PG_PROTOCOL_MAJOR(FrontendProtocol) < 3)
334 elog(FATAL, "Socket command type %c unknown", qtype);
337 case 'd': /* copy data */
338 case 'c': /* copy done */
339 case 'f': /* copy fail */
340 doing_extended_query_message = false;
341 /* these are only legal in protocol 3 */
342 if (PG_PROTOCOL_MAJOR(FrontendProtocol) < 3)
343 elog(FATAL, "Socket command type %c unknown", qtype);
348 * Otherwise we got garbage from the frontend. We treat this
349 * as fatal because we have probably lost message boundary sync,
350 * and there's no good way to recover.
352 elog(FATAL, "Socket command type %c unknown", qtype);
357 * In protocol version 3, all frontend messages have a length word
358 * next after the type code; we can read the message contents
359 * independently of the type.
361 if (PG_PROTOCOL_MAJOR(FrontendProtocol) >= 3)
363 if (pq_getmessage(inBuf, 0))
364 return EOF; /* suitable message already logged */
371 * ReadCommand reads a command from either the frontend or
372 * standard input, places it in inBuf, and returns the
373 * message type code (first byte of the message).
374 * EOF is returned if end of file.
378 ReadCommand(StringInfo inBuf)
382 if (IsUnderPostmaster)
383 result = SocketBackend(inBuf);
385 result = InteractiveBackend(inBuf);
391 * Parse a query string and pass it through the rewriter.
393 * A list of Query nodes is returned, since the string might contain
394 * multiple queries and/or the rewriter might expand one query to several.
396 * NOTE: this routine is no longer used for processing interactive queries,
397 * but it is still needed for parsing of SQL function bodies.
400 pg_parse_and_rewrite(const char *query_string, /* string to execute */
401 Oid *paramTypes, /* parameter types */
402 int numParams) /* number of parameters */
404 List *raw_parsetree_list;
405 List *querytree_list;
409 * (1) parse the request string into a list of raw parse trees.
411 raw_parsetree_list = pg_parse_query(query_string);
414 * (2) Do parse analysis and rule rewrite.
416 querytree_list = NIL;
417 foreach(list_item, raw_parsetree_list)
419 Node *parsetree = (Node *) lfirst(list_item);
421 querytree_list = nconc(querytree_list,
422 pg_analyze_and_rewrite(parsetree,
427 return querytree_list;
431 * Do raw parsing (only).
433 * A list of parsetrees is returned, since there might be multiple
434 * commands in the given string.
436 * NOTE: for interactive queries, it is important to keep this routine
437 * separate from the analysis & rewrite stages. Analysis and rewriting
438 * cannot be done in an aborted transaction, since they require access to
439 * database tables. So, we rely on the raw parser to determine whether
440 * we've seen a COMMIT or ABORT command; when we are in abort state, other
441 * commands are not processed any further than the raw parse stage.
444 pg_parse_query(const char *query_string)
446 List *raw_parsetree_list;
449 elog(LOG, "query: %s", query_string);
451 if (log_parser_stats)
454 raw_parsetree_list = raw_parser(query_string);
456 if (log_parser_stats)
457 ShowUsage("PARSER STATISTICS");
459 return raw_parsetree_list;
463 * Given a raw parsetree (gram.y output), and optionally information about
464 * types of parameter symbols ($n), perform parse analysis and rule rewriting.
466 * A list of Query nodes is returned, since either the analyzer or the
467 * rewriter might expand one query to several.
469 * NOTE: for reasons mentioned above, this must be separate from raw parsing.
472 pg_analyze_and_rewrite(Node *parsetree, Oid *paramTypes, int numParams)
474 List *querytree_list;
477 * (1) Perform parse analysis.
479 if (log_parser_stats)
482 querytree_list = parse_analyze(parsetree, paramTypes, numParams);
484 if (log_parser_stats)
485 ShowUsage("PARSE ANALYSIS STATISTICS");
488 * (2) Rewrite the queries, as necessary
490 querytree_list = pg_rewrite_queries(querytree_list);
492 return querytree_list;
496 * Perform rewriting of a list of queries produced by parse analysis.
499 pg_rewrite_queries(List *querytree_list)
501 List *new_list = NIL;
504 if (log_parser_stats)
508 * rewritten queries are collected in new_list. Note there may be more
509 * or fewer than in the original list.
511 foreach(list_item, querytree_list)
513 Query *querytree = (Query *) lfirst(list_item);
515 if (Debug_print_parse)
516 elog_node_display(LOG, "parse tree", querytree,
519 if (querytree->commandType == CMD_UTILITY)
521 /* don't rewrite utilities, just dump 'em into new_list */
522 new_list = lappend(new_list, querytree);
526 /* rewrite regular queries */
527 List *rewritten = QueryRewrite(querytree);
529 new_list = nconc(new_list, rewritten);
533 querytree_list = new_list;
535 if (log_parser_stats)
536 ShowUsage("REWRITER STATISTICS");
538 #ifdef COPY_PARSE_PLAN_TREES
541 * Optional debugging check: pass querytree output through
544 new_list = (List *) copyObject(querytree_list);
545 /* This checks both copyObject() and the equal() routines... */
546 if (!equal(new_list, querytree_list))
547 elog(WARNING, "pg_rewrite_queries: copyObject failed on parse tree");
549 querytree_list = new_list;
552 if (Debug_print_rewritten)
553 elog_node_display(LOG, "rewritten parse tree", querytree_list,
556 return querytree_list;
560 /* Generate a plan for a single already-rewritten query. */
562 pg_plan_query(Query *querytree)
566 /* Utility commands have no plans. */
567 if (querytree->commandType == CMD_UTILITY)
570 if (log_planner_stats)
573 /* call the optimizer */
574 plan = planner(querytree, false, 0);
576 if (log_planner_stats)
577 ShowUsage("PLANNER STATISTICS");
579 #ifdef COPY_PARSE_PLAN_TREES
580 /* Optional debugging check: pass plan output through copyObject() */
582 Plan *new_plan = (Plan *) copyObject(plan);
585 * equal() currently does not have routines to compare Plan nodes,
586 * so don't try to test equality here. Perhaps fix someday?
589 /* This checks both copyObject() and the equal() routines... */
590 if (!equal(new_plan, plan))
591 elog(WARNING, "pg_plan_query: copyObject failed on plan tree");
599 * Print plan if debugging.
601 if (Debug_print_plan)
602 elog_node_display(LOG, "plan", plan, Debug_pretty_print);
608 * Generate plans for a list of already-rewritten queries.
610 * If needSnapshot is TRUE, we haven't yet set a snapshot for the current
611 * query. A snapshot must be set before invoking the planner, since it
612 * might try to evaluate user-defined functions. But we must not set a
613 * snapshot if the list contains only utility statements, because some
614 * utility statements depend on not having frozen the snapshot yet.
615 * (We assume that such statements cannot appear together with plannable
616 * statements in the rewriter's output.)
619 pg_plan_queries(List *querytrees, bool needSnapshot)
621 List *plan_list = NIL;
624 foreach(query_list, querytrees)
626 Query *query = (Query *) lfirst(query_list);
629 if (query->commandType == CMD_UTILITY)
631 /* Utility commands have no plans. */
639 needSnapshot = false;
641 plan = pg_plan_query(query);
644 plan_list = lappend(plan_list, plan);
654 * Execute a "simple Query" protocol message.
657 exec_simple_query(const char *query_string)
659 MemoryContext oldcontext;
660 List *parsetree_list,
662 struct timeval start_t,
664 bool save_log_duration = log_duration;
665 bool save_log_statement_stats = log_statement_stats;
668 * Report query to various monitoring facilities.
670 debug_query_string = query_string;
672 pgstat_report_activity(query_string);
675 * We use save_log_duration so "SET log_duration = true" doesn't
676 * report incorrect time because gettimeofday() wasn't called.
677 * Similarly, log_statement_stats has to be captured once.
679 if (save_log_duration)
680 gettimeofday(&start_t, NULL);
682 if (save_log_statement_stats)
686 * Start up a transaction command. All queries generated by the
687 * query_string will be in this same command block, *unless* we find a
688 * BEGIN/COMMIT/ABORT statement; we have to force a new xact command
689 * after one of those, else bad things will happen in xact.c. (Note
690 * that this will normally change current memory context.)
692 start_xact_command();
695 * Zap any pre-existing unnamed statement. (While not strictly
696 * necessary, it seems best to define simple-Query mode as if it
697 * used the unnamed statement and portal; this ensures we recover
698 * any storage used by prior unnamed operations.)
700 unnamed_stmt_pstmt = NULL;
701 if (unnamed_stmt_context)
703 DropDependentPortals(unnamed_stmt_context);
704 MemoryContextDelete(unnamed_stmt_context);
706 unnamed_stmt_context = NULL;
709 * Switch to appropriate context for constructing parsetrees.
711 oldcontext = MemoryContextSwitchTo(MessageContext);
713 QueryContext = CurrentMemoryContext;
716 * Do basic parsing of the query or queries (this should be safe even
717 * if we are in aborted transaction state!)
719 parsetree_list = pg_parse_query(query_string);
722 * Switch back to transaction context to enter the loop.
724 MemoryContextSwitchTo(oldcontext);
727 * Run through the raw parsetree(s) and process each one.
729 foreach(parsetree_item, parsetree_list)
731 Node *parsetree = (Node *) lfirst(parsetree_item);
732 const char *commandTag;
733 char completionTag[COMPLETION_TAG_BUFSIZE];
734 List *querytree_list,
739 * Get the command name for use in status display (it also becomes the
740 * default completion tag, down inside PortalRun). Set ps_status and
741 * do any special start-of-SQL-command processing needed by the
744 commandTag = CreateCommandTag(parsetree);
746 set_ps_display(commandTag);
748 BeginCommand(commandTag, whereToSendOutput);
751 * If we are in an aborted transaction, reject all commands except
752 * COMMIT/ABORT. It is important that this test occur before we
753 * try to do parse analysis, rewrite, or planning, since all those
754 * phases try to do database accesses, which may fail in abort
755 * state. (It might be safe to allow some additional utility
756 * commands in this state, but not many...)
758 if (IsAbortedTransactionBlockState())
760 bool allowit = false;
762 if (IsA(parsetree, TransactionStmt))
764 TransactionStmt *stmt = (TransactionStmt *) parsetree;
766 if (stmt->kind == TRANS_STMT_COMMIT ||
767 stmt->kind == TRANS_STMT_ROLLBACK)
772 elog(ERROR, "current transaction is aborted, "
773 "queries ignored until end of transaction block");
776 /* Make sure we are in a transaction command */
777 start_xact_command();
779 /* If we got a cancel signal in parsing or prior command, quit */
780 CHECK_FOR_INTERRUPTS();
783 * OK to analyze, rewrite, and plan this query.
785 * Switch to appropriate context for constructing querytrees (again,
786 * these must outlive the execution context).
788 oldcontext = MemoryContextSwitchTo(MessageContext);
790 querytree_list = pg_analyze_and_rewrite(parsetree, NULL, 0);
792 plantree_list = pg_plan_queries(querytree_list, true);
794 /* If we got a cancel signal in analysis or planning, quit */
795 CHECK_FOR_INTERRUPTS();
798 * Switch back to transaction context for execution.
800 MemoryContextSwitchTo(oldcontext);
803 * Create unnamed portal to run the query or queries in.
804 * If there already is one, silently drop it.
806 portal = CreatePortal("", true, true);
808 PortalDefineQuery(portal,
816 * Run the portal to completion, and then drop it.
818 PortalStart(portal, NULL);
820 (void) PortalRun(portal,
826 PortalDrop(portal, false);
829 if (IsA(parsetree, TransactionStmt) ||
830 IsA(parsetree, VariableSetStmt) ||
831 IsA(parsetree, VariableShowStmt) ||
832 IsA(parsetree, VariableResetStmt))
835 * If this was a transaction control statement or a variable
836 * set/show/reset statement, commit it. We will start a
837 * new xact command for the next command (if any).
839 finish_xact_command(true);
841 else if (lnext(parsetree_item) == NIL || !autocommit)
844 * If this is the last parsetree of the query string, close down
845 * transaction statement before reporting command-complete. This
846 * is so that any end-of-transaction errors are reported before
847 * the command-complete message is issued, to avoid confusing
848 * clients who will expect either a command-complete message or an
849 * error, not one and then the other. But for compatibility with
850 * historical Postgres behavior, we do not force a transaction
851 * boundary between queries appearing in a single query string.
853 finish_xact_command(false);
858 * We need a CommandCounterIncrement after every query,
859 * except those that start or end a transaction block.
861 CommandCounterIncrement();
865 * Tell client that we're done with this query. Note we emit
866 * exactly one EndCommand report for each raw parsetree, thus one
867 * for each SQL command the client sent, regardless of rewriting.
868 * (But a command aborted by error will not send an EndCommand
871 EndCommand(completionTag, whereToSendOutput);
872 } /* end loop over parsetrees */
875 * If there were no parsetrees, return EmptyQueryResponse message.
878 NullCommand(whereToSendOutput);
883 * Close down transaction statement, if one is open.
885 finish_xact_command(false);
888 * Finish up monitoring.
890 if (save_log_duration)
892 gettimeofday(&stop_t, NULL);
893 if (stop_t.tv_usec < start_t.tv_usec)
896 stop_t.tv_usec += 1000000;
898 elog(LOG, "duration: %ld.%06ld sec",
899 (long) (stop_t.tv_sec - start_t.tv_sec),
900 (long) (stop_t.tv_usec - start_t.tv_usec));
903 if (save_log_statement_stats)
904 ShowUsage("QUERY STATISTICS");
906 debug_query_string = NULL;
912 * Execute a "Parse" protocol message.
915 exec_parse_message(const char *query_string, /* string to execute */
916 const char *stmt_name, /* name for prepared stmt */
917 Oid *paramTypes, /* parameter types */
918 int numParams) /* number of parameters */
920 MemoryContext oldcontext;
921 List *parsetree_list;
922 const char *commandTag;
923 List *querytree_list,
927 bool save_log_statement_stats = log_statement_stats;
930 * Report query to various monitoring facilities.
932 debug_query_string = query_string;
934 pgstat_report_activity(query_string);
936 set_ps_display("PARSE");
938 if (save_log_statement_stats)
942 * Start up a transaction command so we can run parse analysis etc.
943 * (Note that this will normally change current memory context.)
944 * Nothing happens if we are already in one.
946 start_xact_command();
949 * Switch to appropriate context for constructing parsetrees.
951 * We have two strategies depending on whether the prepared statement
952 * is named or not. For a named prepared statement, we do parsing
953 * in MessageContext and copy the finished trees into the prepared
954 * statement's private context; then the reset of MessageContext releases
955 * temporary space used by parsing and planning. For an unnamed prepared
956 * statement, we assume the statement isn't going to hang around long,
957 * so getting rid of temp space quickly is probably not worth the costs
958 * of copying parse/plan trees. So in this case, we set up a special
959 * context for the unnamed statement, and do all the parsing/planning
962 is_named = (stmt_name[0] != '\0');
965 /* Named prepared statement --- parse in MessageContext */
966 oldcontext = MemoryContextSwitchTo(MessageContext);
970 /* Unnamed prepared statement --- release any prior unnamed stmt */
971 unnamed_stmt_pstmt = NULL;
972 if (unnamed_stmt_context)
974 DropDependentPortals(unnamed_stmt_context);
975 MemoryContextDelete(unnamed_stmt_context);
977 unnamed_stmt_context = NULL;
978 /* create context for parsing/planning */
979 unnamed_stmt_context =
980 AllocSetContextCreate(TopMemoryContext,
981 "unnamed prepared statement",
982 ALLOCSET_DEFAULT_MINSIZE,
983 ALLOCSET_DEFAULT_INITSIZE,
984 ALLOCSET_DEFAULT_MAXSIZE);
985 oldcontext = MemoryContextSwitchTo(unnamed_stmt_context);
988 QueryContext = CurrentMemoryContext;
991 * Do basic parsing of the query or queries (this should be safe even
992 * if we are in aborted transaction state!)
994 parsetree_list = pg_parse_query(query_string);
997 * We only allow a single user statement in a prepared statement.
998 * This is mainly to keep the protocol simple --- otherwise we'd need
999 * to worry about multiple result tupdescs and things like that.
1001 if (length(parsetree_list) > 1)
1002 elog(ERROR, "Cannot insert multiple commands into a prepared statement");
1004 if (parsetree_list != NIL)
1006 Node *parsetree = (Node *) lfirst(parsetree_list);
1010 * Get the command name for possible use in status display.
1012 commandTag = CreateCommandTag(parsetree);
1015 * If we are in an aborted transaction, reject all commands except
1016 * COMMIT/ROLLBACK. It is important that this test occur before we
1017 * try to do parse analysis, rewrite, or planning, since all those
1018 * phases try to do database accesses, which may fail in abort
1019 * state. (It might be safe to allow some additional utility
1020 * commands in this state, but not many...)
1022 if (IsAbortedTransactionBlockState())
1024 bool allowit = false;
1026 if (IsA(parsetree, TransactionStmt))
1028 TransactionStmt *stmt = (TransactionStmt *) parsetree;
1030 if (stmt->kind == TRANS_STMT_COMMIT ||
1031 stmt->kind == TRANS_STMT_ROLLBACK)
1036 elog(ERROR, "current transaction is aborted, "
1037 "queries ignored until end of transaction block");
1041 * OK to analyze, rewrite, and plan this query. Note that the
1042 * originally specified parameter set is not required to be
1043 * complete, so we have to use parse_analyze_varparams().
1045 if (log_parser_stats)
1048 querytree_list = parse_analyze_varparams(parsetree,
1053 * Check all parameter types got determined, and convert array
1054 * representation to a list for storage.
1057 for (i = 0; i < numParams; i++)
1059 Oid ptype = paramTypes[i];
1061 if (ptype == InvalidOid || ptype == UNKNOWNOID)
1062 elog(ERROR, "Could not determine datatype of parameter $%d",
1064 param_list = lappendo(param_list, ptype);
1067 if (log_parser_stats)
1068 ShowUsage("PARSE ANALYSIS STATISTICS");
1070 querytree_list = pg_rewrite_queries(querytree_list);
1072 plantree_list = pg_plan_queries(querytree_list, true);
1076 /* Empty input string. This is legal. */
1078 querytree_list = NIL;
1079 plantree_list = NIL;
1083 /* If we got a cancel signal in analysis or planning, quit */
1084 CHECK_FOR_INTERRUPTS();
1087 * Store the query as a prepared statement. See above comments.
1091 StorePreparedStatement(stmt_name,
1100 PreparedStatement *pstmt;
1102 pstmt = (PreparedStatement *) palloc0(sizeof(PreparedStatement));
1103 /* query_string needs to be copied into unnamed_stmt_context */
1104 pstmt->query_string = pstrdup(query_string);
1105 /* the rest is there already */
1106 pstmt->commandTag = commandTag;
1107 pstmt->query_list = querytree_list;
1108 pstmt->plan_list = plantree_list;
1109 pstmt->argtype_list = param_list;
1110 pstmt->context = unnamed_stmt_context;
1111 /* Now the unnamed statement is complete and valid */
1112 unnamed_stmt_pstmt = pstmt;
1115 MemoryContextSwitchTo(oldcontext);
1117 QueryContext = NULL;
1120 * We do NOT close the open transaction command here; that only happens
1121 * when the client sends Sync. Instead, do CommandCounterIncrement just
1122 * in case something happened during parse/plan.
1124 CommandCounterIncrement();
1127 * Send ParseComplete.
1129 if (whereToSendOutput == Remote)
1130 pq_putemptymessage('1');
1132 if (save_log_statement_stats)
1133 ShowUsage("PARSE MESSAGE STATISTICS");
1135 debug_query_string = NULL;
1141 * Process a "Bind" message to create a portal from a prepared statement
1144 exec_bind_message(StringInfo input_message)
1146 const char *portal_name;
1147 const char *stmt_name;
1150 PreparedStatement *pstmt;
1152 ParamListInfo params;
1154 pgstat_report_activity("<BIND>");
1156 set_ps_display("BIND");
1159 * Start up a transaction command so we can call functions etc.
1160 * (Note that this will normally change current memory context.)
1161 * Nothing happens if we are already in one.
1163 start_xact_command();
1165 /* Get the fixed part of the message */
1166 portal_name = pq_getmsgstring(input_message);
1167 stmt_name = pq_getmsgstring(input_message);
1168 is_binary = pq_getmsgbyte(input_message);
1169 numParams = pq_getmsgint(input_message, 4);
1172 elog(ERROR, "Binary BIND not implemented yet");
1174 /* Find prepared statement */
1175 if (stmt_name[0] != '\0')
1176 pstmt = FetchPreparedStatement(stmt_name, true);
1179 /* special-case the unnamed statement */
1180 pstmt = unnamed_stmt_pstmt;
1182 elog(ERROR, "Unnamed prepared statement does not exist");
1185 if (numParams != length(pstmt->argtype_list))
1186 elog(ERROR, "Bind message supplies %d parameters, but prepared statement \"%s\" requires %d",
1187 numParams, stmt_name, length(pstmt->argtype_list));
1190 * Create the portal. Allow silent replacement of an existing portal
1191 * only if the unnamed portal is specified.
1193 if (portal_name[0] == '\0')
1194 portal = CreatePortal(portal_name, true, true);
1196 portal = CreatePortal(portal_name, false, false);
1198 PortalDefineQuery(portal,
1199 pstmt->query_string,
1206 * Fetch parameters, if any, and store in the portal's memory context.
1208 * In an aborted transaction, we can't risk calling user-defined functions,
1209 * so bind all parameters to null values.
1213 bool isaborted = IsAbortedTransactionBlockState();
1216 MemoryContext oldContext;
1218 oldContext = MemoryContextSwitchTo(PortalGetHeapMemory(portal));
1220 params = (ParamListInfo)
1221 palloc0((numParams + 1) * sizeof(ParamListInfoData));
1223 foreach(l, pstmt->argtype_list)
1225 Oid ptype = lfirsto(l);
1228 isNull = (pq_getmsgbyte(input_message) != 0) ? false : true;
1231 const char *ptext = pq_getmsgstring(input_message);
1240 getTypeInputInfo(ptype, &typInput, &typElem);
1242 OidFunctionCall3(typInput,
1243 CStringGetDatum(ptext),
1244 ObjectIdGetDatum(typElem),
1248 params[i].kind = PARAM_NUM;
1249 params[i].id = i + 1;
1250 params[i].isnull = isNull;
1255 params[i].kind = PARAM_INVALID;
1257 MemoryContextSwitchTo(oldContext);
1262 pq_getmsgend(input_message);
1265 * Start portal execution.
1267 PortalStart(portal, params);
1270 * Send BindComplete.
1272 if (whereToSendOutput == Remote)
1273 pq_putemptymessage('2');
1277 * exec_execute_message
1279 * Process an "Execute" message for a portal
1282 exec_execute_message(const char *portal_name, int is_binary, long max_rows)
1286 bool is_trans_stmt = false;
1287 bool is_trans_exit = false;
1289 char completionTag[COMPLETION_TAG_BUFSIZE];
1291 /* Adjust destination to tell printtup.c what to do */
1292 dest = whereToSendOutput;
1294 dest = is_binary ? RemoteExecuteInternal : RemoteExecute;
1296 portal = GetPortalByName(portal_name);
1297 if (!PortalIsValid(portal))
1298 elog(ERROR, "Portal \"%s\" not found", portal_name);
1301 * If the original query was a null string, just return EmptyQueryResponse.
1303 if (portal->commandTag == NULL)
1305 Assert(portal->parseTrees == NIL);
1310 if (portal->sourceText)
1312 debug_query_string = portal->sourceText;
1313 pgstat_report_activity(portal->sourceText);
1317 debug_query_string = "execute message";
1318 pgstat_report_activity("<EXECUTE>");
1321 set_ps_display(portal->commandTag);
1323 BeginCommand(portal->commandTag, dest);
1325 /* Check for transaction-control commands */
1326 if (length(portal->parseTrees) == 1)
1328 Query *query = (Query *) lfirst(portal->parseTrees);
1330 if (query->commandType == CMD_UTILITY &&
1331 query->utilityStmt != NULL &&
1332 IsA(query->utilityStmt, TransactionStmt))
1334 TransactionStmt *stmt = (TransactionStmt *) query->utilityStmt;
1336 is_trans_stmt = true;
1337 if (stmt->kind == TRANS_STMT_COMMIT ||
1338 stmt->kind == TRANS_STMT_ROLLBACK)
1339 is_trans_exit = true;
1344 * Ensure we are in a transaction command (this should normally be
1345 * the case already due to prior BIND).
1347 start_xact_command();
1350 * If we are in aborted transaction state, the only portals we can
1351 * actually run are those containing COMMIT or ROLLBACK commands.
1353 if (IsAbortedTransactionBlockState())
1356 elog(ERROR, "current transaction is aborted, "
1357 "queries ignored until end of transaction block");
1360 /* Check for cancel signal before we start execution */
1361 CHECK_FOR_INTERRUPTS();
1364 * Okay to run the portal.
1367 max_rows = FETCH_ALL;
1369 completed = PortalRun(portal,
1380 * If this was a transaction control statement, commit it. We will
1381 * start a new xact command for the next command (if any).
1383 finish_xact_command(true);
1388 * We need a CommandCounterIncrement after every query,
1389 * except those that start or end a transaction block.
1391 CommandCounterIncrement();
1394 /* Send appropriate CommandComplete to client */
1395 EndCommand(completionTag, dest);
1399 /* Portal run not complete, so send PortalSuspended */
1400 if (whereToSendOutput == Remote)
1401 pq_putemptymessage('s');
1404 debug_query_string = NULL;
1408 * exec_describe_statement_message
1410 * Process a "Describe" message for a prepared statement
1413 exec_describe_statement_message(const char *stmt_name)
1415 PreparedStatement *pstmt;
1419 /* Find prepared statement */
1420 if (stmt_name[0] != '\0')
1421 pstmt = FetchPreparedStatement(stmt_name, true);
1424 /* special-case the unnamed statement */
1425 pstmt = unnamed_stmt_pstmt;
1427 elog(ERROR, "Unnamed prepared statement does not exist");
1430 if (whereToSendOutput != Remote)
1431 return; /* can't actually do anything... */
1433 pq_beginmessage(&buf, 't'); /* parameter description message type */
1434 pq_sendint(&buf, length(pstmt->argtype_list), 4);
1436 foreach(l, pstmt->argtype_list)
1438 Oid ptype = lfirsto(l);
1440 pq_sendint(&buf, (int) ptype, 4);
1442 pq_endmessage(&buf);
1446 * exec_describe_portal_message
1448 * Process a "Describe" message for a portal
1451 exec_describe_portal_message(const char *portal_name)
1455 portal = GetPortalByName(portal_name);
1456 if (!PortalIsValid(portal))
1457 elog(ERROR, "Portal \"%s\" not found", portal_name);
1459 if (whereToSendOutput != Remote)
1460 return; /* can't actually do anything... */
1462 if (portal->tupDesc)
1466 if (portal->strategy == PORTAL_ONE_SELECT)
1467 targetlist = ((Plan *) lfirst(portal->planTrees))->targetlist;
1470 SendRowDescriptionMessage(portal->tupDesc, targetlist);
1473 pq_putemptymessage('n'); /* NoData */
1478 * Convenience routines for starting/committing a single command.
1481 start_xact_command(void)
1485 elog(DEBUG2, "StartTransactionCommand");
1486 StartTransactionCommand(false);
1488 /* Set statement timeout running, if any */
1489 if (StatementTimeout > 0)
1490 enable_sig_alarm(StatementTimeout, true);
1492 xact_started = true;
1497 finish_xact_command(bool forceCommit)
1501 /* Invoke IMMEDIATE constraint triggers */
1502 DeferredTriggerEndQuery();
1504 /* Cancel any active statement timeout before committing */
1505 disable_sig_alarm(true);
1507 /* Now commit the command */
1508 elog(DEBUG2, "CommitTransactionCommand");
1510 CommitTransactionCommand(forceCommit);
1512 #ifdef SHOW_MEMORY_STATS
1513 /* Print mem stats at each commit for leak tracking */
1515 MemoryContextStats(TopMemoryContext);
1518 xact_started = false;
1523 /* --------------------------------
1524 * signal handler routines used in PostgresMain()
1525 * --------------------------------
1529 * quickdie() occurs when signalled SIGQUIT by the postmaster.
1531 * Some backend has bought the farm,
1532 * so we need to stop what we're doing and exit.
1535 quickdie(SIGNAL_ARGS)
1537 PG_SETMASK(&BlockSig);
1538 elog(WARNING, "Message from PostgreSQL backend:"
1539 "\n\tThe Postmaster has informed me that some other backend"
1540 "\n\tdied abnormally and possibly corrupted shared memory."
1541 "\n\tI have rolled back the current transaction and am"
1542 "\n\tgoing to terminate your database system connection and exit."
1543 "\n\tPlease reconnect to the database system and repeat your query.");
1546 * DO NOT proc_exit() -- we're here because shared memory may be
1547 * corrupted, so we don't want to try to clean up our transaction.
1548 * Just nail the windows shut and get out of town.
1550 * Note we do exit(1) not exit(0). This is to force the postmaster into
1551 * a system reset cycle if some idiot DBA sends a manual SIGQUIT to a
1552 * random backend. This is necessary precisely because we don't clean
1553 * up our shared memory state.
1560 * Shutdown signal from postmaster: abort transaction and exit
1561 * at soonest convenient time
1566 int save_errno = errno;
1568 /* Don't joggle the elbow of proc_exit */
1569 if (!proc_exit_inprogress)
1571 InterruptPending = true;
1572 ProcDiePending = true;
1575 * If it's safe to interrupt, and we're waiting for input or a
1576 * lock, service the interrupt immediately
1578 if (ImmediateInterruptOK && InterruptHoldoffCount == 0 &&
1579 CritSectionCount == 0)
1581 /* bump holdoff count to make ProcessInterrupts() a no-op */
1582 /* until we are done getting ready for it */
1583 InterruptHoldoffCount++;
1584 DisableNotifyInterrupt();
1585 /* Make sure CheckDeadLock won't run while shutting down... */
1587 InterruptHoldoffCount--;
1588 ProcessInterrupts();
1596 * Timeout or shutdown signal from postmaster during client authentication.
1599 * XXX: possible future improvement: try to send a message indicating
1600 * why we are disconnecting. Problem is to be sure we don't block while
1601 * doing so, nor mess up the authentication message exchange.
1604 authdie(SIGNAL_ARGS)
1610 * Query-cancel signal from postmaster: abort current transaction
1611 * at soonest convenient time
1614 StatementCancelHandler(SIGNAL_ARGS)
1616 int save_errno = errno;
1619 * Don't joggle the elbow of proc_exit, nor an already-in-progress
1622 if (!proc_exit_inprogress && !InError)
1624 InterruptPending = true;
1625 QueryCancelPending = true;
1628 * If it's safe to interrupt, and we're waiting for a lock,
1629 * service the interrupt immediately. No point in interrupting if
1630 * we're waiting for input, however.
1632 if (ImmediateInterruptOK && InterruptHoldoffCount == 0 &&
1633 CritSectionCount == 0)
1635 /* bump holdoff count to make ProcessInterrupts() a no-op */
1636 /* until we are done getting ready for it */
1637 InterruptHoldoffCount++;
1638 if (LockWaitCancel())
1640 DisableNotifyInterrupt();
1641 InterruptHoldoffCount--;
1642 ProcessInterrupts();
1645 InterruptHoldoffCount--;
1652 /* signal handler for floating point exception */
1654 FloatExceptionHandler(SIGNAL_ARGS)
1656 elog(ERROR, "floating point exception!"
1657 " The last floating point operation either exceeded legal ranges"
1658 " or was a divide by zero");
1661 /* SIGHUP: set flag to re-read config file at next convenient time */
1663 SigHupHandler(SIGNAL_ARGS)
1670 * ProcessInterrupts: out-of-line portion of CHECK_FOR_INTERRUPTS() macro
1672 * If an interrupt condition is pending, and it's safe to service it,
1673 * then clear the flag and accept the interrupt. Called only when
1674 * InterruptPending is true.
1677 ProcessInterrupts(void)
1679 /* OK to accept interrupt now? */
1680 if (InterruptHoldoffCount != 0 || CritSectionCount != 0)
1682 InterruptPending = false;
1685 ProcDiePending = false;
1686 QueryCancelPending = false; /* ProcDie trumps QueryCancel */
1687 ImmediateInterruptOK = false; /* not idle anymore */
1688 DisableNotifyInterrupt();
1689 elog(FATAL, "This connection has been terminated by the administrator.");
1691 if (QueryCancelPending)
1693 QueryCancelPending = false;
1694 ImmediateInterruptOK = false; /* not idle anymore */
1695 DisableNotifyInterrupt();
1696 elog(ERROR, "Query was canceled.");
1698 /* If we get here, do nothing (probably, QueryCancelPending was reset) */
1703 usage(char *progname)
1705 printf("%s is the PostgreSQL stand-alone backend. It is not\nintended to be used by normal users.\n\n", progname);
1707 printf("Usage:\n %s [OPTION]... [DBNAME]\n\n", progname);
1708 printf("Options:\n");
1709 #ifdef USE_ASSERT_CHECKING
1710 printf(" -A 1|0 enable/disable run-time assert checking\n");
1712 printf(" -B NBUFFERS number of shared buffers (default %d)\n", DEF_NBUFFERS);
1713 printf(" -c NAME=VALUE set run-time parameter\n");
1714 printf(" -d 0-5 debugging level (0 is off)\n");
1715 printf(" -D DATADIR database directory\n");
1716 printf(" -e use European date format\n");
1717 printf(" -E echo query before execution\n");
1718 printf(" -F turn fsync off\n");
1719 printf(" -N do not use newline as interactive query delimiter\n");
1720 printf(" -o FILENAME send stdout and stderr to given file\n");
1721 printf(" -P disable system indexes\n");
1722 printf(" -s show statistics after each query\n");
1723 printf(" -S SORT-MEM set amount of memory for sorts (in kbytes)\n");
1724 printf(" --help show this help, then exit\n");
1725 printf(" --version output version information, then exit\n");
1726 printf("\nDeveloper options:\n");
1727 printf(" -f s|i|n|m|h forbid use of some plan types\n");
1728 printf(" -i do not execute queries\n");
1729 printf(" -O allow system table structure changes\n");
1730 printf(" -t pa|pl|ex show timings after each query\n");
1731 printf(" -W NUM wait NUM seconds to allow attach from a debugger\n");
1732 printf("\nReport bugs to <pgsql-bugs@postgresql.org>.\n");
1737 /* ----------------------------------------------------------------
1739 * postgres main loop -- all backends, interactive or otherwise start here
1741 * argc/argv are the command line arguments to be used. (When being forked
1742 * by the postmaster, these are not the original argv array of the process.)
1743 * username is the (possibly authenticated) PostgreSQL user name to be used
1745 * ----------------------------------------------------------------
1748 PostgresMain(int argc, char *argv[], const char *username)
1751 const char *DBName = NULL;
1752 char *potential_DataDir = NULL;
1757 GucSource gucsource;
1760 StringInfo input_message;
1764 * Catch standard options before doing much else. This even works on
1765 * systems without getopt_long.
1767 if (!IsUnderPostmaster && argc > 1)
1769 if (strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-?") == 0)
1774 if (strcmp(argv[1], "--version") == 0 || strcmp(argv[1], "-V") == 0)
1776 puts("postgres (PostgreSQL) " PG_VERSION);
1782 * initialize globals (already done if under postmaster, but not if
1783 * standalone; cheap enough to do over)
1786 MyProcPid = getpid();
1789 * Fire up essential subsystems: error and memory management
1791 * If we are running under the postmaster, this is done already.
1793 if (!IsUnderPostmaster)
1794 MemoryContextInit();
1796 set_ps_display("startup");
1798 SetProcessingMode(InitProcessing);
1801 * Set default values for command-line options.
1806 if (!IsUnderPostmaster || ExecBackend)
1808 InitializeGUCOptions();
1810 read_nondefault_variables();
1812 potential_DataDir = getenv("PGDATA");
1816 * parse command line arguments
1818 * There are now two styles of command line layout for the backend:
1820 * For interactive use (not started from postmaster) the format is
1821 * postgres [switches] [databasename]
1822 * If the databasename is omitted it is taken to be the user name.
1824 * When started from the postmaster, the format is
1825 * postgres [secure switches] -p databasename [insecure switches]
1826 * Switches appearing after -p came from the client (via "options"
1827 * field of connection request). For security reasons we restrict
1828 * what these switches can do.
1832 /* all options are allowed until '-p' */
1834 ctx = PGC_POSTMASTER;
1835 gucsource = PGC_S_ARGV; /* initial switches came from command line */
1837 while ((flag = getopt(argc, argv, "A:B:c:CD:d:Eef:FiNOPo:p:S:st:v:W:x:-:")) != -1)
1841 #ifdef USE_ASSERT_CHECKING
1842 SetConfigOption("debug_assertions", optarg, ctx, gucsource);
1844 elog(WARNING, "Assert checking is not compiled in");
1851 * specify the size of buffer pool
1853 SetConfigOption("shared_buffers", optarg, ctx, gucsource);
1859 * don't print version string
1864 case 'D': /* PGDATA directory */
1866 potential_DataDir = optarg;
1869 case 'd': /* debug level */
1871 debug_flag = atoi(optarg);
1872 /* Set server debugging level. */
1873 if (atoi(optarg) != 0)
1875 char *debugstr = palloc(strlen("debug") + strlen(optarg) + 1);
1877 sprintf(debugstr, "debug%s", optarg);
1878 SetConfigOption("log_min_messages", debugstr, ctx, gucsource);
1884 * -d0 allows user to prevent postmaster debug
1885 * from propagating to backend. It would be nice
1886 * to set it to the postgresql.conf value here.
1888 SetConfigOption("log_min_messages", "notice",
1896 * E - echo the query the user entered
1904 * Use european date formats.
1906 SetConfigOption("datestyle", "euro", ctx, gucsource);
1914 SetConfigOption("fsync", "false", ctx, gucsource);
1920 * f - forbid generation of certain plans
1925 case 's': /* seqscan */
1926 tmp = "enable_seqscan";
1928 case 'i': /* indexscan */
1929 tmp = "enable_indexscan";
1931 case 't': /* tidscan */
1932 tmp = "enable_tidscan";
1934 case 'n': /* nestloop */
1935 tmp = "enable_nestloop";
1937 case 'm': /* mergejoin */
1938 tmp = "enable_mergejoin";
1940 case 'h': /* hashjoin */
1941 tmp = "enable_hashjoin";
1947 SetConfigOption(tmp, "false", ctx, gucsource);
1953 * N - Don't use newline as a query delimiter
1961 * allow system table structure modifications
1963 if (secure) /* XXX safe to allow from client??? */
1964 allowSystemTableMods = true;
1970 * ignore system indexes
1972 if (secure) /* XXX safe to allow from client??? */
1973 IgnoreSystemIndexes(true);
1979 * o - send output (stdout and stderr) to the given file
1982 StrNCpy(OutputFileName, optarg, MAXPGPATH);
1988 * p - special flag passed if backend was forked by a
1993 DBName = strdup(optarg);
1994 secure = false; /* subsequent switches are NOT
1997 gucsource = PGC_S_CLIENT;
2004 * S - amount of sort memory to use in 1k bytes
2006 SetConfigOption("sort_mem", optarg, ctx, gucsource);
2012 * s - report usage statistics (timings) after each query
2014 SetConfigOption("show_statement_stats", "true", ctx, gucsource);
2019 * tell postgres to report usage statistics (timings) for
2022 * -tpa[rser] = print stats for parser time of each query
2023 * -tpl[anner] = print stats for planner time of each query
2024 * -te[xecutor] = print stats for executor time of each query
2025 * caution: -s can not be used together with -t.
2032 if (optarg[1] == 'a')
2033 tmp = "log_parser_stats";
2034 else if (optarg[1] == 'l')
2035 tmp = "log_planner_stats";
2040 tmp = "show_executor_stats";
2047 SetConfigOption(tmp, "true", ctx, gucsource);
2052 FrontendProtocol = (ProtocolVersion) atoi(optarg);
2058 * wait N seconds to allow attach from a debugger
2060 sleep(atoi(optarg));
2064 #ifdef NOT_USED /* planner/xfunc.h */
2067 * control joey hellerstein's expensive function
2072 elog(WARNING, "only one -x flag is allowed");
2076 if (strcmp(optarg, "off") == 0)
2077 XfuncMode = XFUNC_OFF;
2078 else if (strcmp(optarg, "nor") == 0)
2079 XfuncMode = XFUNC_NOR;
2080 else if (strcmp(optarg, "nopull") == 0)
2081 XfuncMode = XFUNC_NOPULL;
2082 else if (strcmp(optarg, "nopm") == 0)
2083 XfuncMode = XFUNC_NOPM;
2084 else if (strcmp(optarg, "pullall") == 0)
2085 XfuncMode = XFUNC_PULLALL;
2086 else if (strcmp(optarg, "wait") == 0)
2087 XfuncMode = XFUNC_WAIT;
2090 elog(WARNING, "use -x {off,nor,nopull,nopm,pullall,wait}");
2102 ParseLongOption(optarg, &name, &value);
2106 elog(ERROR, "--%s requires argument", optarg);
2108 elog(ERROR, "-c %s requires argument", optarg);
2111 SetConfigOption(name, value, ctx, gucsource);
2125 * -d is not the same as setting
2126 * log_min_messages because it enables other
2129 if (debug_flag >= 1)
2130 SetConfigOption("log_connections", "true", ctx, gucsource);
2131 if (debug_flag >= 2)
2132 SetConfigOption("log_statement", "true", ctx, gucsource);
2133 if (debug_flag >= 3)
2134 SetConfigOption("debug_print_parse", "true", ctx, gucsource);
2135 if (debug_flag >= 4)
2136 SetConfigOption("debug_print_plan", "true", ctx, gucsource);
2137 if (debug_flag >= 5)
2138 SetConfigOption("debug_print_rewritten", "true", ctx, gucsource);
2141 * Process any additional GUC variable settings passed in startup packet.
2143 if (MyProcPort != NULL)
2145 List *gucopts = MyProcPort->guc_options;
2152 name = lfirst(gucopts);
2153 gucopts = lnext(gucopts);
2154 value = lfirst(gucopts);
2155 gucopts = lnext(gucopts);
2156 SetConfigOption(name, value, PGC_BACKEND, PGC_S_CLIENT);
2161 * Post-processing for command line options.
2163 if (log_statement_stats &&
2164 (log_parser_stats || log_planner_stats || log_executor_stats))
2166 elog(WARNING, "Query statistics are disabled because parser, planner, or executor statistics are on.");
2167 SetConfigOption("show_statement_stats", "false", ctx, gucsource);
2170 if (!IsUnderPostmaster)
2172 if (!potential_DataDir)
2174 fprintf(stderr, "%s does not know where to find the database system "
2175 "data. You must specify the directory that contains the "
2176 "database system either by specifying the -D invocation "
2177 "option or by setting the PGDATA environment variable.\n\n",
2181 SetDataDir(potential_DataDir);
2186 * Set up signal handlers and masks.
2188 * Note that postmaster blocked all signals before forking child process,
2189 * so there is no race condition whereby we might receive a signal
2190 * before we have set up the handler.
2192 * Also note: it's best not to use any signals that are SIG_IGNored in
2193 * the postmaster. If such a signal arrives before we are able to
2194 * change the handler to non-SIG_IGN, it'll get dropped. Instead,
2195 * make a dummy handler in the postmaster to reserve the signal. (Of
2196 * course, this isn't an issue for signals that are locally generated,
2197 * such as SIGALRM and SIGPIPE.)
2200 pqsignal(SIGHUP, SigHupHandler); /* set flag to read config file */
2201 pqsignal(SIGINT, StatementCancelHandler); /* cancel current query */
2202 pqsignal(SIGTERM, die); /* cancel current query and exit */
2203 pqsignal(SIGQUIT, quickdie); /* hard crash time */
2204 pqsignal(SIGALRM, handle_sig_alarm); /* timeout conditions */
2207 * Ignore failure to write to frontend. Note: if frontend closes
2208 * connection, we will notice it and exit cleanly when control next
2209 * returns to outer loop. This seems safer than forcing exit in the
2210 * midst of output during who-knows-what operation...
2212 pqsignal(SIGPIPE, SIG_IGN);
2213 pqsignal(SIGUSR1, SIG_IGN); /* this signal available for use */
2215 pqsignal(SIGUSR2, Async_NotifyHandler); /* flush also sinval cache */
2216 pqsignal(SIGFPE, FloatExceptionHandler);
2219 * Reset some signals that are accepted by postmaster but not by
2222 pqsignal(SIGCHLD, SIG_DFL); /* system() requires this on some
2227 /* We allow SIGQUIT (quickdie) at all times */
2228 #ifdef HAVE_SIGPROCMASK
2229 sigdelset(&BlockSig, SIGQUIT);
2231 BlockSig &= ~(sigmask(SIGQUIT));
2234 PG_SETMASK(&BlockSig); /* block everything except SIGQUIT */
2237 if (IsUnderPostmaster)
2239 /* noninteractive case: nothing should be left after switches */
2240 if (errs || argc != optind || DBName == NULL)
2242 elog(WARNING, "%s: invalid command line arguments\nTry -? for help.",
2244 proc_exit(0); /* not 1, that causes system-wide
2249 AttachSharedMemoryAndSemaphores();
2254 /* interactive case: database name can be last arg on command line */
2255 if (errs || argc - optind > 1)
2257 elog(WARNING, "%s: invalid command line arguments\nTry -? for help.",
2261 else if (argc - optind == 1)
2262 DBName = argv[optind];
2263 else if ((DBName = username) == NULL)
2265 elog(WARNING, "%s: user name undefined and no database specified",
2271 * On some systems our dynloader code needs the executable's
2272 * pathname. (If under postmaster, this was done already.)
2274 if (FindExec(pg_pathname, argv[0], "postgres") < 0)
2275 elog(FATAL, "%s: could not locate executable, bailing out...",
2279 * Validate we have been given a reasonable-looking DataDir (if
2280 * under postmaster, assume postmaster did this already).
2282 ValidatePgVersion(DataDir);
2285 * Create lockfile for data directory.
2287 if (!CreateDataDirLockFile(DataDir, false))
2294 * Start up xlog for standalone backend, and register to have it
2295 * closed down at exit.
2298 on_shmem_exit(ShutdownXLOG, 0);
2301 * Read any existing FSM cache file, and register to write one out
2305 on_shmem_exit(DumpFreeSpaceMap, 0);
2309 * Set up additional info.
2317 * General initialization.
2319 * NOTE: if you are tempted to add code in this vicinity, consider
2320 * putting it inside InitPostgres() instead. In particular, anything
2321 * that involves database access should be there, not here.
2323 elog(DEBUG2, "InitPostgres");
2324 InitPostgres(DBName, username);
2326 SetProcessingMode(NormalProcessing);
2329 * Send this backend's cancellation info to the frontend.
2331 if (whereToSendOutput == Remote &&
2332 PG_PROTOCOL_MAJOR(FrontendProtocol) >= 2)
2336 pq_beginmessage(&buf, 'K');
2337 pq_sendint(&buf, (int32) MyProcPid, sizeof(int32));
2338 pq_sendint(&buf, (int32) MyCancelKey, sizeof(int32));
2339 pq_endmessage(&buf);
2340 /* Need not flush since ReadyForQuery will do it. */
2343 if (!IsUnderPostmaster)
2345 puts("\nPOSTGRES backend interactive interface ");
2346 puts("$Revision: 1.333 $ $Date: 2003/05/06 00:20:33 $\n");
2350 * Create the memory context we will use in the main loop.
2352 * MessageContext is reset once per iteration of the main loop, ie, upon
2353 * completion of processing of each command message from the client.
2355 MessageContext = AllocSetContextCreate(TopMemoryContext,
2357 ALLOCSET_DEFAULT_MINSIZE,
2358 ALLOCSET_DEFAULT_INITSIZE,
2359 ALLOCSET_DEFAULT_MAXSIZE);
2362 * Tell the statistics collector that we're alive and
2363 * to which database we belong.
2369 * POSTGRES main processing loop begins here
2371 * If an exception is encountered, processing resumes here so we abort
2372 * the current transaction and start a new one.
2375 if (sigsetjmp(Warn_restart, 1) != 0)
2378 * NOTE: if you are tempted to add more code in this if-block,
2379 * consider the probability that it should be in
2380 * AbortTransaction() instead.
2382 * Make sure we're not interrupted while cleaning up. Also forget
2383 * any pending QueryCancel request, since we're aborting anyway.
2384 * Force InterruptHoldoffCount to a known state in case we elog'd
2385 * from inside a holdoff section.
2387 ImmediateInterruptOK = false;
2388 QueryCancelPending = false;
2389 InterruptHoldoffCount = 1;
2390 CritSectionCount = 0; /* should be unnecessary, but... */
2391 disable_sig_alarm(true);
2392 QueryCancelPending = false; /* again in case timeout occurred */
2393 DisableNotifyInterrupt();
2394 debug_query_string = NULL;
2397 * Make sure we are in a valid memory context during recovery.
2399 * We use ErrorContext in hopes that it will have some free space
2400 * even if we're otherwise up against it...
2402 MemoryContextSwitchTo(ErrorContext);
2404 /* Do the recovery */
2405 elog(DEBUG1, "AbortCurrentTransaction");
2406 AbortCurrentTransaction();
2409 * Now return to normal top-level context and clear ErrorContext
2412 MemoryContextSwitchTo(TopMemoryContext);
2413 MemoryContextResetAndDeleteChildren(ErrorContext);
2414 CurrentPortal = NULL;
2415 PortalContext = NULL;
2416 QueryContext = NULL;
2419 * Clear flag to indicate that we got out of error recovery mode
2420 * successfully. (Flag was set in elog.c before longjmp().)
2423 xact_started = false;
2426 * If we were handling an extended-query-protocol message,
2427 * initiate skip till next Sync.
2429 if (doing_extended_query_message)
2430 ignore_till_sync = true;
2433 * Exit interrupt holdoff section we implicitly established above.
2435 RESUME_INTERRUPTS();
2438 Warn_restart_ready = true; /* we can now handle elog(ERROR) */
2440 PG_SETMASK(&UnBlockSig);
2442 send_rfq = true; /* initially, or after error */
2445 * Non-error queries loop here.
2451 * At top of loop, reset extended-query-message flag, so that
2452 * any errors encountered in "idle" state don't provoke skip.
2454 doing_extended_query_message = false;
2457 * Release storage left over from prior query cycle, and create a
2458 * new query input buffer in the cleared MessageContext.
2460 MemoryContextSwitchTo(MessageContext);
2461 MemoryContextResetAndDeleteChildren(MessageContext);
2463 input_message = makeStringInfo();
2466 * (1) tell the frontend we're ready for a new query.
2468 * Note: this includes fflush()'ing the last of the prior output.
2472 ReadyForQuery(whereToSendOutput);
2477 * Tell the statistics collector what we've collected
2481 pgstat_report_tabstat();
2483 if (IsTransactionBlock())
2485 set_ps_display("idle in transaction");
2486 pgstat_report_activity("<IDLE> in transaction");
2490 set_ps_display("idle");
2491 pgstat_report_activity("<IDLE>");
2495 * (2) deal with pending asynchronous NOTIFY from other backends,
2496 * and enable async.c's signal handler to execute NOTIFY directly.
2497 * Then set up other stuff needed before blocking for input.
2499 QueryCancelPending = false; /* forget any earlier CANCEL
2502 EnableNotifyInterrupt();
2504 /* Allow "die" interrupt to be processed while waiting */
2505 ImmediateInterruptOK = true;
2506 /* and don't forget to detect one that already arrived */
2507 QueryCancelPending = false;
2508 CHECK_FOR_INTERRUPTS();
2511 * (3) read a command (loop blocks here)
2513 firstchar = ReadCommand(input_message);
2516 * (4) disable async signal conditions again.
2518 ImmediateInterruptOK = false;
2519 QueryCancelPending = false; /* forget any CANCEL signal */
2521 DisableNotifyInterrupt();
2524 * (5) check for any other interesting events that happened while
2530 ProcessConfigFile(PGC_SIGHUP);
2534 * (6) process the command. But ignore it if we're skipping till Sync.
2536 if (ignore_till_sync)
2541 case 'Q': /* simple query */
2543 const char *query_string;
2545 query_string = pq_getmsgstring(input_message);
2546 pq_getmsgend(input_message);
2548 exec_simple_query(query_string);
2554 case 'P': /* parse */
2556 const char *stmt_name;
2557 const char *query_string;
2559 Oid *paramTypes = NULL;
2561 stmt_name = pq_getmsgstring(input_message);
2562 query_string = pq_getmsgstring(input_message);
2563 numParams = pq_getmsgint(input_message, 4);
2568 paramTypes = (Oid *) palloc(numParams * sizeof(Oid));
2569 for (i = 0; i < numParams; i++)
2570 paramTypes[i] = pq_getmsgint(input_message, 4);
2572 pq_getmsgend(input_message);
2574 exec_parse_message(query_string, stmt_name,
2575 paramTypes, numParams);
2579 case 'B': /* bind */
2581 * this message is complex enough that it seems best to put
2582 * the field extraction out-of-line
2584 exec_bind_message(input_message);
2587 case 'E': /* execute */
2589 const char *portal_name;
2593 portal_name = pq_getmsgstring(input_message);
2594 is_binary = pq_getmsgbyte(input_message);
2595 max_rows = pq_getmsgint(input_message, 4);
2596 pq_getmsgend(input_message);
2598 exec_execute_message(portal_name, is_binary, max_rows);
2602 case 'F': /* fastpath function call */
2603 /* Tell the collector what we're doing */
2604 pgstat_report_activity("<FASTPATH> function call");
2606 /* start an xact for this function invocation */
2607 start_xact_command();
2609 if (HandleFunctionRequest(input_message) == EOF)
2611 /* lost frontend connection during F message input */
2614 * Reset whereToSendOutput to prevent elog from
2615 * attempting to send any more messages to client.
2617 if (whereToSendOutput == Remote)
2618 whereToSendOutput = None;
2623 /* commit the function-invocation transaction */
2624 finish_xact_command(false);
2629 case 'C': /* close */
2632 const char *close_target;
2634 close_type = pq_getmsgbyte(input_message);
2635 close_target = pq_getmsgstring(input_message);
2636 pq_getmsgend(input_message);
2641 if (close_target[0] != '\0')
2642 DropPreparedStatement(close_target, false);
2645 /* special-case the unnamed statement */
2646 unnamed_stmt_pstmt = NULL;
2647 if (unnamed_stmt_context)
2649 DropDependentPortals(unnamed_stmt_context);
2650 MemoryContextDelete(unnamed_stmt_context);
2652 unnamed_stmt_context = NULL;
2659 portal = GetPortalByName(close_target);
2660 if (PortalIsValid(portal))
2661 PortalDrop(portal, false);
2665 elog(ERROR, "Invalid Close message subtype %d",
2670 if (whereToSendOutput == Remote)
2671 pq_putemptymessage('3'); /* CloseComplete */
2675 case 'D': /* describe */
2678 const char *describe_target;
2680 describe_type = pq_getmsgbyte(input_message);
2681 describe_target = pq_getmsgstring(input_message);
2682 pq_getmsgend(input_message);
2684 switch (describe_type)
2687 exec_describe_statement_message(describe_target);
2690 exec_describe_portal_message(describe_target);
2693 elog(ERROR, "Invalid Describe message subtype %d",
2700 case 'H': /* flush */
2701 pq_getmsgend(input_message);
2702 if (whereToSendOutput == Remote)
2706 case 'S': /* sync */
2707 pq_getmsgend(input_message);
2708 finish_xact_command(false);
2713 * 'X' means that the frontend is closing down the socket.
2714 * EOF means unexpected loss of frontend connection.
2715 * Either way, perform normal shutdown.
2721 * Reset whereToSendOutput to prevent elog from attempting
2722 * to send any more messages to client.
2724 if (whereToSendOutput == Remote)
2725 whereToSendOutput = None;
2728 * NOTE: if you are tempted to add more code here, DON'T!
2729 * Whatever you had in mind to do should be set up as an
2730 * on_proc_exit or on_shmem_exit callback, instead.
2731 * Otherwise it will fail to be called during other
2732 * backend-shutdown scenarios.
2736 case 'd': /* copy data */
2737 case 'c': /* copy done */
2738 case 'f': /* copy fail */
2740 * Accept but ignore these messages, per protocol spec;
2741 * we probably got here because a COPY failed, and the
2742 * frontend is still sending data.
2747 elog(FATAL, "Socket command type %c unknown", firstchar);
2750 #ifdef MEMORY_CONTEXT_CHECKING
2753 * Check all memory after each backend loop. This is a rather
2754 * weird place to do it, perhaps.
2756 MemoryContextCheck(TopMemoryContext);
2758 } /* end of input-reading loop */
2760 /* can't get here because the above loop never exits */
2763 return 1; /* keep compiler quiet */
2766 #ifndef HAVE_GETRUSAGE
2767 #include "rusagestub.h"
2769 #include <sys/resource.h>
2770 #endif /* HAVE_GETRUSAGE */
2772 struct rusage Save_r;
2773 struct timeval Save_t;
2778 getrusage(RUSAGE_SELF, &Save_r);
2779 gettimeofday(&Save_t, NULL);
2781 /* ResetTupleCount(); */
2785 ShowUsage(const char *title)
2788 struct timeval user,
2790 struct timeval elapse_t;
2794 getrusage(RUSAGE_SELF, &r);
2795 gettimeofday(&elapse_t, NULL);
2796 memcpy((char *) &user, (char *) &r.ru_utime, sizeof(user));
2797 memcpy((char *) &sys, (char *) &r.ru_stime, sizeof(sys));
2798 if (elapse_t.tv_usec < Save_t.tv_usec)
2801 elapse_t.tv_usec += 1000000;
2803 if (r.ru_utime.tv_usec < Save_r.ru_utime.tv_usec)
2805 r.ru_utime.tv_sec--;
2806 r.ru_utime.tv_usec += 1000000;
2808 if (r.ru_stime.tv_usec < Save_r.ru_stime.tv_usec)
2810 r.ru_stime.tv_sec--;
2811 r.ru_stime.tv_usec += 1000000;
2815 * the only stats we don't show here are for memory usage -- i can't
2816 * figure out how to interpret the relevant fields in the rusage
2817 * struct, and they change names across o/s platforms, anyway. if you
2818 * can figure out what the entries mean, you can somehow extract
2819 * resident set size, shared text size, and unshared data and stack
2822 initStringInfo(&str);
2824 appendStringInfo(&str, "! system usage stats:\n");
2825 appendStringInfo(&str,
2826 "!\t%ld.%06ld elapsed %ld.%06ld user %ld.%06ld system sec\n",
2827 (long) (elapse_t.tv_sec - Save_t.tv_sec),
2828 (long) (elapse_t.tv_usec - Save_t.tv_usec),
2829 (long) (r.ru_utime.tv_sec - Save_r.ru_utime.tv_sec),
2830 (long) (r.ru_utime.tv_usec - Save_r.ru_utime.tv_usec),
2831 (long) (r.ru_stime.tv_sec - Save_r.ru_stime.tv_sec),
2832 (long) (r.ru_stime.tv_usec - Save_r.ru_stime.tv_usec));
2833 appendStringInfo(&str,
2834 "!\t[%ld.%06ld user %ld.%06ld sys total]\n",
2836 (long) user.tv_usec,
2838 (long) sys.tv_usec);
2839 /* BeOS has rusage but only has some fields, and not these... */
2840 #if defined(HAVE_GETRUSAGE)
2841 appendStringInfo(&str,
2842 "!\t%ld/%ld [%ld/%ld] filesystem blocks in/out\n",
2843 r.ru_inblock - Save_r.ru_inblock,
2844 /* they only drink coffee at dec */
2845 r.ru_oublock - Save_r.ru_oublock,
2846 r.ru_inblock, r.ru_oublock);
2847 appendStringInfo(&str,
2848 "!\t%ld/%ld [%ld/%ld] page faults/reclaims, %ld [%ld] swaps\n",
2849 r.ru_majflt - Save_r.ru_majflt,
2850 r.ru_minflt - Save_r.ru_minflt,
2851 r.ru_majflt, r.ru_minflt,
2852 r.ru_nswap - Save_r.ru_nswap,
2854 appendStringInfo(&str,
2855 "!\t%ld [%ld] signals rcvd, %ld/%ld [%ld/%ld] messages rcvd/sent\n",
2856 r.ru_nsignals - Save_r.ru_nsignals,
2858 r.ru_msgrcv - Save_r.ru_msgrcv,
2859 r.ru_msgsnd - Save_r.ru_msgsnd,
2860 r.ru_msgrcv, r.ru_msgsnd);
2861 appendStringInfo(&str,
2862 "!\t%ld/%ld [%ld/%ld] voluntary/involuntary context switches\n",
2863 r.ru_nvcsw - Save_r.ru_nvcsw,
2864 r.ru_nivcsw - Save_r.ru_nivcsw,
2865 r.ru_nvcsw, r.ru_nivcsw);
2866 #endif /* HAVE_GETRUSAGE */
2868 bufusage = ShowBufferUsage();
2869 appendStringInfo(&str, "! buffer usage stats:\n%s", bufusage);
2872 /* remove trailing newline */
2873 if (str.data[str.len - 1] == '\n')
2874 str.data[--str.len] = '\0';
2876 elog(LOG, "%s\n%s", title, str.data);