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.338 2003/05/06 23:34:55 momjian Exp $
14 * this is the "main" module of the postgres backend and
15 * hence the main module of the "traffic cop".
17 *-------------------------------------------------------------------------
27 #include <sys/socket.h>
30 #include <sys/select.h>
36 #include "access/printtup.h"
37 #include "access/xlog.h"
38 #include "catalog/pg_type.h"
39 #include "commands/async.h"
40 #include "commands/prepare.h"
41 #include "commands/trigger.h"
42 #include "libpq/libpq.h"
43 #include "libpq/pqformat.h"
44 #include "libpq/pqsignal.h"
45 #include "miscadmin.h"
46 #include "nodes/print.h"
47 #include "optimizer/cost.h"
48 #include "optimizer/planner.h"
49 #include "parser/analyze.h"
50 #include "parser/parser.h"
51 #include "rewrite/rewriteHandler.h"
52 #include "storage/freespace.h"
53 #include "storage/ipc.h"
54 #include "storage/pg_shmem.h"
55 #include "storage/proc.h"
56 #include "tcop/fastpath.h"
57 #include "tcop/pquery.h"
58 #include "tcop/tcopprot.h"
59 #include "tcop/utility.h"
60 #include "utils/guc.h"
61 #include "utils/lsyscache.h"
62 #include "utils/memutils.h"
63 #include "utils/ps_status.h"
64 #include "mb/pg_wchar.h"
76 const char *debug_query_string; /* for pgmonitor and
77 * log_min_error_statement */
79 /* Note: whereToSendOutput is initialized for the bootstrap/standalone case */
80 CommandDest whereToSendOutput = Debug;
82 /* note: these declarations had better match tcopprot.h */
83 sigjmp_buf Warn_restart;
85 bool Warn_restart_ready = false;
88 extern bool autocommit;
91 * Flags for expensive function optimization -- JMH 3/9/92
101 * Flag to mark SIGHUP. Whenever the main loop comes around it
102 * will reread the configuration file. (Better than doing the
103 * reading in the signal handler, ey?)
105 static volatile bool got_SIGHUP = false;
108 * Flag to keep track of whether we have started a transaction.
109 * For extended query protocol this has to be remembered across messages.
111 static bool xact_started = false;
114 * Flags to implement skip-till-Sync-after-error behavior for messages of
115 * the extended query protocol.
117 static bool doing_extended_query_message = false;
118 static bool ignore_till_sync = false;
121 * If an unnamed prepared statement exists, it's stored here.
122 * We keep it separate from the hashtable kept by commands/prepare.c
123 * in order to reduce overhead for short-lived queries.
125 static MemoryContext unnamed_stmt_context = NULL;
126 static PreparedStatement *unnamed_stmt_pstmt = NULL;
129 static bool EchoQuery = false; /* default don't echo */
132 * people who want to use EOF should #define DONTUSENEWLINE in
135 #ifndef TCOP_DONTUSENEWLINE
136 static int UseNewLine = 1; /* Use newlines query delimiters (the
139 static int UseNewLine = 0; /* Use EOF as query delimiters */
140 #endif /* TCOP_DONTUSENEWLINE */
143 /* ----------------------------------------------------------------
144 * decls for routines only used in this file
145 * ----------------------------------------------------------------
147 static int InteractiveBackend(StringInfo inBuf);
148 static int SocketBackend(StringInfo inBuf);
149 static int ReadCommand(StringInfo inBuf);
150 static void start_xact_command(void);
151 static void finish_xact_command(bool forceCommit);
152 static void SigHupHandler(SIGNAL_ARGS);
153 static void FloatExceptionHandler(SIGNAL_ARGS);
156 /* ----------------------------------------------------------------
157 * routines to obtain user input
158 * ----------------------------------------------------------------
162 * InteractiveBackend() is called for user interactive connections
164 * the string entered by the user is placed in its parameter inBuf,
165 * and we act like a Q message was received.
167 * EOF is returned if end-of-file input is seen; time to shut down.
172 InteractiveBackend(StringInfo inBuf)
174 int c; /* character read from getc() */
175 bool end = false; /* end-of-input flag */
176 bool backslashSeen = false; /* have we seen a \ ? */
179 * display a prompt and obtain input from the user
184 /* Reset inBuf to empty */
186 inBuf->data[0] = '\0';
194 * if we are using \n as a delimiter, then read characters
197 while ((c = getc(stdin)) != EOF)
203 /* discard backslash from inBuf */
204 inBuf->data[--inBuf->len] = '\0';
205 backslashSeen = false;
210 /* keep the newline character */
211 appendStringInfoChar(inBuf, '\n');
216 backslashSeen = true;
218 backslashSeen = false;
220 appendStringInfoChar(inBuf, (char) c);
229 * otherwise read characters until EOF.
231 while ((c = getc(stdin)) != EOF)
232 appendStringInfoChar(inBuf, (char) c);
242 * otherwise we have a user query so process it.
247 /* Add '\0' to make it look the same as message case. */
248 appendStringInfoChar(inBuf, (char) '\0');
251 * if the query echo flag was given, print the query..
254 printf("statement: %s\n", inBuf->data);
261 * SocketBackend() Is called for frontend-backend connections
263 * Returns the message type code, and loads message body data into inBuf.
265 * EOF is returned if the connection is lost.
269 SocketBackend(StringInfo inBuf)
274 * Get message type code from the frontend.
276 qtype = pq_getbyte();
278 if (qtype == EOF) /* frontend disconnected */
280 elog(COMMERROR, "unexpected EOF on client connection");
285 * Validate message type code before trying to read body; if we have
286 * lost sync, better to say "command unknown" than to run out of memory
287 * because we used garbage as a length word.
289 * This also gives us a place to set the doing_extended_query_message
290 * flag as soon as possible.
294 case 'Q': /* simple query */
295 doing_extended_query_message = false;
296 if (PG_PROTOCOL_MAJOR(FrontendProtocol) < 3)
298 /* old style without length word; convert */
299 if (pq_getstring(inBuf))
301 elog(COMMERROR, "unexpected EOF on client connection");
307 case 'F': /* fastpath function call */
308 /* we let fastpath.c cope with old-style input of this */
309 doing_extended_query_message = false;
312 case 'X': /* terminate */
313 doing_extended_query_message = false;
317 case 'C': /* close */
318 case 'D': /* describe */
319 case 'E': /* execute */
320 case 'H': /* flush */
321 case 'P': /* parse */
322 doing_extended_query_message = true;
323 /* these are only legal in protocol 3 */
324 if (PG_PROTOCOL_MAJOR(FrontendProtocol) < 3)
325 elog(FATAL, "Socket command type %c unknown", qtype);
329 /* stop any active skip-till-Sync */
330 ignore_till_sync = false;
331 /* mark not-extended, so that a new error doesn't begin skip */
332 doing_extended_query_message = false;
333 /* only legal in protocol 3 */
334 if (PG_PROTOCOL_MAJOR(FrontendProtocol) < 3)
335 elog(FATAL, "Socket command type %c unknown", qtype);
338 case 'd': /* copy data */
339 case 'c': /* copy done */
340 case 'f': /* copy fail */
341 doing_extended_query_message = false;
342 /* these are only legal in protocol 3 */
343 if (PG_PROTOCOL_MAJOR(FrontendProtocol) < 3)
344 elog(FATAL, "Socket command type %c unknown", qtype);
349 * Otherwise we got garbage from the frontend. We treat this
350 * as fatal because we have probably lost message boundary sync,
351 * and there's no good way to recover.
353 elog(FATAL, "Socket command type %c unknown", qtype);
358 * In protocol version 3, all frontend messages have a length word
359 * next after the type code; we can read the message contents
360 * independently of the type.
362 if (PG_PROTOCOL_MAJOR(FrontendProtocol) >= 3)
364 if (pq_getmessage(inBuf, 0))
365 return EOF; /* suitable message already logged */
372 * ReadCommand reads a command from either the frontend or
373 * standard input, places it in inBuf, and returns the
374 * message type code (first byte of the message).
375 * EOF is returned if end of file.
379 ReadCommand(StringInfo inBuf)
383 if (IsUnderPostmaster)
384 result = SocketBackend(inBuf);
386 result = InteractiveBackend(inBuf);
392 * Parse a query string and pass it through the rewriter.
394 * A list of Query nodes is returned, since the string might contain
395 * multiple queries and/or the rewriter might expand one query to several.
397 * NOTE: this routine is no longer used for processing interactive queries,
398 * but it is still needed for parsing of SQL function bodies.
401 pg_parse_and_rewrite(const char *query_string, /* string to execute */
402 Oid *paramTypes, /* parameter types */
403 int numParams) /* number of parameters */
405 List *raw_parsetree_list;
406 List *querytree_list;
410 * (1) parse the request string into a list of raw parse trees.
412 raw_parsetree_list = pg_parse_query(query_string);
415 * (2) Do parse analysis and rule rewrite.
417 querytree_list = NIL;
418 foreach(list_item, raw_parsetree_list)
420 Node *parsetree = (Node *) lfirst(list_item);
422 querytree_list = nconc(querytree_list,
423 pg_analyze_and_rewrite(parsetree,
428 return querytree_list;
432 * Do raw parsing (only).
434 * A list of parsetrees is returned, since there might be multiple
435 * commands in the given string.
437 * NOTE: for interactive queries, it is important to keep this routine
438 * separate from the analysis & rewrite stages. Analysis and rewriting
439 * cannot be done in an aborted transaction, since they require access to
440 * database tables. So, we rely on the raw parser to determine whether
441 * we've seen a COMMIT or ABORT command; when we are in abort state, other
442 * commands are not processed any further than the raw parse stage.
445 pg_parse_query(const char *query_string)
447 List *raw_parsetree_list;
450 elog(LOG, "query: %s", query_string);
452 if (log_parser_stats)
455 raw_parsetree_list = raw_parser(query_string);
457 if (log_parser_stats)
458 ShowUsage("PARSER STATISTICS");
460 return raw_parsetree_list;
464 * Given a raw parsetree (gram.y output), and optionally information about
465 * types of parameter symbols ($n), perform parse analysis and rule rewriting.
467 * A list of Query nodes is returned, since either the analyzer or the
468 * rewriter might expand one query to several.
470 * NOTE: for reasons mentioned above, this must be separate from raw parsing.
473 pg_analyze_and_rewrite(Node *parsetree, Oid *paramTypes, int numParams)
475 List *querytree_list;
478 * (1) Perform parse analysis.
480 if (log_parser_stats)
483 querytree_list = parse_analyze(parsetree, paramTypes, numParams);
485 if (log_parser_stats)
486 ShowUsage("PARSE ANALYSIS STATISTICS");
489 * (2) Rewrite the queries, as necessary
491 querytree_list = pg_rewrite_queries(querytree_list);
493 return querytree_list;
497 * Perform rewriting of a list of queries produced by parse analysis.
500 pg_rewrite_queries(List *querytree_list)
502 List *new_list = NIL;
505 if (log_parser_stats)
509 * rewritten queries are collected in new_list. Note there may be more
510 * or fewer than in the original list.
512 foreach(list_item, querytree_list)
514 Query *querytree = (Query *) lfirst(list_item);
516 if (Debug_print_parse)
517 elog_node_display(LOG, "parse tree", querytree,
520 if (querytree->commandType == CMD_UTILITY)
522 /* don't rewrite utilities, just dump 'em into new_list */
523 new_list = lappend(new_list, querytree);
527 /* rewrite regular queries */
528 List *rewritten = QueryRewrite(querytree);
530 new_list = nconc(new_list, rewritten);
534 querytree_list = new_list;
536 if (log_parser_stats)
537 ShowUsage("REWRITER STATISTICS");
539 #ifdef COPY_PARSE_PLAN_TREES
542 * Optional debugging check: pass querytree output through
545 new_list = (List *) copyObject(querytree_list);
546 /* This checks both copyObject() and the equal() routines... */
547 if (!equal(new_list, querytree_list))
548 elog(WARNING, "pg_rewrite_queries: copyObject failed on parse tree");
550 querytree_list = new_list;
553 if (Debug_print_rewritten)
554 elog_node_display(LOG, "rewritten parse tree", querytree_list,
557 return querytree_list;
561 /* Generate a plan for a single already-rewritten query. */
563 pg_plan_query(Query *querytree)
567 /* Utility commands have no plans. */
568 if (querytree->commandType == CMD_UTILITY)
571 if (log_planner_stats)
574 /* call the optimizer */
575 plan = planner(querytree, false, 0);
577 if (log_planner_stats)
578 ShowUsage("PLANNER STATISTICS");
580 #ifdef COPY_PARSE_PLAN_TREES
581 /* Optional debugging check: pass plan output through copyObject() */
583 Plan *new_plan = (Plan *) copyObject(plan);
586 * equal() currently does not have routines to compare Plan nodes,
587 * so don't try to test equality here. Perhaps fix someday?
590 /* This checks both copyObject() and the equal() routines... */
591 if (!equal(new_plan, plan))
592 elog(WARNING, "pg_plan_query: copyObject failed on plan tree");
600 * Print plan if debugging.
602 if (Debug_print_plan)
603 elog_node_display(LOG, "plan", plan, Debug_pretty_print);
609 * Generate plans for a list of already-rewritten queries.
611 * If needSnapshot is TRUE, we haven't yet set a snapshot for the current
612 * query. A snapshot must be set before invoking the planner, since it
613 * might try to evaluate user-defined functions. But we must not set a
614 * snapshot if the list contains only utility statements, because some
615 * utility statements depend on not having frozen the snapshot yet.
616 * (We assume that such statements cannot appear together with plannable
617 * statements in the rewriter's output.)
620 pg_plan_queries(List *querytrees, bool needSnapshot)
622 List *plan_list = NIL;
625 foreach(query_list, querytrees)
627 Query *query = (Query *) lfirst(query_list);
630 if (query->commandType == CMD_UTILITY)
632 /* Utility commands have no plans. */
640 needSnapshot = false;
642 plan = pg_plan_query(query);
645 plan_list = lappend(plan_list, plan);
655 * Execute a "simple Query" protocol message.
658 exec_simple_query(const char *query_string)
660 CommandDest dest = whereToSendOutput;
661 DestReceiver *receiver;
662 MemoryContext oldcontext;
663 List *parsetree_list,
665 struct timeval start_t,
667 bool save_log_duration = log_duration;
668 bool save_log_statement_stats = log_statement_stats;
671 * Report query to various monitoring facilities.
673 debug_query_string = query_string;
675 pgstat_report_activity(query_string);
678 * We use save_log_duration so "SET log_duration = true" doesn't
679 * report incorrect time because gettimeofday() wasn't called.
680 * Similarly, log_statement_stats has to be captured once.
682 if (save_log_duration)
683 gettimeofday(&start_t, NULL);
685 if (save_log_statement_stats)
689 * Create destination receiver object --- we can reuse it for all
690 * queries in the string. Note it is created in MessageContext.
692 receiver = CreateDestReceiver(dest);
695 * Start up a transaction command. All queries generated by the
696 * query_string will be in this same command block, *unless* we find a
697 * BEGIN/COMMIT/ABORT statement; we have to force a new xact command
698 * after one of those, else bad things will happen in xact.c. (Note
699 * that this will normally change current memory context.)
701 start_xact_command();
704 * Zap any pre-existing unnamed statement. (While not strictly
705 * necessary, it seems best to define simple-Query mode as if it
706 * used the unnamed statement and portal; this ensures we recover
707 * any storage used by prior unnamed operations.)
709 unnamed_stmt_pstmt = NULL;
710 if (unnamed_stmt_context)
712 DropDependentPortals(unnamed_stmt_context);
713 MemoryContextDelete(unnamed_stmt_context);
715 unnamed_stmt_context = NULL;
718 * Switch to appropriate context for constructing parsetrees.
720 oldcontext = MemoryContextSwitchTo(MessageContext);
722 QueryContext = CurrentMemoryContext;
725 * Do basic parsing of the query or queries (this should be safe even
726 * if we are in aborted transaction state!)
728 parsetree_list = pg_parse_query(query_string);
731 * Switch back to transaction context to enter the loop.
733 MemoryContextSwitchTo(oldcontext);
736 * Run through the raw parsetree(s) and process each one.
738 foreach(parsetree_item, parsetree_list)
740 Node *parsetree = (Node *) lfirst(parsetree_item);
741 const char *commandTag;
742 char completionTag[COMPLETION_TAG_BUFSIZE];
743 List *querytree_list,
748 * Get the command name for use in status display (it also becomes the
749 * default completion tag, down inside PortalRun). Set ps_status and
750 * do any special start-of-SQL-command processing needed by the
753 commandTag = CreateCommandTag(parsetree);
755 set_ps_display(commandTag);
757 BeginCommand(commandTag, dest);
760 * If we are in an aborted transaction, reject all commands except
761 * COMMIT/ABORT. It is important that this test occur before we
762 * try to do parse analysis, rewrite, or planning, since all those
763 * phases try to do database accesses, which may fail in abort
764 * state. (It might be safe to allow some additional utility
765 * commands in this state, but not many...)
767 if (IsAbortedTransactionBlockState())
769 bool allowit = false;
771 if (IsA(parsetree, TransactionStmt))
773 TransactionStmt *stmt = (TransactionStmt *) parsetree;
775 if (stmt->kind == TRANS_STMT_COMMIT ||
776 stmt->kind == TRANS_STMT_ROLLBACK)
781 elog(ERROR, "current transaction is aborted, "
782 "queries ignored until end of transaction block");
785 /* Make sure we are in a transaction command */
786 start_xact_command();
788 /* If we got a cancel signal in parsing or prior command, quit */
789 CHECK_FOR_INTERRUPTS();
792 * OK to analyze, rewrite, and plan this query.
794 * Switch to appropriate context for constructing querytrees (again,
795 * these must outlive the execution context).
797 oldcontext = MemoryContextSwitchTo(MessageContext);
799 querytree_list = pg_analyze_and_rewrite(parsetree, NULL, 0);
801 plantree_list = pg_plan_queries(querytree_list, true);
803 /* If we got a cancel signal in analysis or planning, quit */
804 CHECK_FOR_INTERRUPTS();
807 * Switch back to transaction context for execution.
809 MemoryContextSwitchTo(oldcontext);
812 * Create unnamed portal to run the query or queries in.
813 * If there already is one, silently drop it.
815 portal = CreatePortal("", true, true);
817 PortalDefineQuery(portal,
825 * Run the portal to completion, and then drop it.
827 PortalStart(portal, NULL);
829 (void) PortalRun(portal,
835 PortalDrop(portal, false);
838 if (IsA(parsetree, TransactionStmt) ||
839 IsA(parsetree, VariableSetStmt) ||
840 IsA(parsetree, VariableShowStmt) ||
841 IsA(parsetree, VariableResetStmt))
844 * If this was a transaction control statement or a variable
845 * set/show/reset statement, commit it. We will start a
846 * new xact command for the next command (if any).
848 finish_xact_command(true);
850 else if (lnext(parsetree_item) == NIL || !autocommit)
853 * If this is the last parsetree of the query string, close down
854 * transaction statement before reporting command-complete. This
855 * is so that any end-of-transaction errors are reported before
856 * the command-complete message is issued, to avoid confusing
857 * clients who will expect either a command-complete message or an
858 * error, not one and then the other. But for compatibility with
859 * historical Postgres behavior, we do not force a transaction
860 * boundary between queries appearing in a single query string.
862 finish_xact_command(false);
867 * We need a CommandCounterIncrement after every query,
868 * except those that start or end a transaction block.
870 CommandCounterIncrement();
874 * Tell client that we're done with this query. Note we emit
875 * exactly one EndCommand report for each raw parsetree, thus one
876 * for each SQL command the client sent, regardless of rewriting.
877 * (But a command aborted by error will not send an EndCommand
880 EndCommand(completionTag, dest);
881 } /* end loop over parsetrees */
884 * If there were no parsetrees, return EmptyQueryResponse message.
889 (*receiver->destroy) (receiver);
894 * Close down transaction statement, if one is open.
896 finish_xact_command(false);
899 * Finish up monitoring.
901 if (save_log_duration)
903 gettimeofday(&stop_t, NULL);
904 if (stop_t.tv_usec < start_t.tv_usec)
907 stop_t.tv_usec += 1000000;
909 elog(LOG, "duration: %ld.%06ld sec",
910 (long) (stop_t.tv_sec - start_t.tv_sec),
911 (long) (stop_t.tv_usec - start_t.tv_usec));
914 if (save_log_statement_stats)
915 ShowUsage("QUERY STATISTICS");
917 debug_query_string = NULL;
923 * Execute a "Parse" protocol message.
926 exec_parse_message(const char *query_string, /* string to execute */
927 const char *stmt_name, /* name for prepared stmt */
928 Oid *paramTypes, /* parameter types */
929 int numParams) /* number of parameters */
931 MemoryContext oldcontext;
932 List *parsetree_list;
933 const char *commandTag;
934 List *querytree_list,
938 bool save_log_statement_stats = log_statement_stats;
941 * Report query to various monitoring facilities.
943 debug_query_string = query_string;
945 pgstat_report_activity(query_string);
947 set_ps_display("PARSE");
949 if (save_log_statement_stats)
953 * Start up a transaction command so we can run parse analysis etc.
954 * (Note that this will normally change current memory context.)
955 * Nothing happens if we are already in one.
957 start_xact_command();
960 * Switch to appropriate context for constructing parsetrees.
962 * We have two strategies depending on whether the prepared statement
963 * is named or not. For a named prepared statement, we do parsing
964 * in MessageContext and copy the finished trees into the prepared
965 * statement's private context; then the reset of MessageContext releases
966 * temporary space used by parsing and planning. For an unnamed prepared
967 * statement, we assume the statement isn't going to hang around long,
968 * so getting rid of temp space quickly is probably not worth the costs
969 * of copying parse/plan trees. So in this case, we set up a special
970 * context for the unnamed statement, and do all the parsing/planning
973 is_named = (stmt_name[0] != '\0');
976 /* Named prepared statement --- parse in MessageContext */
977 oldcontext = MemoryContextSwitchTo(MessageContext);
981 /* Unnamed prepared statement --- release any prior unnamed stmt */
982 unnamed_stmt_pstmt = NULL;
983 if (unnamed_stmt_context)
985 DropDependentPortals(unnamed_stmt_context);
986 MemoryContextDelete(unnamed_stmt_context);
988 unnamed_stmt_context = NULL;
989 /* create context for parsing/planning */
990 unnamed_stmt_context =
991 AllocSetContextCreate(TopMemoryContext,
992 "unnamed prepared statement",
993 ALLOCSET_DEFAULT_MINSIZE,
994 ALLOCSET_DEFAULT_INITSIZE,
995 ALLOCSET_DEFAULT_MAXSIZE);
996 oldcontext = MemoryContextSwitchTo(unnamed_stmt_context);
999 QueryContext = CurrentMemoryContext;
1002 * Do basic parsing of the query or queries (this should be safe even
1003 * if we are in aborted transaction state!)
1005 parsetree_list = pg_parse_query(query_string);
1008 * We only allow a single user statement in a prepared statement.
1009 * This is mainly to keep the protocol simple --- otherwise we'd need
1010 * to worry about multiple result tupdescs and things like that.
1012 if (length(parsetree_list) > 1)
1013 elog(ERROR, "Cannot insert multiple commands into a prepared statement");
1015 if (parsetree_list != NIL)
1017 Node *parsetree = (Node *) lfirst(parsetree_list);
1021 * Get the command name for possible use in status display.
1023 commandTag = CreateCommandTag(parsetree);
1026 * If we are in an aborted transaction, reject all commands except
1027 * COMMIT/ROLLBACK. It is important that this test occur before we
1028 * try to do parse analysis, rewrite, or planning, since all those
1029 * phases try to do database accesses, which may fail in abort
1030 * state. (It might be safe to allow some additional utility
1031 * commands in this state, but not many...)
1033 if (IsAbortedTransactionBlockState())
1035 bool allowit = false;
1037 if (IsA(parsetree, TransactionStmt))
1039 TransactionStmt *stmt = (TransactionStmt *) parsetree;
1041 if (stmt->kind == TRANS_STMT_COMMIT ||
1042 stmt->kind == TRANS_STMT_ROLLBACK)
1047 elog(ERROR, "current transaction is aborted, "
1048 "queries ignored until end of transaction block");
1052 * OK to analyze, rewrite, and plan this query. Note that the
1053 * originally specified parameter set is not required to be
1054 * complete, so we have to use parse_analyze_varparams().
1056 if (log_parser_stats)
1059 querytree_list = parse_analyze_varparams(parsetree,
1064 * Check all parameter types got determined, and convert array
1065 * representation to a list for storage.
1068 for (i = 0; i < numParams; i++)
1070 Oid ptype = paramTypes[i];
1072 if (ptype == InvalidOid || ptype == UNKNOWNOID)
1073 elog(ERROR, "Could not determine datatype of parameter $%d",
1075 param_list = lappendo(param_list, ptype);
1078 if (log_parser_stats)
1079 ShowUsage("PARSE ANALYSIS STATISTICS");
1081 querytree_list = pg_rewrite_queries(querytree_list);
1083 plantree_list = pg_plan_queries(querytree_list, true);
1087 /* Empty input string. This is legal. */
1089 querytree_list = NIL;
1090 plantree_list = NIL;
1094 /* If we got a cancel signal in analysis or planning, quit */
1095 CHECK_FOR_INTERRUPTS();
1098 * Store the query as a prepared statement. See above comments.
1102 StorePreparedStatement(stmt_name,
1111 PreparedStatement *pstmt;
1113 pstmt = (PreparedStatement *) palloc0(sizeof(PreparedStatement));
1114 /* query_string needs to be copied into unnamed_stmt_context */
1115 pstmt->query_string = pstrdup(query_string);
1116 /* the rest is there already */
1117 pstmt->commandTag = commandTag;
1118 pstmt->query_list = querytree_list;
1119 pstmt->plan_list = plantree_list;
1120 pstmt->argtype_list = param_list;
1121 pstmt->context = unnamed_stmt_context;
1122 /* Now the unnamed statement is complete and valid */
1123 unnamed_stmt_pstmt = pstmt;
1126 MemoryContextSwitchTo(oldcontext);
1128 QueryContext = NULL;
1131 * We do NOT close the open transaction command here; that only happens
1132 * when the client sends Sync. Instead, do CommandCounterIncrement just
1133 * in case something happened during parse/plan.
1135 CommandCounterIncrement();
1138 * Send ParseComplete.
1140 if (whereToSendOutput == Remote)
1141 pq_putemptymessage('1');
1143 if (save_log_statement_stats)
1144 ShowUsage("PARSE MESSAGE STATISTICS");
1146 debug_query_string = NULL;
1152 * Process a "Bind" message to create a portal from a prepared statement
1155 exec_bind_message(StringInfo input_message)
1157 const char *portal_name;
1158 const char *stmt_name;
1161 PreparedStatement *pstmt;
1163 ParamListInfo params;
1165 pgstat_report_activity("<BIND>");
1167 set_ps_display("BIND");
1170 * Start up a transaction command so we can call functions etc.
1171 * (Note that this will normally change current memory context.)
1172 * Nothing happens if we are already in one.
1174 start_xact_command();
1176 /* Get the fixed part of the message */
1177 portal_name = pq_getmsgstring(input_message);
1178 stmt_name = pq_getmsgstring(input_message);
1179 is_binary = pq_getmsgbyte(input_message);
1180 numParams = pq_getmsgint(input_message, 4);
1183 elog(ERROR, "Binary BIND not implemented yet");
1185 /* Find prepared statement */
1186 if (stmt_name[0] != '\0')
1187 pstmt = FetchPreparedStatement(stmt_name, true);
1190 /* special-case the unnamed statement */
1191 pstmt = unnamed_stmt_pstmt;
1193 elog(ERROR, "Unnamed prepared statement does not exist");
1196 if (numParams != length(pstmt->argtype_list))
1197 elog(ERROR, "Bind message supplies %d parameters, but prepared statement \"%s\" requires %d",
1198 numParams, stmt_name, length(pstmt->argtype_list));
1201 * Create the portal. Allow silent replacement of an existing portal
1202 * only if the unnamed portal is specified.
1204 if (portal_name[0] == '\0')
1205 portal = CreatePortal(portal_name, true, true);
1207 portal = CreatePortal(portal_name, false, false);
1209 PortalDefineQuery(portal,
1210 pstmt->query_string,
1217 * Fetch parameters, if any, and store in the portal's memory context.
1219 * In an aborted transaction, we can't risk calling user-defined functions,
1220 * so bind all parameters to null values.
1224 bool isaborted = IsAbortedTransactionBlockState();
1227 MemoryContext oldContext;
1229 oldContext = MemoryContextSwitchTo(PortalGetHeapMemory(portal));
1231 params = (ParamListInfo)
1232 palloc0((numParams + 1) * sizeof(ParamListInfoData));
1234 foreach(l, pstmt->argtype_list)
1236 Oid ptype = lfirsto(l);
1239 isNull = (pq_getmsgbyte(input_message) != 0) ? false : true;
1242 const char *ptext = pq_getmsgstring(input_message);
1251 getTypeInputInfo(ptype, &typInput, &typElem);
1253 OidFunctionCall3(typInput,
1254 CStringGetDatum(ptext),
1255 ObjectIdGetDatum(typElem),
1259 params[i].kind = PARAM_NUM;
1260 params[i].id = i + 1;
1261 params[i].isnull = isNull;
1266 params[i].kind = PARAM_INVALID;
1268 MemoryContextSwitchTo(oldContext);
1273 pq_getmsgend(input_message);
1276 * Start portal execution.
1278 PortalStart(portal, params);
1281 * Send BindComplete.
1283 if (whereToSendOutput == Remote)
1284 pq_putemptymessage('2');
1288 * exec_execute_message
1290 * Process an "Execute" message for a portal
1293 exec_execute_message(const char *portal_name, int is_binary, long max_rows)
1296 DestReceiver *receiver;
1298 bool is_trans_stmt = false;
1299 bool is_trans_exit = false;
1301 char completionTag[COMPLETION_TAG_BUFSIZE];
1303 /* Adjust destination to tell printtup.c what to do */
1304 dest = whereToSendOutput;
1306 dest = is_binary ? RemoteExecuteInternal : RemoteExecute;
1308 portal = GetPortalByName(portal_name);
1309 if (!PortalIsValid(portal))
1310 elog(ERROR, "Portal \"%s\" not found", portal_name);
1313 * If the original query was a null string, just return EmptyQueryResponse.
1315 if (portal->commandTag == NULL)
1317 Assert(portal->parseTrees == NIL);
1322 if (portal->sourceText)
1324 debug_query_string = portal->sourceText;
1325 pgstat_report_activity(portal->sourceText);
1329 debug_query_string = "execute message";
1330 pgstat_report_activity("<EXECUTE>");
1333 set_ps_display(portal->commandTag);
1335 BeginCommand(portal->commandTag, dest);
1337 /* Check for transaction-control commands */
1338 if (length(portal->parseTrees) == 1)
1340 Query *query = (Query *) lfirst(portal->parseTrees);
1342 if (query->commandType == CMD_UTILITY &&
1343 query->utilityStmt != NULL &&
1344 IsA(query->utilityStmt, TransactionStmt))
1346 TransactionStmt *stmt = (TransactionStmt *) query->utilityStmt;
1348 is_trans_stmt = true;
1349 if (stmt->kind == TRANS_STMT_COMMIT ||
1350 stmt->kind == TRANS_STMT_ROLLBACK)
1351 is_trans_exit = true;
1356 * Ensure we are in a transaction command (this should normally be
1357 * the case already due to prior BIND).
1359 start_xact_command();
1362 * If we are in aborted transaction state, the only portals we can
1363 * actually run are those containing COMMIT or ROLLBACK commands.
1365 if (IsAbortedTransactionBlockState())
1368 elog(ERROR, "current transaction is aborted, "
1369 "queries ignored until end of transaction block");
1372 /* Check for cancel signal before we start execution */
1373 CHECK_FOR_INTERRUPTS();
1376 * Okay to run the portal.
1378 receiver = CreateDestReceiver(dest);
1381 max_rows = FETCH_ALL;
1383 completed = PortalRun(portal,
1389 (*receiver->destroy) (receiver);
1396 * If this was a transaction control statement, commit it. We will
1397 * start a new xact command for the next command (if any).
1399 finish_xact_command(true);
1404 * We need a CommandCounterIncrement after every query,
1405 * except those that start or end a transaction block.
1407 CommandCounterIncrement();
1410 /* Send appropriate CommandComplete to client */
1411 EndCommand(completionTag, dest);
1415 /* Portal run not complete, so send PortalSuspended */
1416 if (whereToSendOutput == Remote)
1417 pq_putemptymessage('s');
1420 debug_query_string = NULL;
1424 * exec_describe_statement_message
1426 * Process a "Describe" message for a prepared statement
1429 exec_describe_statement_message(const char *stmt_name)
1431 PreparedStatement *pstmt;
1436 /* Find prepared statement */
1437 if (stmt_name[0] != '\0')
1438 pstmt = FetchPreparedStatement(stmt_name, true);
1441 /* special-case the unnamed statement */
1442 pstmt = unnamed_stmt_pstmt;
1444 elog(ERROR, "Unnamed prepared statement does not exist");
1447 if (whereToSendOutput != Remote)
1448 return; /* can't actually do anything... */
1451 * First describe the parameters...
1453 pq_beginmessage(&buf, 't'); /* parameter description message type */
1454 pq_sendint(&buf, length(pstmt->argtype_list), 4);
1456 foreach(l, pstmt->argtype_list)
1458 Oid ptype = lfirsto(l);
1460 pq_sendint(&buf, (int) ptype, 4);
1462 pq_endmessage(&buf);
1465 * Next send RowDescription or NoData to describe the result...
1467 tupdesc = FetchPreparedStatementResultDesc(pstmt);
1472 if (ChoosePortalStrategy(pstmt->query_list) == PORTAL_ONE_SELECT)
1473 targetlist = ((Query *) lfirst(pstmt->query_list))->targetList;
1476 SendRowDescriptionMessage(tupdesc, targetlist);
1479 pq_putemptymessage('n'); /* NoData */
1484 * exec_describe_portal_message
1486 * Process a "Describe" message for a portal
1489 exec_describe_portal_message(const char *portal_name)
1493 portal = GetPortalByName(portal_name);
1494 if (!PortalIsValid(portal))
1495 elog(ERROR, "Portal \"%s\" not found", portal_name);
1497 if (whereToSendOutput != Remote)
1498 return; /* can't actually do anything... */
1500 if (portal->tupDesc)
1504 if (portal->strategy == PORTAL_ONE_SELECT)
1505 targetlist = ((Plan *) lfirst(portal->planTrees))->targetlist;
1508 SendRowDescriptionMessage(portal->tupDesc, targetlist);
1511 pq_putemptymessage('n'); /* NoData */
1516 * Convenience routines for starting/committing a single command.
1519 start_xact_command(void)
1523 elog(DEBUG2, "StartTransactionCommand");
1524 StartTransactionCommand(false);
1526 /* Set statement timeout running, if any */
1527 if (StatementTimeout > 0)
1528 enable_sig_alarm(StatementTimeout, true);
1530 xact_started = true;
1535 finish_xact_command(bool forceCommit)
1539 /* Invoke IMMEDIATE constraint triggers */
1540 DeferredTriggerEndQuery();
1542 /* Cancel any active statement timeout before committing */
1543 disable_sig_alarm(true);
1545 /* Now commit the command */
1546 elog(DEBUG2, "CommitTransactionCommand");
1548 CommitTransactionCommand(forceCommit);
1550 #ifdef SHOW_MEMORY_STATS
1551 /* Print mem stats at each commit for leak tracking */
1553 MemoryContextStats(TopMemoryContext);
1556 xact_started = false;
1561 /* --------------------------------
1562 * signal handler routines used in PostgresMain()
1563 * --------------------------------
1567 * quickdie() occurs when signalled SIGQUIT by the postmaster.
1569 * Some backend has bought the farm,
1570 * so we need to stop what we're doing and exit.
1573 quickdie(SIGNAL_ARGS)
1575 PG_SETMASK(&BlockSig);
1576 elog(WARNING, "Message from PostgreSQL backend:"
1577 "\n\tThe Postmaster has informed me that some other backend"
1578 "\n\tdied abnormally and possibly corrupted shared memory."
1579 "\n\tI have rolled back the current transaction and am"
1580 "\n\tgoing to terminate your database system connection and exit."
1581 "\n\tPlease reconnect to the database system and repeat your query.");
1584 * DO NOT proc_exit() -- we're here because shared memory may be
1585 * corrupted, so we don't want to try to clean up our transaction.
1586 * Just nail the windows shut and get out of town.
1588 * Note we do exit(1) not exit(0). This is to force the postmaster into
1589 * a system reset cycle if some idiot DBA sends a manual SIGQUIT to a
1590 * random backend. This is necessary precisely because we don't clean
1591 * up our shared memory state.
1598 * Shutdown signal from postmaster: abort transaction and exit
1599 * at soonest convenient time
1604 int save_errno = errno;
1606 /* Don't joggle the elbow of proc_exit */
1607 if (!proc_exit_inprogress)
1609 InterruptPending = true;
1610 ProcDiePending = true;
1613 * If it's safe to interrupt, and we're waiting for input or a
1614 * lock, service the interrupt immediately
1616 if (ImmediateInterruptOK && InterruptHoldoffCount == 0 &&
1617 CritSectionCount == 0)
1619 /* bump holdoff count to make ProcessInterrupts() a no-op */
1620 /* until we are done getting ready for it */
1621 InterruptHoldoffCount++;
1622 DisableNotifyInterrupt();
1623 /* Make sure CheckDeadLock won't run while shutting down... */
1625 InterruptHoldoffCount--;
1626 ProcessInterrupts();
1634 * Timeout or shutdown signal from postmaster during client authentication.
1637 * XXX: possible future improvement: try to send a message indicating
1638 * why we are disconnecting. Problem is to be sure we don't block while
1639 * doing so, nor mess up the authentication message exchange.
1642 authdie(SIGNAL_ARGS)
1648 * Query-cancel signal from postmaster: abort current transaction
1649 * at soonest convenient time
1652 StatementCancelHandler(SIGNAL_ARGS)
1654 int save_errno = errno;
1657 * Don't joggle the elbow of proc_exit, nor an already-in-progress
1660 if (!proc_exit_inprogress && !InError)
1662 InterruptPending = true;
1663 QueryCancelPending = true;
1666 * If it's safe to interrupt, and we're waiting for a lock,
1667 * service the interrupt immediately. No point in interrupting if
1668 * we're waiting for input, however.
1670 if (ImmediateInterruptOK && InterruptHoldoffCount == 0 &&
1671 CritSectionCount == 0)
1673 /* bump holdoff count to make ProcessInterrupts() a no-op */
1674 /* until we are done getting ready for it */
1675 InterruptHoldoffCount++;
1676 if (LockWaitCancel())
1678 DisableNotifyInterrupt();
1679 InterruptHoldoffCount--;
1680 ProcessInterrupts();
1683 InterruptHoldoffCount--;
1690 /* signal handler for floating point exception */
1692 FloatExceptionHandler(SIGNAL_ARGS)
1694 elog(ERROR, "floating point exception!"
1695 " The last floating point operation either exceeded legal ranges"
1696 " or was a divide by zero");
1699 /* SIGHUP: set flag to re-read config file at next convenient time */
1701 SigHupHandler(SIGNAL_ARGS)
1708 * ProcessInterrupts: out-of-line portion of CHECK_FOR_INTERRUPTS() macro
1710 * If an interrupt condition is pending, and it's safe to service it,
1711 * then clear the flag and accept the interrupt. Called only when
1712 * InterruptPending is true.
1715 ProcessInterrupts(void)
1717 /* OK to accept interrupt now? */
1718 if (InterruptHoldoffCount != 0 || CritSectionCount != 0)
1720 InterruptPending = false;
1723 ProcDiePending = false;
1724 QueryCancelPending = false; /* ProcDie trumps QueryCancel */
1725 ImmediateInterruptOK = false; /* not idle anymore */
1726 DisableNotifyInterrupt();
1727 elog(FATAL, "This connection has been terminated by the administrator.");
1729 if (QueryCancelPending)
1731 QueryCancelPending = false;
1732 ImmediateInterruptOK = false; /* not idle anymore */
1733 DisableNotifyInterrupt();
1734 elog(ERROR, "Query was canceled.");
1736 /* If we get here, do nothing (probably, QueryCancelPending was reset) */
1741 usage(char *progname)
1743 printf("%s is the PostgreSQL stand-alone backend. It is not\nintended to be used by normal users.\n\n", progname);
1745 printf("Usage:\n %s [OPTION]... [DBNAME]\n\n", progname);
1746 printf("Options:\n");
1747 #ifdef USE_ASSERT_CHECKING
1748 printf(" -A 1|0 enable/disable run-time assert checking\n");
1750 printf(" -B NBUFFERS number of shared buffers (default %d)\n", DEF_NBUFFERS);
1751 printf(" -c NAME=VALUE set run-time parameter\n");
1752 printf(" -d 0-5 debugging level (0 is off)\n");
1753 printf(" -D DATADIR database directory\n");
1754 printf(" -e use European date format\n");
1755 printf(" -E echo query before execution\n");
1756 printf(" -F turn fsync off\n");
1757 printf(" -N do not use newline as interactive query delimiter\n");
1758 printf(" -o FILENAME send stdout and stderr to given file\n");
1759 printf(" -P disable system indexes\n");
1760 printf(" -s show statistics after each query\n");
1761 printf(" -S SORT-MEM set amount of memory for sorts (in kbytes)\n");
1762 printf(" --help show this help, then exit\n");
1763 printf(" --version output version information, then exit\n");
1764 printf("\nDeveloper options:\n");
1765 printf(" -f s|i|n|m|h forbid use of some plan types\n");
1766 printf(" -i do not execute queries\n");
1767 printf(" -O allow system table structure changes\n");
1768 printf(" -t pa|pl|ex show timings after each query\n");
1769 printf(" -W NUM wait NUM seconds to allow attach from a debugger\n");
1770 printf("\nReport bugs to <pgsql-bugs@postgresql.org>.\n");
1775 /* ----------------------------------------------------------------
1777 * postgres main loop -- all backends, interactive or otherwise start here
1779 * argc/argv are the command line arguments to be used. (When being forked
1780 * by the postmaster, these are not the original argv array of the process.)
1781 * username is the (possibly authenticated) PostgreSQL user name to be used
1783 * ----------------------------------------------------------------
1786 PostgresMain(int argc, char *argv[], const char *username)
1789 const char *dbname = NULL;
1790 char *potential_DataDir = NULL;
1795 GucSource gucsource;
1798 StringInfo input_message;
1802 * Catch standard options before doing much else. This even works on
1803 * systems without getopt_long.
1805 if (!IsUnderPostmaster && argc > 1)
1807 if (strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-?") == 0)
1812 if (strcmp(argv[1], "--version") == 0 || strcmp(argv[1], "-V") == 0)
1814 puts("postgres (PostgreSQL) " PG_VERSION);
1820 * initialize globals (already done if under postmaster, but not if
1821 * standalone; cheap enough to do over)
1824 MyProcPid = getpid();
1827 * Fire up essential subsystems: error and memory management
1829 * If we are running under the postmaster, this is done already.
1831 if (!IsUnderPostmaster)
1832 MemoryContextInit();
1834 set_ps_display("startup");
1836 SetProcessingMode(InitProcessing);
1839 * Set default values for command-line options.
1844 if (!IsUnderPostmaster /* when exec || ExecBackend*/)
1846 InitializeGUCOptions();
1847 potential_DataDir = getenv("PGDATA");
1851 * parse command line arguments
1853 * There are now two styles of command line layout for the backend:
1855 * For interactive use (not started from postmaster) the format is
1856 * postgres [switches] [databasename]
1857 * If the databasename is omitted it is taken to be the user name.
1859 * When started from the postmaster, the format is
1860 * postgres [secure switches] -p databasename [insecure switches]
1861 * Switches appearing after -p came from the client (via "options"
1862 * field of connection request). For security reasons we restrict
1863 * what these switches can do.
1867 /* all options are allowed until '-p' */
1869 ctx = PGC_POSTMASTER;
1870 gucsource = PGC_S_ARGV; /* initial switches came from command line */
1872 while ((flag = getopt(argc, argv, "A:B:c:CD:d:Eef:FiNOPo:p:S:st:v:W:x:-:")) != -1)
1876 #ifdef USE_ASSERT_CHECKING
1877 SetConfigOption("debug_assertions", optarg, ctx, gucsource);
1879 elog(WARNING, "Assert checking is not compiled in");
1886 * specify the size of buffer pool
1888 SetConfigOption("shared_buffers", optarg, ctx, gucsource);
1894 * don't print version string
1899 case 'D': /* PGDATA directory */
1901 potential_DataDir = optarg;
1904 case 'd': /* debug level */
1906 debug_flag = atoi(optarg);
1907 /* Set server debugging level. */
1908 if (atoi(optarg) != 0)
1910 char *debugstr = palloc(strlen("debug") + strlen(optarg) + 1);
1912 sprintf(debugstr, "debug%s", optarg);
1913 SetConfigOption("log_min_messages", debugstr, ctx, gucsource);
1919 * -d0 allows user to prevent postmaster debug
1920 * from propagating to backend. It would be nice
1921 * to set it to the postgresql.conf value here.
1923 SetConfigOption("log_min_messages", "notice",
1931 * E - echo the query the user entered
1939 * Use european date formats.
1941 SetConfigOption("datestyle", "euro", ctx, gucsource);
1949 SetConfigOption("fsync", "false", ctx, gucsource);
1955 * f - forbid generation of certain plans
1960 case 's': /* seqscan */
1961 tmp = "enable_seqscan";
1963 case 'i': /* indexscan */
1964 tmp = "enable_indexscan";
1966 case 't': /* tidscan */
1967 tmp = "enable_tidscan";
1969 case 'n': /* nestloop */
1970 tmp = "enable_nestloop";
1972 case 'm': /* mergejoin */
1973 tmp = "enable_mergejoin";
1975 case 'h': /* hashjoin */
1976 tmp = "enable_hashjoin";
1982 SetConfigOption(tmp, "false", ctx, gucsource);
1988 * N - Don't use newline as a query delimiter
1996 * allow system table structure modifications
1998 if (secure) /* XXX safe to allow from client??? */
1999 allowSystemTableMods = true;
2005 * ignore system indexes
2007 if (secure) /* XXX safe to allow from client??? */
2008 IgnoreSystemIndexes(true);
2014 * o - send output (stdout and stderr) to the given file
2017 StrNCpy(OutputFileName, optarg, MAXPGPATH);
2023 * p - special flag passed if backend was forked by a
2030 sscanf(optarg, "%d,%d,", &MyProcPort->sock, &UsedShmemSegID);
2031 /* Grab dbname as last param */
2032 p = strchr(optarg, ',');
2034 p = strchr(p+1, ',');
2036 dbname = strdup(p+1);
2038 dbname = strdup(optarg);
2040 secure = false; /* subsequent switches are NOT
2043 gucsource = PGC_S_CLIENT;
2050 * S - amount of sort memory to use in 1k bytes
2052 SetConfigOption("sort_mem", optarg, ctx, gucsource);
2058 * s - report usage statistics (timings) after each query
2060 SetConfigOption("show_statement_stats", "true", ctx, gucsource);
2065 * tell postgres to report usage statistics (timings) for
2068 * -tpa[rser] = print stats for parser time of each query
2069 * -tpl[anner] = print stats for planner time of each query
2070 * -te[xecutor] = print stats for executor time of each query
2071 * caution: -s can not be used together with -t.
2078 if (optarg[1] == 'a')
2079 tmp = "log_parser_stats";
2080 else if (optarg[1] == 'l')
2081 tmp = "log_planner_stats";
2086 tmp = "show_executor_stats";
2093 SetConfigOption(tmp, "true", ctx, gucsource);
2098 FrontendProtocol = (ProtocolVersion) atoi(optarg);
2104 * wait N seconds to allow attach from a debugger
2106 sleep(atoi(optarg));
2110 #ifdef NOT_USED /* planner/xfunc.h */
2113 * control joey hellerstein's expensive function
2118 elog(WARNING, "only one -x flag is allowed");
2122 if (strcmp(optarg, "off") == 0)
2123 XfuncMode = XFUNC_OFF;
2124 else if (strcmp(optarg, "nor") == 0)
2125 XfuncMode = XFUNC_NOR;
2126 else if (strcmp(optarg, "nopull") == 0)
2127 XfuncMode = XFUNC_NOPULL;
2128 else if (strcmp(optarg, "nopm") == 0)
2129 XfuncMode = XFUNC_NOPM;
2130 else if (strcmp(optarg, "pullall") == 0)
2131 XfuncMode = XFUNC_PULLALL;
2132 else if (strcmp(optarg, "wait") == 0)
2133 XfuncMode = XFUNC_WAIT;
2136 elog(WARNING, "use -x {off,nor,nopull,nopm,pullall,wait}");
2148 ParseLongOption(optarg, &name, &value);
2152 elog(ERROR, "--%s requires argument", optarg);
2154 elog(ERROR, "-c %s requires argument", optarg);
2157 SetConfigOption(name, value, ctx, gucsource);
2171 * -d is not the same as setting
2172 * log_min_messages because it enables other
2175 if (debug_flag >= 1)
2176 SetConfigOption("log_connections", "true", ctx, gucsource);
2177 if (debug_flag >= 2)
2178 SetConfigOption("log_statement", "true", ctx, gucsource);
2179 if (debug_flag >= 3)
2180 SetConfigOption("debug_print_parse", "true", ctx, gucsource);
2181 if (debug_flag >= 4)
2182 SetConfigOption("debug_print_plan", "true", ctx, gucsource);
2183 if (debug_flag >= 5)
2184 SetConfigOption("debug_print_rewritten", "true", ctx, gucsource);
2187 * Process any additional GUC variable settings passed in startup packet.
2189 if (MyProcPort != NULL)
2191 List *gucopts = MyProcPort->guc_options;
2198 name = lfirst(gucopts);
2199 gucopts = lnext(gucopts);
2200 value = lfirst(gucopts);
2201 gucopts = lnext(gucopts);
2202 SetConfigOption(name, value, PGC_BACKEND, PGC_S_CLIENT);
2207 * Post-processing for command line options.
2209 if (log_statement_stats &&
2210 (log_parser_stats || log_planner_stats || log_executor_stats))
2212 elog(WARNING, "Query statistics are disabled because parser, planner, or executor statistics are on.");
2213 SetConfigOption("show_statement_stats", "false", ctx, gucsource);
2216 if (!IsUnderPostmaster)
2218 if (!potential_DataDir)
2220 fprintf(stderr, "%s does not know where to find the database system "
2221 "data. You must specify the directory that contains the "
2222 "database system either by specifying the -D invocation "
2223 "option or by setting the PGDATA environment variable.\n\n",
2227 SetDataDir(potential_DataDir);
2232 read_nondefault_variables();
2236 * Set up signal handlers and masks.
2238 * Note that postmaster blocked all signals before forking child process,
2239 * so there is no race condition whereby we might receive a signal
2240 * before we have set up the handler.
2242 * Also note: it's best not to use any signals that are SIG_IGNored in
2243 * the postmaster. If such a signal arrives before we are able to
2244 * change the handler to non-SIG_IGN, it'll get dropped. Instead,
2245 * make a dummy handler in the postmaster to reserve the signal. (Of
2246 * course, this isn't an issue for signals that are locally generated,
2247 * such as SIGALRM and SIGPIPE.)
2250 pqsignal(SIGHUP, SigHupHandler); /* set flag to read config file */
2251 pqsignal(SIGINT, StatementCancelHandler); /* cancel current query */
2252 pqsignal(SIGTERM, die); /* cancel current query and exit */
2253 pqsignal(SIGQUIT, quickdie); /* hard crash time */
2254 pqsignal(SIGALRM, handle_sig_alarm); /* timeout conditions */
2257 * Ignore failure to write to frontend. Note: if frontend closes
2258 * connection, we will notice it and exit cleanly when control next
2259 * returns to outer loop. This seems safer than forcing exit in the
2260 * midst of output during who-knows-what operation...
2262 pqsignal(SIGPIPE, SIG_IGN);
2263 pqsignal(SIGUSR1, SIG_IGN); /* this signal available for use */
2265 pqsignal(SIGUSR2, Async_NotifyHandler); /* flush also sinval cache */
2266 pqsignal(SIGFPE, FloatExceptionHandler);
2269 * Reset some signals that are accepted by postmaster but not by
2272 pqsignal(SIGCHLD, SIG_DFL); /* system() requires this on some
2277 /* We allow SIGQUIT (quickdie) at all times */
2278 #ifdef HAVE_SIGPROCMASK
2279 sigdelset(&BlockSig, SIGQUIT);
2281 BlockSig &= ~(sigmask(SIGQUIT));
2284 PG_SETMASK(&BlockSig); /* block everything except SIGQUIT */
2287 if (IsUnderPostmaster)
2289 /* noninteractive case: nothing should be left after switches */
2290 if (errs || argc != optind || dbname == NULL)
2292 elog(WARNING, "%s: invalid command line arguments\nTry -? for help.",
2294 proc_exit(0); /* not 1, that causes system-wide
2299 AttachSharedMemoryAndSemaphores();
2304 /* interactive case: database name can be last arg on command line */
2305 if (errs || argc - optind > 1)
2307 elog(WARNING, "%s: invalid command line arguments\nTry -? for help.",
2311 else if (argc - optind == 1)
2312 dbname = argv[optind];
2313 else if ((dbname = username) == NULL)
2315 elog(WARNING, "%s: user name undefined and no database specified",
2321 * On some systems our dynloader code needs the executable's
2322 * pathname. (If under postmaster, this was done already.)
2324 if (FindExec(pg_pathname, argv[0], "postgres") < 0)
2325 elog(FATAL, "%s: could not locate executable, bailing out...",
2329 * Validate we have been given a reasonable-looking DataDir (if
2330 * under postmaster, assume postmaster did this already).
2332 ValidatePgVersion(DataDir);
2335 * Create lockfile for data directory.
2337 if (!CreateDataDirLockFile(DataDir, false))
2344 * Start up xlog for standalone backend, and register to have it
2345 * closed down at exit.
2348 on_shmem_exit(ShutdownXLOG, 0);
2351 * Read any existing FSM cache file, and register to write one out
2355 on_shmem_exit(DumpFreeSpaceMap, 0);
2359 * Set up additional info.
2367 * General initialization.
2369 * NOTE: if you are tempted to add code in this vicinity, consider
2370 * putting it inside InitPostgres() instead. In particular, anything
2371 * that involves database access should be there, not here.
2373 elog(DEBUG2, "InitPostgres");
2374 InitPostgres(dbname, username);
2376 SetProcessingMode(NormalProcessing);
2379 * Send this backend's cancellation info to the frontend.
2381 if (whereToSendOutput == Remote &&
2382 PG_PROTOCOL_MAJOR(FrontendProtocol) >= 2)
2386 pq_beginmessage(&buf, 'K');
2387 pq_sendint(&buf, (int32) MyProcPid, sizeof(int32));
2388 pq_sendint(&buf, (int32) MyCancelKey, sizeof(int32));
2389 pq_endmessage(&buf);
2390 /* Need not flush since ReadyForQuery will do it. */
2393 if (!IsUnderPostmaster)
2395 puts("\nPOSTGRES backend interactive interface ");
2396 puts("$Revision: 1.338 $ $Date: 2003/05/06 23:34:55 $\n");
2400 * Create the memory context we will use in the main loop.
2402 * MessageContext is reset once per iteration of the main loop, ie, upon
2403 * completion of processing of each command message from the client.
2405 MessageContext = AllocSetContextCreate(TopMemoryContext,
2407 ALLOCSET_DEFAULT_MINSIZE,
2408 ALLOCSET_DEFAULT_INITSIZE,
2409 ALLOCSET_DEFAULT_MAXSIZE);
2412 * Tell the statistics collector that we're alive and
2413 * to which database we belong.
2419 * POSTGRES main processing loop begins here
2421 * If an exception is encountered, processing resumes here so we abort
2422 * the current transaction and start a new one.
2425 if (sigsetjmp(Warn_restart, 1) != 0)
2428 * NOTE: if you are tempted to add more code in this if-block,
2429 * consider the probability that it should be in
2430 * AbortTransaction() instead.
2432 * Make sure we're not interrupted while cleaning up. Also forget
2433 * any pending QueryCancel request, since we're aborting anyway.
2434 * Force InterruptHoldoffCount to a known state in case we elog'd
2435 * from inside a holdoff section.
2437 ImmediateInterruptOK = false;
2438 QueryCancelPending = false;
2439 InterruptHoldoffCount = 1;
2440 CritSectionCount = 0; /* should be unnecessary, but... */
2441 disable_sig_alarm(true);
2442 QueryCancelPending = false; /* again in case timeout occurred */
2443 DisableNotifyInterrupt();
2444 debug_query_string = NULL;
2447 * Make sure we are in a valid memory context during recovery.
2449 * We use ErrorContext in hopes that it will have some free space
2450 * even if we're otherwise up against it...
2452 MemoryContextSwitchTo(ErrorContext);
2454 /* Do the recovery */
2455 elog(DEBUG1, "AbortCurrentTransaction");
2456 AbortCurrentTransaction();
2459 * Now return to normal top-level context and clear ErrorContext
2462 MemoryContextSwitchTo(TopMemoryContext);
2463 MemoryContextResetAndDeleteChildren(ErrorContext);
2464 PortalContext = NULL;
2465 QueryContext = NULL;
2468 * Clear flag to indicate that we got out of error recovery mode
2469 * successfully. (Flag was set in elog.c before longjmp().)
2472 xact_started = false;
2475 * If we were handling an extended-query-protocol message,
2476 * initiate skip till next Sync.
2478 if (doing_extended_query_message)
2479 ignore_till_sync = true;
2482 * Exit interrupt holdoff section we implicitly established above.
2484 RESUME_INTERRUPTS();
2487 Warn_restart_ready = true; /* we can now handle elog(ERROR) */
2489 PG_SETMASK(&UnBlockSig);
2491 send_rfq = true; /* initially, or after error */
2494 * Non-error queries loop here.
2500 * At top of loop, reset extended-query-message flag, so that
2501 * any errors encountered in "idle" state don't provoke skip.
2503 doing_extended_query_message = false;
2506 * Release storage left over from prior query cycle, and create a
2507 * new query input buffer in the cleared MessageContext.
2509 MemoryContextSwitchTo(MessageContext);
2510 MemoryContextResetAndDeleteChildren(MessageContext);
2512 input_message = makeStringInfo();
2515 * (1) tell the frontend we're ready for a new query.
2517 * Note: this includes fflush()'ing the last of the prior output.
2521 ReadyForQuery(whereToSendOutput);
2526 * Tell the statistics collector what we've collected
2530 pgstat_report_tabstat();
2532 if (IsTransactionBlock())
2534 set_ps_display("idle in transaction");
2535 pgstat_report_activity("<IDLE> in transaction");
2539 set_ps_display("idle");
2540 pgstat_report_activity("<IDLE>");
2544 * (2) deal with pending asynchronous NOTIFY from other backends,
2545 * and enable async.c's signal handler to execute NOTIFY directly.
2546 * Then set up other stuff needed before blocking for input.
2548 QueryCancelPending = false; /* forget any earlier CANCEL
2551 EnableNotifyInterrupt();
2553 /* Allow "die" interrupt to be processed while waiting */
2554 ImmediateInterruptOK = true;
2555 /* and don't forget to detect one that already arrived */
2556 QueryCancelPending = false;
2557 CHECK_FOR_INTERRUPTS();
2560 * (3) read a command (loop blocks here)
2562 firstchar = ReadCommand(input_message);
2565 * (4) disable async signal conditions again.
2567 ImmediateInterruptOK = false;
2568 QueryCancelPending = false; /* forget any CANCEL signal */
2570 DisableNotifyInterrupt();
2573 * (5) check for any other interesting events that happened while
2579 ProcessConfigFile(PGC_SIGHUP);
2583 * (6) process the command. But ignore it if we're skipping till Sync.
2585 if (ignore_till_sync)
2590 case 'Q': /* simple query */
2592 const char *query_string;
2594 query_string = pq_getmsgstring(input_message);
2595 pq_getmsgend(input_message);
2597 exec_simple_query(query_string);
2603 case 'P': /* parse */
2605 const char *stmt_name;
2606 const char *query_string;
2608 Oid *paramTypes = NULL;
2610 stmt_name = pq_getmsgstring(input_message);
2611 query_string = pq_getmsgstring(input_message);
2612 numParams = pq_getmsgint(input_message, 4);
2617 paramTypes = (Oid *) palloc(numParams * sizeof(Oid));
2618 for (i = 0; i < numParams; i++)
2619 paramTypes[i] = pq_getmsgint(input_message, 4);
2621 pq_getmsgend(input_message);
2623 exec_parse_message(query_string, stmt_name,
2624 paramTypes, numParams);
2628 case 'B': /* bind */
2630 * this message is complex enough that it seems best to put
2631 * the field extraction out-of-line
2633 exec_bind_message(input_message);
2636 case 'E': /* execute */
2638 const char *portal_name;
2642 portal_name = pq_getmsgstring(input_message);
2643 is_binary = pq_getmsgbyte(input_message);
2644 max_rows = pq_getmsgint(input_message, 4);
2645 pq_getmsgend(input_message);
2647 exec_execute_message(portal_name, is_binary, max_rows);
2651 case 'F': /* fastpath function call */
2652 /* Tell the collector what we're doing */
2653 pgstat_report_activity("<FASTPATH> function call");
2655 /* start an xact for this function invocation */
2656 start_xact_command();
2658 if (HandleFunctionRequest(input_message) == EOF)
2660 /* lost frontend connection during F message input */
2663 * Reset whereToSendOutput to prevent elog from
2664 * attempting to send any more messages to client.
2666 if (whereToSendOutput == Remote)
2667 whereToSendOutput = None;
2672 /* commit the function-invocation transaction */
2673 finish_xact_command(false);
2678 case 'C': /* close */
2681 const char *close_target;
2683 close_type = pq_getmsgbyte(input_message);
2684 close_target = pq_getmsgstring(input_message);
2685 pq_getmsgend(input_message);
2690 if (close_target[0] != '\0')
2691 DropPreparedStatement(close_target, false);
2694 /* special-case the unnamed statement */
2695 unnamed_stmt_pstmt = NULL;
2696 if (unnamed_stmt_context)
2698 DropDependentPortals(unnamed_stmt_context);
2699 MemoryContextDelete(unnamed_stmt_context);
2701 unnamed_stmt_context = NULL;
2708 portal = GetPortalByName(close_target);
2709 if (PortalIsValid(portal))
2710 PortalDrop(portal, false);
2714 elog(ERROR, "Invalid Close message subtype %d",
2719 if (whereToSendOutput == Remote)
2720 pq_putemptymessage('3'); /* CloseComplete */
2724 case 'D': /* describe */
2727 const char *describe_target;
2729 describe_type = pq_getmsgbyte(input_message);
2730 describe_target = pq_getmsgstring(input_message);
2731 pq_getmsgend(input_message);
2733 switch (describe_type)
2736 exec_describe_statement_message(describe_target);
2739 exec_describe_portal_message(describe_target);
2742 elog(ERROR, "Invalid Describe message subtype %d",
2749 case 'H': /* flush */
2750 pq_getmsgend(input_message);
2751 if (whereToSendOutput == Remote)
2755 case 'S': /* sync */
2756 pq_getmsgend(input_message);
2757 finish_xact_command(false);
2762 * 'X' means that the frontend is closing down the socket.
2763 * EOF means unexpected loss of frontend connection.
2764 * Either way, perform normal shutdown.
2770 * Reset whereToSendOutput to prevent elog from attempting
2771 * to send any more messages to client.
2773 if (whereToSendOutput == Remote)
2774 whereToSendOutput = None;
2777 * NOTE: if you are tempted to add more code here, DON'T!
2778 * Whatever you had in mind to do should be set up as an
2779 * on_proc_exit or on_shmem_exit callback, instead.
2780 * Otherwise it will fail to be called during other
2781 * backend-shutdown scenarios.
2785 case 'd': /* copy data */
2786 case 'c': /* copy done */
2787 case 'f': /* copy fail */
2789 * Accept but ignore these messages, per protocol spec;
2790 * we probably got here because a COPY failed, and the
2791 * frontend is still sending data.
2796 elog(FATAL, "Socket command type %c unknown", firstchar);
2799 #ifdef MEMORY_CONTEXT_CHECKING
2802 * Check all memory after each backend loop. This is a rather
2803 * weird place to do it, perhaps.
2805 MemoryContextCheck(TopMemoryContext);
2807 } /* end of input-reading loop */
2809 /* can't get here because the above loop never exits */
2812 return 1; /* keep compiler quiet */
2815 #ifndef HAVE_GETRUSAGE
2816 #include "rusagestub.h"
2818 #include <sys/resource.h>
2819 #endif /* HAVE_GETRUSAGE */
2821 struct rusage Save_r;
2822 struct timeval Save_t;
2827 getrusage(RUSAGE_SELF, &Save_r);
2828 gettimeofday(&Save_t, NULL);
2830 /* ResetTupleCount(); */
2834 ShowUsage(const char *title)
2837 struct timeval user,
2839 struct timeval elapse_t;
2843 getrusage(RUSAGE_SELF, &r);
2844 gettimeofday(&elapse_t, NULL);
2845 memcpy((char *) &user, (char *) &r.ru_utime, sizeof(user));
2846 memcpy((char *) &sys, (char *) &r.ru_stime, sizeof(sys));
2847 if (elapse_t.tv_usec < Save_t.tv_usec)
2850 elapse_t.tv_usec += 1000000;
2852 if (r.ru_utime.tv_usec < Save_r.ru_utime.tv_usec)
2854 r.ru_utime.tv_sec--;
2855 r.ru_utime.tv_usec += 1000000;
2857 if (r.ru_stime.tv_usec < Save_r.ru_stime.tv_usec)
2859 r.ru_stime.tv_sec--;
2860 r.ru_stime.tv_usec += 1000000;
2864 * the only stats we don't show here are for memory usage -- i can't
2865 * figure out how to interpret the relevant fields in the rusage
2866 * struct, and they change names across o/s platforms, anyway. if you
2867 * can figure out what the entries mean, you can somehow extract
2868 * resident set size, shared text size, and unshared data and stack
2871 initStringInfo(&str);
2873 appendStringInfo(&str, "! system usage stats:\n");
2874 appendStringInfo(&str,
2875 "!\t%ld.%06ld elapsed %ld.%06ld user %ld.%06ld system sec\n",
2876 (long) (elapse_t.tv_sec - Save_t.tv_sec),
2877 (long) (elapse_t.tv_usec - Save_t.tv_usec),
2878 (long) (r.ru_utime.tv_sec - Save_r.ru_utime.tv_sec),
2879 (long) (r.ru_utime.tv_usec - Save_r.ru_utime.tv_usec),
2880 (long) (r.ru_stime.tv_sec - Save_r.ru_stime.tv_sec),
2881 (long) (r.ru_stime.tv_usec - Save_r.ru_stime.tv_usec));
2882 appendStringInfo(&str,
2883 "!\t[%ld.%06ld user %ld.%06ld sys total]\n",
2885 (long) user.tv_usec,
2887 (long) sys.tv_usec);
2888 /* BeOS has rusage but only has some fields, and not these... */
2889 #if defined(HAVE_GETRUSAGE)
2890 appendStringInfo(&str,
2891 "!\t%ld/%ld [%ld/%ld] filesystem blocks in/out\n",
2892 r.ru_inblock - Save_r.ru_inblock,
2893 /* they only drink coffee at dec */
2894 r.ru_oublock - Save_r.ru_oublock,
2895 r.ru_inblock, r.ru_oublock);
2896 appendStringInfo(&str,
2897 "!\t%ld/%ld [%ld/%ld] page faults/reclaims, %ld [%ld] swaps\n",
2898 r.ru_majflt - Save_r.ru_majflt,
2899 r.ru_minflt - Save_r.ru_minflt,
2900 r.ru_majflt, r.ru_minflt,
2901 r.ru_nswap - Save_r.ru_nswap,
2903 appendStringInfo(&str,
2904 "!\t%ld [%ld] signals rcvd, %ld/%ld [%ld/%ld] messages rcvd/sent\n",
2905 r.ru_nsignals - Save_r.ru_nsignals,
2907 r.ru_msgrcv - Save_r.ru_msgrcv,
2908 r.ru_msgsnd - Save_r.ru_msgsnd,
2909 r.ru_msgrcv, r.ru_msgsnd);
2910 appendStringInfo(&str,
2911 "!\t%ld/%ld [%ld/%ld] voluntary/involuntary context switches\n",
2912 r.ru_nvcsw - Save_r.ru_nvcsw,
2913 r.ru_nivcsw - Save_r.ru_nivcsw,
2914 r.ru_nvcsw, r.ru_nivcsw);
2915 #endif /* HAVE_GETRUSAGE */
2917 bufusage = ShowBufferUsage();
2918 appendStringInfo(&str, "! buffer usage stats:\n%s", bufusage);
2921 /* remove trailing newline */
2922 if (str.data[str.len - 1] == '\n')
2923 str.data[--str.len] = '\0';
2925 elog(LOG, "%s\n%s", title, str.data);