1 /*-------------------------------------------------------------------------
4 * POSTGRES C Backend Interface
6 * Portions Copyright (c) 1996-2003, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
11 * $PostgreSQL: pgsql/src/backend/tcop/postgres.c,v 1.400 2004/04/19 17:42:58 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"
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 /* flag for logging end of session */
88 bool Log_disconnections = false;
90 LogStmtLevel log_statement = LOGSTMT_NONE;
93 * Flags for expensive function optimization -- JMH 3/9/92
97 /* GUC variable for maximum stack depth (measured in kilobytes) */
98 int max_stack_depth = 2048;
106 /* max_stack_depth converted to bytes for speed of checking */
107 static int max_stack_depth_bytes = 2048*1024;
109 /* stack base pointer (initialized by PostgresMain) */
110 static char *stack_base_ptr = NULL;
114 * Flag to mark SIGHUP. Whenever the main loop comes around it
115 * will reread the configuration file. (Better than doing the
116 * reading in the signal handler, ey?)
118 static volatile bool got_SIGHUP = false;
121 * Flag to keep track of whether we have started a transaction.
122 * For extended query protocol this has to be remembered across messages.
124 static bool xact_started = false;
127 * Flags to implement skip-till-Sync-after-error behavior for messages of
128 * the extended query protocol.
130 static bool doing_extended_query_message = false;
131 static bool ignore_till_sync = false;
134 * If an unnamed prepared statement exists, it's stored here.
135 * We keep it separate from the hashtable kept by commands/prepare.c
136 * in order to reduce overhead for short-lived queries.
138 static MemoryContext unnamed_stmt_context = NULL;
139 static PreparedStatement *unnamed_stmt_pstmt = NULL;
142 static bool EchoQuery = false; /* default don't echo */
145 * people who want to use EOF should #define DONTUSENEWLINE in
148 #ifndef TCOP_DONTUSENEWLINE
149 static int UseNewLine = 1; /* Use newlines query delimiters (the
153 static int UseNewLine = 0; /* Use EOF as query delimiters */
154 #endif /* TCOP_DONTUSENEWLINE */
157 /* ----------------------------------------------------------------
158 * decls for routines only used in this file
159 * ----------------------------------------------------------------
161 static int InteractiveBackend(StringInfo inBuf);
162 static int SocketBackend(StringInfo inBuf);
163 static int ReadCommand(StringInfo inBuf);
164 static void start_xact_command(void);
165 static void finish_xact_command(void);
166 static void SigHupHandler(SIGNAL_ARGS);
167 static void FloatExceptionHandler(SIGNAL_ARGS);
168 static void log_disconnections(int code, Datum arg);
171 /* ----------------------------------------------------------------
172 * routines to obtain user input
173 * ----------------------------------------------------------------
177 * InteractiveBackend() is called for user interactive connections
179 * the string entered by the user is placed in its parameter inBuf,
180 * and we act like a Q message was received.
182 * EOF is returned if end-of-file input is seen; time to shut down.
187 InteractiveBackend(StringInfo inBuf)
189 int c; /* character read from getc() */
190 bool end = false; /* end-of-input flag */
191 bool backslashSeen = false; /* have we seen a \ ? */
194 * display a prompt and obtain input from the user
199 /* Reset inBuf to empty */
201 inBuf->data[0] = '\0';
209 * if we are using \n as a delimiter, then read characters
212 while ((c = getc(stdin)) != EOF)
218 /* discard backslash from inBuf */
219 inBuf->data[--inBuf->len] = '\0';
220 backslashSeen = false;
225 /* keep the newline character */
226 appendStringInfoChar(inBuf, '\n');
231 backslashSeen = true;
233 backslashSeen = false;
235 appendStringInfoChar(inBuf, (char) c);
244 * otherwise read characters until EOF.
246 while ((c = getc(stdin)) != EOF)
247 appendStringInfoChar(inBuf, (char) c);
257 * otherwise we have a user query so process it.
262 /* Add '\0' to make it look the same as message case. */
263 appendStringInfoChar(inBuf, (char) '\0');
266 * if the query echo flag was given, print the query..
269 printf("statement: %s\n", inBuf->data);
276 * SocketBackend() Is called for frontend-backend connections
278 * Returns the message type code, and loads message body data into inBuf.
280 * EOF is returned if the connection is lost.
284 SocketBackend(StringInfo inBuf)
289 * Get message type code from the frontend.
291 qtype = pq_getbyte();
293 if (qtype == EOF) /* frontend disconnected */
296 (errcode(ERRCODE_PROTOCOL_VIOLATION),
297 errmsg("unexpected EOF on client connection")));
302 * Validate message type code before trying to read body; if we have
303 * lost sync, better to say "command unknown" than to run out of
304 * memory because we used garbage as a length word.
306 * This also gives us a place to set the doing_extended_query_message
307 * flag as soon as possible.
311 case 'Q': /* simple query */
312 doing_extended_query_message = false;
313 if (PG_PROTOCOL_MAJOR(FrontendProtocol) < 3)
315 /* old style without length word; convert */
316 if (pq_getstring(inBuf))
319 (errcode(ERRCODE_PROTOCOL_VIOLATION),
320 errmsg("unexpected EOF on client connection")));
326 case 'F': /* fastpath function call */
327 /* we let fastpath.c cope with old-style input of this */
328 doing_extended_query_message = false;
331 case 'X': /* terminate */
332 doing_extended_query_message = false;
333 ignore_till_sync = false;
337 case 'C': /* close */
338 case 'D': /* describe */
339 case 'E': /* execute */
340 case 'H': /* flush */
341 case 'P': /* parse */
342 doing_extended_query_message = true;
343 /* these are only legal in protocol 3 */
344 if (PG_PROTOCOL_MAJOR(FrontendProtocol) < 3)
346 (errcode(ERRCODE_PROTOCOL_VIOLATION),
347 errmsg("invalid frontend message type %d", qtype)));
351 /* stop any active skip-till-Sync */
352 ignore_till_sync = false;
353 /* mark not-extended, so that a new error doesn't begin skip */
354 doing_extended_query_message = false;
355 /* only legal in protocol 3 */
356 if (PG_PROTOCOL_MAJOR(FrontendProtocol) < 3)
358 (errcode(ERRCODE_PROTOCOL_VIOLATION),
359 errmsg("invalid frontend message type %d", qtype)));
362 case 'd': /* copy data */
363 case 'c': /* copy done */
364 case 'f': /* copy fail */
365 doing_extended_query_message = false;
366 /* these are only legal in protocol 3 */
367 if (PG_PROTOCOL_MAJOR(FrontendProtocol) < 3)
369 (errcode(ERRCODE_PROTOCOL_VIOLATION),
370 errmsg("invalid frontend message type %d", qtype)));
376 * Otherwise we got garbage from the frontend. We treat this
377 * as fatal because we have probably lost message boundary
378 * sync, and there's no good way to recover.
381 (errcode(ERRCODE_PROTOCOL_VIOLATION),
382 errmsg("invalid frontend message type %d", qtype)));
387 * In protocol version 3, all frontend messages have a length word
388 * next after the type code; we can read the message contents
389 * independently of the type.
391 if (PG_PROTOCOL_MAJOR(FrontendProtocol) >= 3)
393 if (pq_getmessage(inBuf, 0))
394 return EOF; /* suitable message already logged */
401 * ReadCommand reads a command from either the frontend or
402 * standard input, places it in inBuf, and returns the
403 * message type code (first byte of the message).
404 * EOF is returned if end of file.
408 ReadCommand(StringInfo inBuf)
412 if (whereToSendOutput == Remote)
413 result = SocketBackend(inBuf);
415 result = InteractiveBackend(inBuf);
421 * Parse a query string and pass it through the rewriter.
423 * A list of Query nodes is returned, since the string might contain
424 * multiple queries and/or the rewriter might expand one query to several.
426 * NOTE: this routine is no longer used for processing interactive queries,
427 * but it is still needed for parsing of SQL function bodies.
430 pg_parse_and_rewrite(const char *query_string, /* string to execute */
431 Oid *paramTypes, /* parameter types */
432 int numParams) /* number of parameters */
434 List *raw_parsetree_list;
435 List *querytree_list;
439 * (1) parse the request string into a list of raw parse trees.
441 raw_parsetree_list = pg_parse_query(query_string);
444 * (2) Do parse analysis and rule rewrite.
446 querytree_list = NIL;
447 foreach(list_item, raw_parsetree_list)
449 Node *parsetree = (Node *) lfirst(list_item);
451 querytree_list = nconc(querytree_list,
452 pg_analyze_and_rewrite(parsetree,
457 return querytree_list;
461 * Do raw parsing (only).
463 * A list of parsetrees is returned, since there might be multiple
464 * commands in the given string.
466 * NOTE: for interactive queries, it is important to keep this routine
467 * separate from the analysis & rewrite stages. Analysis and rewriting
468 * cannot be done in an aborted transaction, since they require access to
469 * database tables. So, we rely on the raw parser to determine whether
470 * we've seen a COMMIT or ABORT command; when we are in abort state, other
471 * commands are not processed any further than the raw parse stage.
474 pg_parse_query(const char *query_string)
476 List *raw_parsetree_list,
479 if (log_statement == LOGSTMT_ALL)
481 (errmsg("statement: %s", query_string)));
483 if (log_parser_stats)
486 raw_parsetree_list = raw_parser(query_string);
488 /* do log_statement tests for mod and ddl */
489 if (log_statement == LOGSTMT_MOD ||
490 log_statement == LOGSTMT_DDL)
492 foreach(parsetree_item, raw_parsetree_list)
494 Node *parsetree = (Node *) lfirst(parsetree_item);
495 const char *commandTag;
497 if (IsA(parsetree, ExplainStmt) &&
498 ((ExplainStmt *)parsetree)->analyze)
499 parsetree = (Node *)(((ExplainStmt *)parsetree)->query);
501 if (IsA(parsetree, PrepareStmt))
502 parsetree = (Node *)(((PrepareStmt *)parsetree)->query);
504 if (IsA(parsetree, SelectStmt))
505 continue; /* optimization for frequent command */
507 if (log_statement == LOGSTMT_MOD &&
508 (IsA(parsetree, InsertStmt) ||
509 IsA(parsetree, UpdateStmt) ||
510 IsA(parsetree, DeleteStmt) ||
511 IsA(parsetree, TruncateStmt) ||
512 (IsA(parsetree, CopyStmt) &&
513 ((CopyStmt *)parsetree)->is_from))) /* COPY FROM */
516 (errmsg("statement: %s", query_string)));
519 commandTag = CreateCommandTag(parsetree);
520 if (strncmp(commandTag, "CREATE ", strlen("CREATE ")) == 0 ||
521 strncmp(commandTag, "ALTER ", strlen("ALTER ")) == 0 ||
522 strncmp(commandTag, "DROP ", strlen("DROP ")) == 0 ||
523 IsA(parsetree, GrantStmt) || /* GRANT or REVOKE */
524 IsA(parsetree, CommentStmt))
527 (errmsg("statement: %s", query_string)));
533 if (log_parser_stats)
534 ShowUsage("PARSER STATISTICS");
536 return raw_parsetree_list;
540 * Given a raw parsetree (gram.y output), and optionally information about
541 * types of parameter symbols ($n), perform parse analysis and rule rewriting.
543 * A list of Query nodes is returned, since either the analyzer or the
544 * rewriter might expand one query to several.
546 * NOTE: for reasons mentioned above, this must be separate from raw parsing.
549 pg_analyze_and_rewrite(Node *parsetree, Oid *paramTypes, int numParams)
551 List *querytree_list;
554 * (1) Perform parse analysis.
556 if (log_parser_stats)
559 querytree_list = parse_analyze(parsetree, paramTypes, numParams);
561 if (log_parser_stats)
562 ShowUsage("PARSE ANALYSIS STATISTICS");
565 * (2) Rewrite the queries, as necessary
567 querytree_list = pg_rewrite_queries(querytree_list);
569 return querytree_list;
573 * Perform rewriting of a list of queries produced by parse analysis.
576 pg_rewrite_queries(List *querytree_list)
578 List *new_list = NIL;
581 if (log_parser_stats)
585 * rewritten queries are collected in new_list. Note there may be
586 * more or fewer than in the original list.
588 foreach(list_item, querytree_list)
590 Query *querytree = (Query *) lfirst(list_item);
592 if (Debug_print_parse)
593 elog_node_display(DEBUG1, "parse tree", querytree,
596 if (querytree->commandType == CMD_UTILITY)
598 /* don't rewrite utilities, just dump 'em into new_list */
599 new_list = lappend(new_list, querytree);
603 /* rewrite regular queries */
604 List *rewritten = QueryRewrite(querytree);
606 new_list = nconc(new_list, rewritten);
610 querytree_list = new_list;
612 if (log_parser_stats)
613 ShowUsage("REWRITER STATISTICS");
615 #ifdef COPY_PARSE_PLAN_TREES
618 * Optional debugging check: pass querytree output through
621 new_list = (List *) copyObject(querytree_list);
622 /* This checks both copyObject() and the equal() routines... */
623 if (!equal(new_list, querytree_list))
624 elog(WARNING, "copyObject() failed to produce an equal parse tree");
626 querytree_list = new_list;
629 if (Debug_print_rewritten)
630 elog_node_display(DEBUG1, "rewritten parse tree", querytree_list,
633 return querytree_list;
637 /* Generate a plan for a single already-rewritten query. */
639 pg_plan_query(Query *querytree)
643 /* Utility commands have no plans. */
644 if (querytree->commandType == CMD_UTILITY)
647 if (log_planner_stats)
650 /* call the optimizer */
651 plan = planner(querytree, false, 0);
653 if (log_planner_stats)
654 ShowUsage("PLANNER STATISTICS");
656 #ifdef COPY_PARSE_PLAN_TREES
657 /* Optional debugging check: pass plan output through copyObject() */
659 Plan *new_plan = (Plan *) copyObject(plan);
662 * equal() currently does not have routines to compare Plan nodes,
663 * so don't try to test equality here. Perhaps fix someday?
666 /* This checks both copyObject() and the equal() routines... */
667 if (!equal(new_plan, plan))
668 elog(WARNING, "copyObject() failed to produce an equal plan tree");
676 * Print plan if debugging.
678 if (Debug_print_plan)
679 elog_node_display(DEBUG1, "plan", plan, Debug_pretty_print);
685 * Generate plans for a list of already-rewritten queries.
687 * If needSnapshot is TRUE, we haven't yet set a snapshot for the current
688 * query. A snapshot must be set before invoking the planner, since it
689 * might try to evaluate user-defined functions. But we must not set a
690 * snapshot if the list contains only utility statements, because some
691 * utility statements depend on not having frozen the snapshot yet.
692 * (We assume that such statements cannot appear together with plannable
693 * statements in the rewriter's output.)
696 pg_plan_queries(List *querytrees, bool needSnapshot)
698 List *plan_list = NIL;
701 foreach(query_list, querytrees)
703 Query *query = (Query *) lfirst(query_list);
706 if (query->commandType == CMD_UTILITY)
708 /* Utility commands have no plans. */
716 needSnapshot = false;
718 plan = pg_plan_query(query);
721 plan_list = lappend(plan_list, plan);
731 * Execute a "simple Query" protocol message.
734 exec_simple_query(const char *query_string)
736 CommandDest dest = whereToSendOutput;
737 MemoryContext oldcontext;
738 List *parsetree_list,
740 struct timeval start_t,
742 bool save_log_duration = log_duration;
743 int save_log_min_duration_statement = log_min_duration_statement;
744 bool save_log_statement_stats = log_statement_stats;
747 * Report query to various monitoring facilities.
749 debug_query_string = query_string;
751 pgstat_report_activity(query_string);
754 * We use save_log_* so "SET log_duration = true" and "SET
755 * log_min_duration_statement = true" don't report incorrect time
756 * because gettimeofday() wasn't called. Similarly,
757 * log_statement_stats has to be captured once.
759 if (save_log_duration || save_log_min_duration_statement != -1)
760 gettimeofday(&start_t, NULL);
762 if (save_log_statement_stats)
766 * Start up a transaction command. All queries generated by the
767 * query_string will be in this same command block, *unless* we find a
768 * BEGIN/COMMIT/ABORT statement; we have to force a new xact command
769 * after one of those, else bad things will happen in xact.c. (Note
770 * that this will normally change current memory context.)
772 start_xact_command();
775 * Zap any pre-existing unnamed statement. (While not strictly
776 * necessary, it seems best to define simple-Query mode as if it used
777 * the unnamed statement and portal; this ensures we recover any
778 * storage used by prior unnamed operations.)
780 unnamed_stmt_pstmt = NULL;
781 if (unnamed_stmt_context)
783 DropDependentPortals(unnamed_stmt_context);
784 MemoryContextDelete(unnamed_stmt_context);
786 unnamed_stmt_context = NULL;
789 * Switch to appropriate context for constructing parsetrees.
791 oldcontext = MemoryContextSwitchTo(MessageContext);
793 QueryContext = CurrentMemoryContext;
796 * Do basic parsing of the query or queries (this should be safe even
797 * if we are in aborted transaction state!)
799 parsetree_list = pg_parse_query(query_string);
802 * Switch back to transaction context to enter the loop.
804 MemoryContextSwitchTo(oldcontext);
807 * Run through the raw parsetree(s) and process each one.
809 foreach(parsetree_item, parsetree_list)
811 Node *parsetree = (Node *) lfirst(parsetree_item);
812 const char *commandTag;
813 char completionTag[COMPLETION_TAG_BUFSIZE];
814 List *querytree_list,
817 DestReceiver *receiver;
821 * Get the command name for use in status display (it also becomes
822 * the default completion tag, down inside PortalRun). Set
823 * ps_status and do any special start-of-SQL-command processing
824 * needed by the destination.
826 commandTag = CreateCommandTag(parsetree);
828 set_ps_display(commandTag);
830 BeginCommand(commandTag, dest);
833 * If we are in an aborted transaction, reject all commands except
834 * COMMIT/ABORT. It is important that this test occur before we
835 * try to do parse analysis, rewrite, or planning, since all those
836 * phases try to do database accesses, which may fail in abort
837 * state. (It might be safe to allow some additional utility
838 * commands in this state, but not many...)
840 if (IsAbortedTransactionBlockState())
842 bool allowit = false;
844 if (IsA(parsetree, TransactionStmt))
846 TransactionStmt *stmt = (TransactionStmt *) parsetree;
848 if (stmt->kind == TRANS_STMT_COMMIT ||
849 stmt->kind == TRANS_STMT_ROLLBACK)
855 (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
856 errmsg("current transaction is aborted, "
857 "commands ignored until end of transaction block")));
860 /* Make sure we are in a transaction command */
861 start_xact_command();
863 /* If we got a cancel signal in parsing or prior command, quit */
864 CHECK_FOR_INTERRUPTS();
867 * OK to analyze, rewrite, and plan this query.
869 * Switch to appropriate context for constructing querytrees (again,
870 * these must outlive the execution context).
872 oldcontext = MemoryContextSwitchTo(MessageContext);
874 querytree_list = pg_analyze_and_rewrite(parsetree, NULL, 0);
876 plantree_list = pg_plan_queries(querytree_list, true);
878 /* If we got a cancel signal in analysis or planning, quit */
879 CHECK_FOR_INTERRUPTS();
882 * Create unnamed portal to run the query or queries in. If there
883 * already is one, silently drop it.
885 portal = CreatePortal("", true, true);
887 PortalDefineQuery(portal,
895 * Start the portal. No parameters here.
897 PortalStart(portal, NULL);
900 * Select the appropriate output format: text unless we are doing
901 * a FETCH from a binary cursor. (Pretty grotty to have to do
902 * this here --- but it avoids grottiness in other places. Ah,
903 * the joys of backward compatibility...)
905 format = 0; /* TEXT is default */
906 if (IsA(parsetree, FetchStmt))
908 FetchStmt *stmt = (FetchStmt *) parsetree;
912 Portal fportal = GetPortalByName(stmt->portalname);
914 if (PortalIsValid(fportal) &&
915 (fportal->cursorOptions & CURSOR_OPT_BINARY))
916 format = 1; /* BINARY */
919 PortalSetResultFormat(portal, 1, &format);
922 * Now we can create the destination receiver object.
924 receiver = CreateDestReceiver(dest, portal);
927 * Switch back to transaction context for execution.
929 MemoryContextSwitchTo(oldcontext);
932 * Run the portal to completion, and then drop it (and the
935 (void) PortalRun(portal,
941 (*receiver->rDestroy) (receiver);
943 PortalDrop(portal, false);
945 if (IsA(parsetree, TransactionStmt))
948 * If this was a transaction control statement, commit it. We
949 * will start a new xact command for the next command (if
952 finish_xact_command();
954 else if (lnext(parsetree_item) == NIL)
957 * If this is the last parsetree of the query string, close
958 * down transaction statement before reporting
959 * command-complete. This is so that any end-of-transaction
960 * errors are reported before the command-complete message is
961 * issued, to avoid confusing clients who will expect either a
962 * command-complete message or an error, not one and then the
963 * other. But for compatibility with historical Postgres
964 * behavior, we do not force a transaction boundary between
965 * queries appearing in a single query string.
967 finish_xact_command();
972 * We need a CommandCounterIncrement after every query, except
973 * those that start or end a transaction block.
975 CommandCounterIncrement();
979 * Tell client that we're done with this query. Note we emit
980 * exactly one EndCommand report for each raw parsetree, thus one
981 * for each SQL command the client sent, regardless of rewriting.
982 * (But a command aborted by error will not send an EndCommand
985 EndCommand(completionTag, dest);
986 } /* end loop over parsetrees */
989 * Close down transaction statement, if one is open.
991 finish_xact_command();
994 * If there were no parsetrees, return EmptyQueryResponse message.
1002 * Combine processing here as we need to calculate the query duration
1003 * in both instances.
1005 if (save_log_duration || save_log_min_duration_statement != -1)
1009 gettimeofday(&stop_t, NULL);
1010 if (stop_t.tv_usec < start_t.tv_usec)
1013 stop_t.tv_usec += 1000000;
1015 usecs = (long) (stop_t.tv_sec - start_t.tv_sec) * 1000000 + (long) (stop_t.tv_usec - start_t.tv_usec);
1017 if (save_log_duration)
1019 (errmsg("duration: %ld.%03ld ms",
1020 (long) ((stop_t.tv_sec - start_t.tv_sec) * 1000 +
1021 (stop_t.tv_usec - start_t.tv_usec) / 1000),
1022 (long) (stop_t.tv_usec - start_t.tv_usec) % 1000)));
1025 * Output a duration_statement to the log if the query has exceeded
1026 * the min duration, or if we are to print all durations.
1028 if (save_log_min_duration_statement == 0 ||
1029 (save_log_min_duration_statement > 0 &&
1030 usecs >= save_log_min_duration_statement * 1000))
1032 (errmsg("duration: %ld.%03ld ms statement: %s",
1033 (long) ((stop_t.tv_sec - start_t.tv_sec) * 1000 +
1034 (stop_t.tv_usec - start_t.tv_usec) / 1000),
1035 (long) (stop_t.tv_usec - start_t.tv_usec) % 1000,
1039 if (save_log_statement_stats)
1040 ShowUsage("QUERY STATISTICS");
1042 debug_query_string = NULL;
1046 * exec_parse_message
1048 * Execute a "Parse" protocol message.
1051 exec_parse_message(const char *query_string, /* string to execute */
1052 const char *stmt_name, /* name for prepared stmt */
1053 Oid *paramTypes, /* parameter types */
1054 int numParams) /* number of parameters */
1056 MemoryContext oldcontext;
1057 List *parsetree_list;
1058 const char *commandTag;
1059 List *querytree_list,
1063 bool save_log_statement_stats = log_statement_stats;
1066 * Report query to various monitoring facilities.
1068 debug_query_string = query_string;
1070 pgstat_report_activity(query_string);
1072 set_ps_display("PARSE");
1074 if (save_log_statement_stats)
1078 * Start up a transaction command so we can run parse analysis etc.
1079 * (Note that this will normally change current memory context.)
1080 * Nothing happens if we are already in one.
1082 start_xact_command();
1085 * Switch to appropriate context for constructing parsetrees.
1087 * We have two strategies depending on whether the prepared statement is
1088 * named or not. For a named prepared statement, we do parsing in
1089 * MessageContext and copy the finished trees into the prepared
1090 * statement's private context; then the reset of MessageContext
1091 * releases temporary space used by parsing and planning. For an
1092 * unnamed prepared statement, we assume the statement isn't going to
1093 * hang around long, so getting rid of temp space quickly is probably
1094 * not worth the costs of copying parse/plan trees. So in this case,
1095 * we set up a special context for the unnamed statement, and do all
1096 * the parsing/planning therein.
1098 is_named = (stmt_name[0] != '\0');
1101 /* Named prepared statement --- parse in MessageContext */
1102 oldcontext = MemoryContextSwitchTo(MessageContext);
1106 /* Unnamed prepared statement --- release any prior unnamed stmt */
1107 unnamed_stmt_pstmt = NULL;
1108 if (unnamed_stmt_context)
1110 DropDependentPortals(unnamed_stmt_context);
1111 MemoryContextDelete(unnamed_stmt_context);
1113 unnamed_stmt_context = NULL;
1114 /* create context for parsing/planning */
1115 unnamed_stmt_context =
1116 AllocSetContextCreate(TopMemoryContext,
1117 "unnamed prepared statement",
1118 ALLOCSET_DEFAULT_MINSIZE,
1119 ALLOCSET_DEFAULT_INITSIZE,
1120 ALLOCSET_DEFAULT_MAXSIZE);
1121 oldcontext = MemoryContextSwitchTo(unnamed_stmt_context);
1124 QueryContext = CurrentMemoryContext;
1127 * Do basic parsing of the query or queries (this should be safe even
1128 * if we are in aborted transaction state!)
1130 parsetree_list = pg_parse_query(query_string);
1133 * We only allow a single user statement in a prepared statement. This
1134 * is mainly to keep the protocol simple --- otherwise we'd need to
1135 * worry about multiple result tupdescs and things like that.
1137 if (length(parsetree_list) > 1)
1139 (errcode(ERRCODE_SYNTAX_ERROR),
1140 errmsg("cannot insert multiple commands into a prepared statement")));
1142 if (parsetree_list != NIL)
1144 Node *parsetree = (Node *) lfirst(parsetree_list);
1148 * Get the command name for possible use in status display.
1150 commandTag = CreateCommandTag(parsetree);
1153 * If we are in an aborted transaction, reject all commands except
1154 * COMMIT/ROLLBACK. It is important that this test occur before
1155 * we try to do parse analysis, rewrite, or planning, since all
1156 * those phases try to do database accesses, which may fail in
1157 * abort state. (It might be safe to allow some additional utility
1158 * commands in this state, but not many...)
1160 if (IsAbortedTransactionBlockState())
1162 bool allowit = false;
1164 if (IsA(parsetree, TransactionStmt))
1166 TransactionStmt *stmt = (TransactionStmt *) parsetree;
1168 if (stmt->kind == TRANS_STMT_COMMIT ||
1169 stmt->kind == TRANS_STMT_ROLLBACK)
1175 (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
1176 errmsg("current transaction is aborted, "
1177 "commands ignored until end of transaction block")));
1181 * OK to analyze, rewrite, and plan this query. Note that the
1182 * originally specified parameter set is not required to be
1183 * complete, so we have to use parse_analyze_varparams().
1185 if (log_parser_stats)
1188 querytree_list = parse_analyze_varparams(parsetree,
1193 * Check all parameter types got determined, and convert array
1194 * representation to a list for storage.
1197 for (i = 0; i < numParams; i++)
1199 Oid ptype = paramTypes[i];
1201 if (ptype == InvalidOid || ptype == UNKNOWNOID)
1203 (errcode(ERRCODE_INDETERMINATE_DATATYPE),
1204 errmsg("could not determine data type of parameter $%d",
1206 param_list = lappendo(param_list, ptype);
1209 if (log_parser_stats)
1210 ShowUsage("PARSE ANALYSIS STATISTICS");
1212 querytree_list = pg_rewrite_queries(querytree_list);
1214 plantree_list = pg_plan_queries(querytree_list, true);
1218 /* Empty input string. This is legal. */
1220 querytree_list = NIL;
1221 plantree_list = NIL;
1225 /* If we got a cancel signal in analysis or planning, quit */
1226 CHECK_FOR_INTERRUPTS();
1229 * Store the query as a prepared statement. See above comments.
1233 StorePreparedStatement(stmt_name,
1242 PreparedStatement *pstmt;
1244 pstmt = (PreparedStatement *) palloc0(sizeof(PreparedStatement));
1245 /* query_string needs to be copied into unnamed_stmt_context */
1246 pstmt->query_string = pstrdup(query_string);
1247 /* the rest is there already */
1248 pstmt->commandTag = commandTag;
1249 pstmt->query_list = querytree_list;
1250 pstmt->plan_list = plantree_list;
1251 pstmt->argtype_list = param_list;
1252 pstmt->context = unnamed_stmt_context;
1253 /* Now the unnamed statement is complete and valid */
1254 unnamed_stmt_pstmt = pstmt;
1257 MemoryContextSwitchTo(oldcontext);
1259 QueryContext = NULL;
1262 * We do NOT close the open transaction command here; that only
1263 * happens when the client sends Sync. Instead, do
1264 * CommandCounterIncrement just in case something happened during
1267 CommandCounterIncrement();
1270 * Send ParseComplete.
1272 if (whereToSendOutput == Remote)
1273 pq_putemptymessage('1');
1275 if (save_log_statement_stats)
1276 ShowUsage("PARSE MESSAGE STATISTICS");
1278 debug_query_string = NULL;
1284 * Process a "Bind" message to create a portal from a prepared statement
1287 exec_bind_message(StringInfo input_message)
1289 const char *portal_name;
1290 const char *stmt_name;
1292 int16 *pformats = NULL;
1295 int16 *rformats = NULL;
1297 PreparedStatement *pstmt;
1299 ParamListInfo params;
1301 pgstat_report_activity("<BIND>");
1303 set_ps_display("BIND");
1306 * Start up a transaction command so we can call functions etc. (Note
1307 * that this will normally change current memory context.) Nothing
1308 * happens if we are already in one.
1310 start_xact_command();
1312 /* Switch back to message context */
1313 MemoryContextSwitchTo(MessageContext);
1315 /* Get the fixed part of the message */
1316 portal_name = pq_getmsgstring(input_message);
1317 stmt_name = pq_getmsgstring(input_message);
1319 /* Get the parameter format codes */
1320 numPFormats = pq_getmsgint(input_message, 2);
1321 if (numPFormats > 0)
1323 pformats = (int16 *) palloc(numPFormats * sizeof(int16));
1324 for (i = 0; i < numPFormats; i++)
1325 pformats[i] = pq_getmsgint(input_message, 2);
1328 /* Get the parameter value count */
1329 numParams = pq_getmsgint(input_message, 2);
1331 if (numPFormats > 1 && numPFormats != numParams)
1333 (errcode(ERRCODE_PROTOCOL_VIOLATION),
1334 errmsg("bind message has %d parameter formats but %d parameters",
1335 numPFormats, numParams)));
1337 /* Find prepared statement */
1338 if (stmt_name[0] != '\0')
1339 pstmt = FetchPreparedStatement(stmt_name, true);
1342 /* special-case the unnamed statement */
1343 pstmt = unnamed_stmt_pstmt;
1346 (errcode(ERRCODE_UNDEFINED_PSTATEMENT),
1347 errmsg("unnamed prepared statement does not exist")));
1350 if (numParams != length(pstmt->argtype_list))
1352 (errcode(ERRCODE_PROTOCOL_VIOLATION),
1353 errmsg("bind message supplies %d parameters, but prepared statement \"%s\" requires %d",
1354 numParams, stmt_name, length(pstmt->argtype_list))));
1357 * Create the portal. Allow silent replacement of an existing portal
1358 * only if the unnamed portal is specified.
1360 if (portal_name[0] == '\0')
1361 portal = CreatePortal(portal_name, true, true);
1363 portal = CreatePortal(portal_name, false, false);
1365 PortalDefineQuery(portal,
1366 pstmt->query_string,
1373 * Fetch parameters, if any, and store in the portal's memory context.
1375 * In an aborted transaction, we can't risk calling user-defined
1376 * functions, but we can't fail to Bind either, so bind all parameters
1381 bool isaborted = IsAbortedTransactionBlockState();
1383 MemoryContext oldContext;
1385 oldContext = MemoryContextSwitchTo(PortalGetHeapMemory(portal));
1387 params = (ParamListInfo)
1388 palloc0((numParams + 1) * sizeof(ParamListInfoData));
1391 foreach(l, pstmt->argtype_list)
1393 Oid ptype = lfirsto(l);
1397 plength = pq_getmsgint(input_message, 4);
1398 isNull = (plength == -1);
1402 const char *pvalue = pq_getmsgbytes(input_message, plength);
1406 /* We don't bother to check the format in this case */
1412 StringInfoData pbuf;
1415 if (numPFormats > 1)
1416 pformat = pformats[i];
1417 else if (numPFormats > 0)
1418 pformat = pformats[0];
1420 pformat = 0; /* default = text */
1423 * Rather than copying data around, we just set up a
1424 * phony StringInfo pointing to the correct portion of
1425 * the message buffer. We assume we can scribble on
1426 * the message buffer so as to maintain the convention
1427 * that StringInfos have a trailing null. This is
1428 * grotty but is a big win when dealing with very
1429 * large parameter strings.
1431 pbuf.data = (char *) pvalue;
1432 pbuf.maxlen = plength + 1;
1436 csave = pbuf.data[plength];
1437 pbuf.data[plength] = '\0';
1445 getTypeInputInfo(ptype, &typInput, &typElem);
1448 * We have to do encoding conversion before
1449 * calling the typinput routine.
1452 pg_client_to_server((unsigned char *) pbuf.data,
1455 OidFunctionCall3(typInput,
1456 CStringGetDatum(pstring),
1457 ObjectIdGetDatum(typElem),
1459 /* Free result of encoding conversion, if any */
1460 if (pstring != pbuf.data)
1463 else if (pformat == 1)
1469 * Call the parameter type's binary input
1472 getTypeBinaryInputInfo(ptype, &typReceive, &typElem);
1475 OidFunctionCall2(typReceive,
1476 PointerGetDatum(&pbuf),
1477 ObjectIdGetDatum(typElem));
1479 /* Trouble if it didn't eat the whole buffer */
1480 if (pbuf.cursor != pbuf.len)
1482 (errcode(ERRCODE_INVALID_BINARY_REPRESENTATION),
1483 errmsg("incorrect binary data format in bind parameter %d",
1489 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1490 errmsg("unsupported format code: %d",
1494 /* Restore message buffer contents */
1495 pbuf.data[plength] = csave;
1499 params[i].kind = PARAM_NUM;
1500 params[i].id = i + 1;
1501 params[i].isnull = isNull;
1506 params[i].kind = PARAM_INVALID;
1508 MemoryContextSwitchTo(oldContext);
1513 /* Get the result format codes */
1514 numRFormats = pq_getmsgint(input_message, 2);
1515 if (numRFormats > 0)
1517 rformats = (int16 *) palloc(numRFormats * sizeof(int16));
1518 for (i = 0; i < numRFormats; i++)
1519 rformats[i] = pq_getmsgint(input_message, 2);
1522 pq_getmsgend(input_message);
1525 * Start portal execution.
1527 PortalStart(portal, params);
1530 * Apply the result format requests to the portal.
1532 PortalSetResultFormat(portal, numRFormats, rformats);
1535 * Send BindComplete.
1537 if (whereToSendOutput == Remote)
1538 pq_putemptymessage('2');
1542 * exec_execute_message
1544 * Process an "Execute" message for a portal
1547 exec_execute_message(const char *portal_name, long max_rows)
1550 DestReceiver *receiver;
1552 bool is_trans_stmt = false;
1553 bool is_trans_exit = false;
1555 char completionTag[COMPLETION_TAG_BUFSIZE];
1557 /* Adjust destination to tell printtup.c what to do */
1558 dest = whereToSendOutput;
1560 dest = RemoteExecute;
1562 portal = GetPortalByName(portal_name);
1563 if (!PortalIsValid(portal))
1565 (errcode(ERRCODE_UNDEFINED_CURSOR),
1566 errmsg("portal \"%s\" does not exist", portal_name)));
1569 * If the original query was a null string, just return
1570 * EmptyQueryResponse.
1572 if (portal->commandTag == NULL)
1574 Assert(portal->parseTrees == NIL);
1579 if (portal->sourceText)
1581 debug_query_string = portal->sourceText;
1582 pgstat_report_activity(portal->sourceText);
1586 debug_query_string = "execute message";
1587 pgstat_report_activity("<EXECUTE>");
1590 set_ps_display(portal->commandTag);
1592 BeginCommand(portal->commandTag, dest);
1594 /* Check for transaction-control commands */
1595 if (length(portal->parseTrees) == 1)
1597 Query *query = (Query *) lfirst(portal->parseTrees);
1599 if (query->commandType == CMD_UTILITY &&
1600 query->utilityStmt != NULL &&
1601 IsA(query->utilityStmt, TransactionStmt))
1603 TransactionStmt *stmt = (TransactionStmt *) query->utilityStmt;
1605 is_trans_stmt = true;
1606 if (stmt->kind == TRANS_STMT_COMMIT ||
1607 stmt->kind == TRANS_STMT_ROLLBACK)
1608 is_trans_exit = true;
1613 * Create dest receiver in MessageContext (we don't want it in
1614 * transaction context, because that may get deleted if portal
1617 receiver = CreateDestReceiver(dest, portal);
1620 * Ensure we are in a transaction command (this should normally be the
1621 * case already due to prior BIND).
1623 start_xact_command();
1626 * If we are in aborted transaction state, the only portals we can
1627 * actually run are those containing COMMIT or ROLLBACK commands.
1629 if (IsAbortedTransactionBlockState())
1633 (errcode(ERRCODE_IN_FAILED_SQL_TRANSACTION),
1634 errmsg("current transaction is aborted, "
1635 "commands ignored until end of transaction block")));
1638 /* Check for cancel signal before we start execution */
1639 CHECK_FOR_INTERRUPTS();
1642 * Okay to run the portal.
1645 max_rows = FETCH_ALL;
1647 completed = PortalRun(portal,
1653 (*receiver->rDestroy) (receiver);
1660 * If this was a transaction control statement, commit it. We
1661 * will start a new xact command for the next command (if
1664 finish_xact_command();
1669 * We need a CommandCounterIncrement after every query, except
1670 * those that start or end a transaction block.
1672 CommandCounterIncrement();
1675 /* Send appropriate CommandComplete to client */
1676 EndCommand(completionTag, dest);
1680 /* Portal run not complete, so send PortalSuspended */
1681 if (whereToSendOutput == Remote)
1682 pq_putemptymessage('s');
1685 debug_query_string = NULL;
1689 * exec_describe_statement_message
1691 * Process a "Describe" message for a prepared statement
1694 exec_describe_statement_message(const char *stmt_name)
1696 PreparedStatement *pstmt;
1701 /* Find prepared statement */
1702 if (stmt_name[0] != '\0')
1703 pstmt = FetchPreparedStatement(stmt_name, true);
1706 /* special-case the unnamed statement */
1707 pstmt = unnamed_stmt_pstmt;
1710 (errcode(ERRCODE_UNDEFINED_PSTATEMENT),
1711 errmsg("unnamed prepared statement does not exist")));
1714 if (whereToSendOutput != Remote)
1715 return; /* can't actually do anything... */
1718 * First describe the parameters...
1720 pq_beginmessage(&buf, 't'); /* parameter description message type */
1721 pq_sendint(&buf, length(pstmt->argtype_list), 2);
1723 foreach(l, pstmt->argtype_list)
1725 Oid ptype = lfirsto(l);
1727 pq_sendint(&buf, (int) ptype, 4);
1729 pq_endmessage(&buf);
1732 * Next send RowDescription or NoData to describe the result...
1734 tupdesc = FetchPreparedStatementResultDesc(pstmt);
1739 if (ChoosePortalStrategy(pstmt->query_list) == PORTAL_ONE_SELECT)
1740 targetlist = ((Query *) lfirst(pstmt->query_list))->targetList;
1743 SendRowDescriptionMessage(tupdesc, targetlist, NULL);
1746 pq_putemptymessage('n'); /* NoData */
1751 * exec_describe_portal_message
1753 * Process a "Describe" message for a portal
1756 exec_describe_portal_message(const char *portal_name)
1760 portal = GetPortalByName(portal_name);
1761 if (!PortalIsValid(portal))
1763 (errcode(ERRCODE_UNDEFINED_CURSOR),
1764 errmsg("portal \"%s\" does not exist", portal_name)));
1766 if (whereToSendOutput != Remote)
1767 return; /* can't actually do anything... */
1769 if (portal->tupDesc)
1773 if (portal->strategy == PORTAL_ONE_SELECT)
1774 targetlist = ((Query *) lfirst(portal->parseTrees))->targetList;
1777 SendRowDescriptionMessage(portal->tupDesc, targetlist,
1781 pq_putemptymessage('n'); /* NoData */
1786 * Convenience routines for starting/committing a single command.
1789 start_xact_command(void)
1794 (errmsg_internal("StartTransactionCommand")));
1795 StartTransactionCommand();
1797 /* Set statement timeout running, if any */
1798 if (StatementTimeout > 0)
1799 enable_sig_alarm(StatementTimeout, true);
1801 xact_started = true;
1806 finish_xact_command(void)
1810 /* Invoke IMMEDIATE constraint triggers */
1811 DeferredTriggerEndQuery();
1813 /* Cancel any active statement timeout before committing */
1814 disable_sig_alarm(true);
1816 /* Now commit the command */
1818 (errmsg_internal("CommitTransactionCommand")));
1820 CommitTransactionCommand();
1822 #ifdef MEMORY_CONTEXT_CHECKING
1823 /* Check all memory contexts that weren't freed during commit */
1824 /* (those that were, were checked before being deleted) */
1825 MemoryContextCheck(TopMemoryContext);
1828 #ifdef SHOW_MEMORY_STATS
1829 /* Print mem stats after each commit for leak tracking */
1831 MemoryContextStats(TopMemoryContext);
1834 xact_started = false;
1839 /* --------------------------------
1840 * signal handler routines used in PostgresMain()
1841 * --------------------------------
1845 * quickdie() occurs when signalled SIGQUIT by the postmaster.
1847 * Some backend has bought the farm,
1848 * so we need to stop what we're doing and exit.
1851 quickdie(SIGNAL_ARGS)
1853 PG_SETMASK(&BlockSig);
1856 * Ideally this should be ereport(FATAL), but then we'd not get
1857 * control back (perhaps could fix by doing local sigsetjmp?)
1860 (errcode(ERRCODE_CRASH_SHUTDOWN),
1861 errmsg("terminating connection because of crash of another server process"),
1862 errdetail("The postmaster has commanded this server process to roll back"
1863 " the current transaction and exit, because another"
1864 " server process exited abnormally and possibly corrupted"
1866 errhint("In a moment you should be able to reconnect to the"
1867 " database and repeat your command.")));
1870 * DO NOT proc_exit() -- we're here because shared memory may be
1871 * corrupted, so we don't want to try to clean up our transaction.
1872 * Just nail the windows shut and get out of town.
1874 * Note we do exit(1) not exit(0). This is to force the postmaster into
1875 * a system reset cycle if some idiot DBA sends a manual SIGQUIT to a
1876 * random backend. This is necessary precisely because we don't clean
1877 * up our shared memory state.
1883 * Shutdown signal from postmaster: abort transaction and exit
1884 * at soonest convenient time
1889 int save_errno = errno;
1891 /* Don't joggle the elbow of proc_exit */
1892 if (!proc_exit_inprogress)
1894 InterruptPending = true;
1895 ProcDiePending = true;
1898 * If it's safe to interrupt, and we're waiting for input or a
1899 * lock, service the interrupt immediately
1901 if (ImmediateInterruptOK && InterruptHoldoffCount == 0 &&
1902 CritSectionCount == 0)
1904 /* bump holdoff count to make ProcessInterrupts() a no-op */
1905 /* until we are done getting ready for it */
1906 InterruptHoldoffCount++;
1907 DisableNotifyInterrupt();
1908 /* Make sure CheckDeadLock won't run while shutting down... */
1910 InterruptHoldoffCount--;
1911 ProcessInterrupts();
1919 * Timeout or shutdown signal from postmaster during client authentication.
1922 * XXX: possible future improvement: try to send a message indicating
1923 * why we are disconnecting. Problem is to be sure we don't block while
1924 * doing so, nor mess up the authentication message exchange.
1927 authdie(SIGNAL_ARGS)
1933 * Query-cancel signal from postmaster: abort current transaction
1934 * at soonest convenient time
1937 StatementCancelHandler(SIGNAL_ARGS)
1939 int save_errno = errno;
1942 * Don't joggle the elbow of proc_exit, nor an already-in-progress
1945 if (!proc_exit_inprogress && !InError)
1947 InterruptPending = true;
1948 QueryCancelPending = true;
1951 * If it's safe to interrupt, and we're waiting for a lock,
1952 * service the interrupt immediately. No point in interrupting if
1953 * we're waiting for input, however.
1955 if (ImmediateInterruptOK && InterruptHoldoffCount == 0 &&
1956 CritSectionCount == 0)
1958 /* bump holdoff count to make ProcessInterrupts() a no-op */
1959 /* until we are done getting ready for it */
1960 InterruptHoldoffCount++;
1961 if (LockWaitCancel())
1963 DisableNotifyInterrupt();
1964 InterruptHoldoffCount--;
1965 ProcessInterrupts();
1968 InterruptHoldoffCount--;
1975 /* signal handler for floating point exception */
1977 FloatExceptionHandler(SIGNAL_ARGS)
1980 (errcode(ERRCODE_FLOATING_POINT_EXCEPTION),
1981 errmsg("floating-point exception"),
1982 errdetail("An invalid floating-point operation was signaled. "
1983 "This probably means an out-of-range result or an "
1984 "invalid operation, such as division by zero.")));
1987 /* SIGHUP: set flag to re-read config file at next convenient time */
1989 SigHupHandler(SIGNAL_ARGS)
1996 * ProcessInterrupts: out-of-line portion of CHECK_FOR_INTERRUPTS() macro
1998 * If an interrupt condition is pending, and it's safe to service it,
1999 * then clear the flag and accept the interrupt. Called only when
2000 * InterruptPending is true.
2003 ProcessInterrupts(void)
2005 /* OK to accept interrupt now? */
2006 if (InterruptHoldoffCount != 0 || CritSectionCount != 0)
2008 InterruptPending = false;
2011 ProcDiePending = false;
2012 QueryCancelPending = false; /* ProcDie trumps QueryCancel */
2013 ImmediateInterruptOK = false; /* not idle anymore */
2014 DisableNotifyInterrupt();
2016 (errcode(ERRCODE_ADMIN_SHUTDOWN),
2017 errmsg("terminating connection due to administrator command")));
2019 if (QueryCancelPending)
2021 QueryCancelPending = false;
2022 ImmediateInterruptOK = false; /* not idle anymore */
2023 DisableNotifyInterrupt();
2025 (errcode(ERRCODE_QUERY_CANCELED),
2026 errmsg("canceling query due to user request")));
2028 /* If we get here, do nothing (probably, QueryCancelPending was reset) */
2033 * check_stack_depth: check for excessively deep recursion
2035 * This should be called someplace in any recursive routine that might possibly
2036 * recurse deep enough to overflow the stack. Most Unixen treat stack
2037 * overflow as an unrecoverable SIGSEGV, so we want to error out ourselves
2038 * before hitting the hardware limit. Unfortunately we have no direct way
2039 * to detect the hardware limit, so we have to rely on the admin to set a
2040 * GUC variable for it ...
2043 check_stack_depth(void)
2049 * Compute distance from PostgresMain's local variables to my own
2051 * Note: in theory stack_depth should be ptrdiff_t or some such, but
2052 * since the whole point of this code is to bound the value to something
2053 * much less than integer-sized, int should work fine.
2055 stack_depth = (int) (stack_base_ptr - &stack_top_loc);
2057 * Take abs value, since stacks grow up on some machines, down on others
2059 if (stack_depth < 0)
2060 stack_depth = -stack_depth;
2064 * The test on stack_base_ptr prevents us from erroring out if called
2065 * during process setup or in a non-backend process. Logically it should
2066 * be done first, but putting it here avoids wasting cycles during normal
2069 if (stack_depth > max_stack_depth_bytes &&
2070 stack_base_ptr != NULL)
2073 (errcode(ERRCODE_STATEMENT_TOO_COMPLEX),
2074 errmsg("stack depth limit exceeded"),
2075 errhint("Increase the configuration parameter \"max_stack_depth\".")));
2079 /* GUC assign hook to update max_stack_depth_bytes from max_stack_depth */
2081 assign_max_stack_depth(int newval, bool doit, GucSource source)
2083 /* Range check was already handled by guc.c */
2085 max_stack_depth_bytes = newval * 1024;
2091 usage(char *progname)
2093 printf(gettext("%s is the PostgreSQL stand-alone backend. It is not\nintended to be used by normal users.\n\n"), progname);
2095 printf(gettext("Usage:\n %s [OPTION]... [DBNAME]\n\n"), progname);
2096 printf(gettext("Options:\n"));
2097 #ifdef USE_ASSERT_CHECKING
2098 printf(gettext(" -A 1|0 enable/disable run-time assert checking\n"));
2100 printf(gettext(" -B NBUFFERS number of shared buffers\n"));
2101 printf(gettext(" -c NAME=VALUE set run-time parameter\n"));
2102 printf(gettext(" -d 0-5 debugging level (0 is off)\n"));
2103 printf(gettext(" -D DATADIR database directory\n"));
2104 printf(gettext(" -e use European date input format (DMY)\n"));
2105 printf(gettext(" -E echo query before execution\n"));
2106 printf(gettext(" -F turn fsync off\n"));
2107 printf(gettext(" -N do not use newline as interactive query delimiter\n"));
2108 printf(gettext(" -o FILENAME send stdout and stderr to given file\n"));
2109 printf(gettext(" -P disable system indexes\n"));
2110 printf(gettext(" -s show statistics after each query\n"));
2111 printf(gettext(" -S WORK-MEM set amount of memory for sorts (in kbytes)\n"));
2112 printf(gettext(" --describe-config describe configuration parameters, then exit\n"));
2113 printf(gettext(" --help show this help, then exit\n"));
2114 printf(gettext(" --version output version information, then exit\n"));
2115 printf(gettext("\nDeveloper options:\n"));
2116 printf(gettext(" -f s|i|n|m|h forbid use of some plan types\n"));
2117 printf(gettext(" -i do not execute queries\n"));
2118 printf(gettext(" -O allow system table structure changes\n"));
2119 printf(gettext(" -t pa|pl|ex show timings after each query\n"));
2120 printf(gettext(" -W NUM wait NUM seconds to allow attach from a debugger\n"));
2121 printf(gettext("\nReport bugs to <pgsql-bugs@postgresql.org>.\n"));
2126 /* ----------------------------------------------------------------
2128 * postgres main loop -- all backends, interactive or otherwise start here
2130 * argc/argv are the command line arguments to be used. (When being forked
2131 * by the postmaster, these are not the original argv array of the process.)
2132 * username is the (possibly authenticated) PostgreSQL user name to be used
2134 * ----------------------------------------------------------------
2137 PostgresMain(int argc, char *argv[], const char *username)
2140 const char *dbname = NULL;
2141 char *potential_DataDir = NULL;
2147 GucSource gucsource;
2151 StringInfoData input_message;
2152 volatile bool send_rfq = true;
2155 * Catch standard options before doing much else. This even works on
2156 * systems without getopt_long.
2158 if (!IsUnderPostmaster && argc > 1)
2160 if (strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-?") == 0)
2165 if (strcmp(argv[1], "--version") == 0 || strcmp(argv[1], "-V") == 0)
2167 puts("postgres (PostgreSQL) " PG_VERSION);
2173 * initialize globals (already done if under postmaster, but not if
2174 * standalone; cheap enough to do over)
2176 MyProcPid = getpid();
2179 * Fire up essential subsystems: error and memory management
2181 * If we are running under the postmaster, this is done already.
2183 if (!IsUnderPostmaster)
2184 MemoryContextInit();
2186 set_ps_display("startup");
2188 SetProcessingMode(InitProcessing);
2190 /* Set up reference point for stack depth checking */
2191 stack_base_ptr = &stack_base;
2194 * Set default values for command-line options.
2198 if (!IsUnderPostmaster)
2200 InitializeGUCOptions();
2201 potential_DataDir = getenv("PGDATA");
2205 * parse command line arguments
2207 * There are now two styles of command line layout for the backend:
2209 * For interactive use (not started from postmaster) the format is
2210 * postgres [switches] [databasename]
2211 * If the databasename is omitted it is taken to be the user name.
2213 * When started from the postmaster, the format is
2214 * postgres [secure switches] -p databasename [insecure switches]
2215 * Switches appearing after -p came from the client (via "options"
2216 * field of connection request). For security reasons we restrict
2217 * what these switches can do.
2221 /* all options are allowed until '-p' */
2223 ctx = debug_context = PGC_POSTMASTER;
2224 gucsource = PGC_S_ARGV; /* initial switches came from command line */
2226 while ((flag = getopt(argc, argv, "A:B:c:D:d:Eef:FiNOPo:p:S:st:v:W:x:-:")) != -1)
2230 #ifdef USE_ASSERT_CHECKING
2231 SetConfigOption("debug_assertions", optarg, ctx, gucsource);
2234 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2235 errmsg("assert checking is not compiled in")));
2242 * specify the size of buffer pool
2244 SetConfigOption("shared_buffers", optarg, ctx, gucsource);
2247 case 'D': /* PGDATA directory */
2249 potential_DataDir = optarg;
2252 case 'd': /* debug level */
2255 * Client option can't decrease debug level. We have
2256 * to do the test here because we group priv and
2257 * client set GUC calls below, after we know the final
2260 if (ctx != PGC_BACKEND || atoi(optarg) > debug_flag)
2262 debug_flag = atoi(optarg);
2263 debug_context = ctx; /* save context for use
2265 /* Set server debugging level. */
2266 if (debug_flag != 0)
2268 char *debugstr = palloc(strlen("debug") + strlen(optarg) + 1);
2270 sprintf(debugstr, "debug%s", optarg);
2271 SetConfigOption("log_min_messages", debugstr, ctx, gucsource);
2278 * -d0 allows user to prevent postmaster debug
2279 * from propagating to backend. It would be
2280 * nice to set it to the postgresql.conf value
2283 SetConfigOption("log_min_messages", "notice",
2292 * E - echo the query the user entered
2300 * Use European date input format (DMY)
2302 SetConfigOption("datestyle", "euro", ctx, gucsource);
2310 SetConfigOption("fsync", "false", ctx, gucsource);
2316 * f - forbid generation of certain plans
2321 case 's': /* seqscan */
2322 tmp = "enable_seqscan";
2324 case 'i': /* indexscan */
2325 tmp = "enable_indexscan";
2327 case 't': /* tidscan */
2328 tmp = "enable_tidscan";
2330 case 'n': /* nestloop */
2331 tmp = "enable_nestloop";
2333 case 'm': /* mergejoin */
2334 tmp = "enable_mergejoin";
2336 case 'h': /* hashjoin */
2337 tmp = "enable_hashjoin";
2343 SetConfigOption(tmp, "false", ctx, gucsource);
2349 * N - Don't use newline as a query delimiter
2357 * allow system table structure modifications
2359 if (secure) /* XXX safe to allow from client??? */
2360 allowSystemTableMods = true;
2366 * ignore system indexes
2368 * As of PG 7.4 this is safe to allow from the client,
2369 * since it only disables reading the system indexes,
2370 * not writing them. Worst case consequence is slowness.
2372 IgnoreSystemIndexes(true);
2378 * o - send output (stdout and stderr) to the given file
2381 StrNCpy(OutputFileName, optarg, MAXPGPATH);
2386 * p - special flag passed if backend was forked by a
2391 dbname = strdup(optarg);
2393 secure = false; /* subsequent switches are NOT
2396 gucsource = PGC_S_CLIENT;
2403 * S - amount of sort memory to use in 1k bytes
2405 SetConfigOption("work_mem", optarg, ctx, gucsource);
2411 * s - report usage statistics (timings) after each query
2413 SetConfigOption("log_statement_stats", "true", ctx, gucsource);
2418 * tell postgres to report usage statistics (timings) for
2421 * -tpa[rser] = print stats for parser time of each query
2422 * -tpl[anner] = print stats for planner time of each query
2423 * -te[xecutor] = print stats for executor time of each query
2424 * caution: -s can not be used together with -t.
2431 if (optarg[1] == 'a')
2432 tmp = "log_parser_stats";
2433 else if (optarg[1] == 'l')
2434 tmp = "log_planner_stats";
2439 tmp = "log_executor_stats";
2446 SetConfigOption(tmp, "true", ctx, gucsource);
2451 FrontendProtocol = (ProtocolVersion) atoi(optarg);
2457 * wait N seconds to allow attach from a debugger
2459 pg_usleep(atoi(optarg)*1000000L);
2463 #ifdef NOT_USED /* planner/xfunc.h */
2466 * control joey hellerstein's expensive function
2471 elog(WARNING, "only one -x flag is allowed");
2475 if (strcmp(optarg, "off") == 0)
2476 XfuncMode = XFUNC_OFF;
2477 else if (strcmp(optarg, "nor") == 0)
2478 XfuncMode = XFUNC_NOR;
2479 else if (strcmp(optarg, "nopull") == 0)
2480 XfuncMode = XFUNC_NOPULL;
2481 else if (strcmp(optarg, "nopm") == 0)
2482 XfuncMode = XFUNC_NOPM;
2483 else if (strcmp(optarg, "pullall") == 0)
2484 XfuncMode = XFUNC_PULLALL;
2485 else if (strcmp(optarg, "wait") == 0)
2486 XfuncMode = XFUNC_WAIT;
2489 elog(WARNING, "use -x {off,nor,nopull,nopm,pullall,wait}");
2501 ParseLongOption(optarg, &name, &value);
2506 (errcode(ERRCODE_SYNTAX_ERROR),
2507 errmsg("--%s requires a value",
2511 (errcode(ERRCODE_SYNTAX_ERROR),
2512 errmsg("-c %s requires a value",
2516 SetConfigOption(name, value, ctx, gucsource);
2530 * -d is not the same as setting log_min_messages because it enables
2531 * other output options.
2533 if (debug_flag >= 1)
2535 SetConfigOption("log_connections", "true", debug_context, gucsource);
2536 SetConfigOption("log_disconnections", "true", debug_context, gucsource);
2538 if (debug_flag >= 2)
2539 SetConfigOption("log_statement", "all", debug_context, gucsource);
2540 if (debug_flag >= 3)
2541 SetConfigOption("debug_print_parse", "true", debug_context, gucsource);
2542 if (debug_flag >= 4)
2543 SetConfigOption("debug_print_plan", "true", debug_context, gucsource);
2544 if (debug_flag >= 5)
2545 SetConfigOption("debug_print_rewritten", "true", debug_context, gucsource);
2548 * Process any additional GUC variable settings passed in startup
2551 if (MyProcPort != NULL)
2553 List *gucopts = MyProcPort->guc_options;
2560 name = lfirst(gucopts);
2561 gucopts = lnext(gucopts);
2562 value = lfirst(gucopts);
2563 gucopts = lnext(gucopts);
2564 SetConfigOption(name, value, PGC_BACKEND, PGC_S_CLIENT);
2568 * set up handler to log session end.
2570 if (IsUnderPostmaster && Log_disconnections)
2571 on_proc_exit(log_disconnections,0);
2575 * Post-processing for command line options.
2577 if (log_statement_stats &&
2578 (log_parser_stats || log_planner_stats || log_executor_stats))
2581 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
2582 errmsg("statement-level statistics are disabled because parser, planner, or executor statistics are on")));
2583 SetConfigOption("log_statement_stats", "false", ctx, gucsource);
2586 if (!IsUnderPostmaster || ExecBackend)
2588 if (!potential_DataDir)
2591 gettext("%s does not know where to find the database system data.\n"
2592 "You must specify the directory that contains the database system\n"
2593 "either by specifying the -D invocation option or by setting the\n"
2594 "PGDATA environment variable.\n"),
2598 SetDataDir(potential_DataDir);
2602 /* Acquire configuration parameters */
2603 if (IsUnderPostmaster)
2606 read_nondefault_variables();
2609 ProcessConfigFile(PGC_POSTMASTER);
2612 * Set up signal handlers and masks.
2614 * Note that postmaster blocked all signals before forking child process,
2615 * so there is no race condition whereby we might receive a signal
2616 * before we have set up the handler.
2618 * Also note: it's best not to use any signals that are SIG_IGNored in
2619 * the postmaster. If such a signal arrives before we are able to
2620 * change the handler to non-SIG_IGN, it'll get dropped. Instead,
2621 * make a dummy handler in the postmaster to reserve the signal. (Of
2622 * course, this isn't an issue for signals that are locally generated,
2623 * such as SIGALRM and SIGPIPE.)
2625 pqsignal(SIGHUP, SigHupHandler); /* set flag to read config file */
2626 pqsignal(SIGINT, StatementCancelHandler); /* cancel current query */
2627 pqsignal(SIGTERM, die); /* cancel current query and exit */
2628 pqsignal(SIGQUIT, quickdie); /* hard crash time */
2629 pqsignal(SIGALRM, handle_sig_alarm); /* timeout conditions */
2632 * Ignore failure to write to frontend. Note: if frontend closes
2633 * connection, we will notice it and exit cleanly when control next
2634 * returns to outer loop. This seems safer than forcing exit in the
2635 * midst of output during who-knows-what operation...
2637 pqsignal(SIGPIPE, SIG_IGN);
2638 pqsignal(SIGUSR1, SIG_IGN); /* this signal available for use */
2640 pqsignal(SIGUSR2, Async_NotifyHandler); /* flush also sinval cache */
2641 pqsignal(SIGFPE, FloatExceptionHandler);
2644 * Reset some signals that are accepted by postmaster but not by
2647 pqsignal(SIGCHLD, SIG_DFL); /* system() requires this on some
2652 /* We allow SIGQUIT (quickdie) at all times */
2653 #ifdef HAVE_SIGPROCMASK
2654 sigdelset(&BlockSig, SIGQUIT);
2656 BlockSig &= ~(sigmask(SIGQUIT));
2659 PG_SETMASK(&BlockSig); /* block everything except SIGQUIT */
2662 if (IsUnderPostmaster)
2664 /* noninteractive case: nothing should be left after switches */
2665 if (errs || argc != optind || dbname == NULL)
2668 (errcode(ERRCODE_SYNTAX_ERROR),
2669 errmsg("invalid command-line arguments for server process"),
2670 errhint("Try \"%s --help\" for more information.", argv[0])));
2679 /* interactive case: database name can be last arg on command line */
2680 if (errs || argc - optind > 1)
2683 (errcode(ERRCODE_SYNTAX_ERROR),
2684 errmsg("%s: invalid command-line arguments",
2686 errhint("Try \"%s --help\" for more information.", argv[0])));
2688 else if (argc - optind == 1)
2689 dbname = argv[optind];
2690 else if ((dbname = username) == NULL)
2693 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
2694 errmsg("%s: no database nor user name specified",
2699 * On some systems our dynloader code needs the executable's
2700 * pathname. (If under postmaster, this was done already.)
2702 if (FindExec(pg_pathname, argv[0], "postgres") < 0)
2704 (errmsg("%s: could not locate postgres executable",
2708 * Validate we have been given a reasonable-looking DataDir (if
2709 * under postmaster, assume postmaster did this already).
2711 ValidatePgVersion(DataDir);
2714 * Create lockfile for data directory.
2716 CreateDataDirLockFile(DataDir, false);
2722 * Start up xlog for standalone backend, and register to have it
2723 * closed down at exit.
2726 on_shmem_exit(ShutdownXLOG, 0);
2729 * Read any existing FSM cache file, and register to write one out
2733 on_shmem_exit(DumpFreeSpaceMap, 0);
2737 * General initialization.
2739 * NOTE: if you are tempted to add code in this vicinity, consider
2740 * putting it inside InitPostgres() instead. In particular, anything
2741 * that involves database access should be there, not here.
2744 (errmsg_internal("InitPostgres")));
2745 InitPostgres(dbname, username);
2747 SetProcessingMode(NormalProcessing);
2750 * Send this backend's cancellation info to the frontend.
2752 if (whereToSendOutput == Remote &&
2753 PG_PROTOCOL_MAJOR(FrontendProtocol) >= 2)
2757 pq_beginmessage(&buf, 'K');
2758 pq_sendint(&buf, (int32) MyProcPid, sizeof(int32));
2759 pq_sendint(&buf, (int32) MyCancelKey, sizeof(int32));
2760 pq_endmessage(&buf);
2761 /* Need not flush since ReadyForQuery will do it. */
2764 /* Welcome banner for standalone case */
2765 if (whereToSendOutput == Debug)
2766 printf("\nPostgreSQL stand-alone backend %s\n", PG_VERSION);
2769 * Create the memory context we will use in the main loop.
2771 * MessageContext is reset once per iteration of the main loop, ie, upon
2772 * completion of processing of each command message from the client.
2774 MessageContext = AllocSetContextCreate(TopMemoryContext,
2776 ALLOCSET_DEFAULT_MINSIZE,
2777 ALLOCSET_DEFAULT_INITSIZE,
2778 ALLOCSET_DEFAULT_MAXSIZE);
2781 * Tell the statistics collector that we're alive and
2782 * to which database we belong.
2788 * POSTGRES main processing loop begins here
2790 * If an exception is encountered, processing resumes here so we abort
2791 * the current transaction and start a new one.
2794 if (sigsetjmp(Warn_restart, 1) != 0)
2797 * NOTE: if you are tempted to add more code in this if-block,
2798 * consider the probability that it should be in
2799 * AbortTransaction() instead.
2801 * Make sure we're not interrupted while cleaning up. Also forget
2802 * any pending QueryCancel request, since we're aborting anyway.
2803 * Force InterruptHoldoffCount to a known state in case we
2804 * ereport'd from inside a holdoff section.
2806 ImmediateInterruptOK = false;
2807 QueryCancelPending = false;
2808 InterruptHoldoffCount = 1;
2809 CritSectionCount = 0; /* should be unnecessary, but... */
2810 disable_sig_alarm(true);
2811 QueryCancelPending = false; /* again in case timeout occurred */
2812 DisableNotifyInterrupt();
2813 debug_query_string = NULL;
2816 * Make sure we are in a valid memory context during recovery.
2818 * We use ErrorContext in hopes that it will have some free space
2819 * even if we're otherwise up against it...
2821 MemoryContextSwitchTo(ErrorContext);
2823 /* Do the recovery */
2825 (errmsg_internal("AbortCurrentTransaction")));
2826 AbortCurrentTransaction();
2829 * Now return to normal top-level context and clear ErrorContext
2832 MemoryContextSwitchTo(TopMemoryContext);
2833 MemoryContextResetAndDeleteChildren(ErrorContext);
2834 ActivePortal = NULL;
2835 PortalContext = NULL;
2836 QueryContext = NULL;
2839 * Clear flag to indicate that we got out of error recovery mode
2840 * successfully. (Flag was set in elog.c before longjmp().)
2843 xact_started = false;
2846 * Clear flag that causes accounting for cost based vacuum.
2848 VacuumCostActive = false;
2851 * If we were handling an extended-query-protocol message,
2852 * initiate skip till next Sync. This also causes us not to issue
2853 * ReadyForQuery (until we get Sync).
2855 if (doing_extended_query_message)
2856 ignore_till_sync = true;
2859 * Exit interrupt holdoff section we implicitly established above.
2861 RESUME_INTERRUPTS();
2864 Warn_restart_ready = true; /* we can now handle ereport(ERROR) */
2866 PG_SETMASK(&UnBlockSig);
2868 if (!ignore_till_sync)
2869 send_rfq = true; /* initially, or after error */
2872 * Non-error queries loop here.
2878 * At top of loop, reset extended-query-message flag, so that any
2879 * errors encountered in "idle" state don't provoke skip.
2881 doing_extended_query_message = false;
2884 * Release storage left over from prior query cycle, and create a
2885 * new query input buffer in the cleared MessageContext.
2887 MemoryContextSwitchTo(MessageContext);
2888 MemoryContextResetAndDeleteChildren(MessageContext);
2890 initStringInfo(&input_message);
2893 * (1) If we've reached idle state, tell the frontend we're ready
2896 * Note: this includes fflush()'ing the last of the prior output.
2898 * This is also a good time to send collected statistics to the
2899 * collector, and to update the PS stats display. We avoid doing
2900 * those every time through the message loop because it'd slow down
2901 * processing of batched messages.
2905 pgstat_report_tabstat();
2907 if (IsTransactionOrTransactionBlock())
2909 set_ps_display("idle in transaction");
2910 pgstat_report_activity("<IDLE> in transaction");
2914 set_ps_display("idle");
2915 pgstat_report_activity("<IDLE>");
2918 ReadyForQuery(whereToSendOutput);
2923 * (2) deal with pending asynchronous NOTIFY from other backends,
2924 * and enable async.c's signal handler to execute NOTIFY directly.
2925 * Then set up other stuff needed before blocking for input.
2927 QueryCancelPending = false; /* forget any earlier CANCEL
2930 EnableNotifyInterrupt();
2932 /* Allow "die" interrupt to be processed while waiting */
2933 ImmediateInterruptOK = true;
2934 /* and don't forget to detect one that already arrived */
2935 QueryCancelPending = false;
2936 CHECK_FOR_INTERRUPTS();
2939 * (3) read a command (loop blocks here)
2942 firstchar = ReadCommand(&input_message);
2947 * (4) disable async signal conditions again.
2949 ImmediateInterruptOK = false;
2950 QueryCancelPending = false; /* forget any CANCEL signal */
2952 DisableNotifyInterrupt();
2955 * (5) check for any other interesting events that happened while
2962 read_nondefault_variables();
2964 ProcessConfigFile(PGC_SIGHUP);
2969 * (6) process the command. But ignore it if we're skipping till
2972 if (ignore_till_sync && firstchar != EOF)
2977 case 'Q': /* simple query */
2979 const char *query_string;
2981 query_string = pq_getmsgstring(&input_message);
2982 pq_getmsgend(&input_message);
2984 exec_simple_query(query_string);
2990 case 'P': /* parse */
2992 const char *stmt_name;
2993 const char *query_string;
2995 Oid *paramTypes = NULL;
2997 stmt_name = pq_getmsgstring(&input_message);
2998 query_string = pq_getmsgstring(&input_message);
2999 numParams = pq_getmsgint(&input_message, 2);
3004 paramTypes = (Oid *) palloc(numParams * sizeof(Oid));
3005 for (i = 0; i < numParams; i++)
3006 paramTypes[i] = pq_getmsgint(&input_message, 4);
3008 pq_getmsgend(&input_message);
3010 exec_parse_message(query_string, stmt_name,
3011 paramTypes, numParams);
3015 case 'B': /* bind */
3018 * this message is complex enough that it seems best to
3019 * put the field extraction out-of-line
3021 exec_bind_message(&input_message);
3024 case 'E': /* execute */
3026 const char *portal_name;
3029 portal_name = pq_getmsgstring(&input_message);
3030 max_rows = pq_getmsgint(&input_message, 4);
3031 pq_getmsgend(&input_message);
3033 exec_execute_message(portal_name, max_rows);
3037 case 'F': /* fastpath function call */
3038 /* Tell the collector what we're doing */
3039 pgstat_report_activity("<FASTPATH> function call");
3041 /* start an xact for this function invocation */
3042 start_xact_command();
3044 /* switch back to message context */
3045 MemoryContextSwitchTo(MessageContext);
3047 if (HandleFunctionRequest(&input_message) == EOF)
3049 /* lost frontend connection during F message input */
3052 * Reset whereToSendOutput to prevent ereport from
3053 * attempting to send any more messages to client.
3055 if (whereToSendOutput == Remote)
3056 whereToSendOutput = None;
3061 /* commit the function-invocation transaction */
3062 finish_xact_command();
3067 case 'C': /* close */
3070 const char *close_target;
3072 close_type = pq_getmsgbyte(&input_message);
3073 close_target = pq_getmsgstring(&input_message);
3074 pq_getmsgend(&input_message);
3079 if (close_target[0] != '\0')
3080 DropPreparedStatement(close_target, false);
3083 /* special-case the unnamed statement */
3084 unnamed_stmt_pstmt = NULL;
3085 if (unnamed_stmt_context)
3087 DropDependentPortals(unnamed_stmt_context);
3088 MemoryContextDelete(unnamed_stmt_context);
3090 unnamed_stmt_context = NULL;
3097 portal = GetPortalByName(close_target);
3098 if (PortalIsValid(portal))
3099 PortalDrop(portal, false);
3104 (errcode(ERRCODE_PROTOCOL_VIOLATION),
3105 errmsg("invalid CLOSE message subtype %d",
3110 if (whereToSendOutput == Remote)
3111 pq_putemptymessage('3'); /* CloseComplete */
3115 case 'D': /* describe */
3118 const char *describe_target;
3120 describe_type = pq_getmsgbyte(&input_message);
3121 describe_target = pq_getmsgstring(&input_message);
3122 pq_getmsgend(&input_message);
3124 switch (describe_type)
3127 exec_describe_statement_message(describe_target);
3130 exec_describe_portal_message(describe_target);
3134 (errcode(ERRCODE_PROTOCOL_VIOLATION),
3135 errmsg("invalid DESCRIBE message subtype %d",
3142 case 'H': /* flush */
3143 pq_getmsgend(&input_message);
3144 if (whereToSendOutput == Remote)
3148 case 'S': /* sync */
3149 pq_getmsgend(&input_message);
3150 finish_xact_command();
3155 * 'X' means that the frontend is closing down the socket.
3156 * EOF means unexpected loss of frontend connection.
3157 * Either way, perform normal shutdown.
3163 * Reset whereToSendOutput to prevent ereport from
3164 * attempting to send any more messages to client.
3166 if (whereToSendOutput == Remote)
3167 whereToSendOutput = None;
3170 * NOTE: if you are tempted to add more code here, DON'T!
3171 * Whatever you had in mind to do should be set up as an
3172 * on_proc_exit or on_shmem_exit callback, instead.
3173 * Otherwise it will fail to be called during other
3174 * backend-shutdown scenarios.
3176 proc_exit(!in_fatal_exit ? 0 : proc_exit_inprogress ||
3177 !IsUnderPostmaster);
3179 case 'd': /* copy data */
3180 case 'c': /* copy done */
3181 case 'f': /* copy fail */
3184 * Accept but ignore these messages, per protocol spec; we
3185 * probably got here because a COPY failed, and the
3186 * frontend is still sending data.
3192 (errcode(ERRCODE_PROTOCOL_VIOLATION),
3193 errmsg("invalid frontend message type %d",
3196 } /* end of input-reading loop */
3198 /* can't get here because the above loop never exits */
3201 return 1; /* keep compiler quiet */
3204 #ifndef HAVE_GETRUSAGE
3205 #include "rusagestub.h"
3207 #include <sys/resource.h>
3208 #endif /* HAVE_GETRUSAGE */
3210 static struct rusage Save_r;
3211 static struct timeval Save_t;
3216 getrusage(RUSAGE_SELF, &Save_r);
3217 gettimeofday(&Save_t, NULL);
3219 /* ResetTupleCount(); */
3223 ShowUsage(const char *title)
3226 struct timeval user,
3228 struct timeval elapse_t;
3232 getrusage(RUSAGE_SELF, &r);
3233 gettimeofday(&elapse_t, NULL);
3234 memcpy((char *) &user, (char *) &r.ru_utime, sizeof(user));
3235 memcpy((char *) &sys, (char *) &r.ru_stime, sizeof(sys));
3236 if (elapse_t.tv_usec < Save_t.tv_usec)
3239 elapse_t.tv_usec += 1000000;
3241 if (r.ru_utime.tv_usec < Save_r.ru_utime.tv_usec)
3243 r.ru_utime.tv_sec--;
3244 r.ru_utime.tv_usec += 1000000;
3246 if (r.ru_stime.tv_usec < Save_r.ru_stime.tv_usec)
3248 r.ru_stime.tv_sec--;
3249 r.ru_stime.tv_usec += 1000000;
3253 * the only stats we don't show here are for memory usage -- i can't
3254 * figure out how to interpret the relevant fields in the rusage
3255 * struct, and they change names across o/s platforms, anyway. if you
3256 * can figure out what the entries mean, you can somehow extract
3257 * resident set size, shared text size, and unshared data and stack
3260 initStringInfo(&str);
3262 appendStringInfo(&str, "! system usage stats:\n");
3263 appendStringInfo(&str,
3264 "!\t%ld.%06ld elapsed %ld.%06ld user %ld.%06ld system sec\n",
3265 (long) (elapse_t.tv_sec - Save_t.tv_sec),
3266 (long) (elapse_t.tv_usec - Save_t.tv_usec),
3267 (long) (r.ru_utime.tv_sec - Save_r.ru_utime.tv_sec),
3268 (long) (r.ru_utime.tv_usec - Save_r.ru_utime.tv_usec),
3269 (long) (r.ru_stime.tv_sec - Save_r.ru_stime.tv_sec),
3270 (long) (r.ru_stime.tv_usec - Save_r.ru_stime.tv_usec));
3271 appendStringInfo(&str,
3272 "!\t[%ld.%06ld user %ld.%06ld sys total]\n",
3274 (long) user.tv_usec,
3276 (long) sys.tv_usec);
3277 /* BeOS has rusage but only has some fields, and not these... */
3278 #if defined(HAVE_GETRUSAGE)
3279 appendStringInfo(&str,
3280 "!\t%ld/%ld [%ld/%ld] filesystem blocks in/out\n",
3281 r.ru_inblock - Save_r.ru_inblock,
3282 /* they only drink coffee at dec */
3283 r.ru_oublock - Save_r.ru_oublock,
3284 r.ru_inblock, r.ru_oublock);
3285 appendStringInfo(&str,
3286 "!\t%ld/%ld [%ld/%ld] page faults/reclaims, %ld [%ld] swaps\n",
3287 r.ru_majflt - Save_r.ru_majflt,
3288 r.ru_minflt - Save_r.ru_minflt,
3289 r.ru_majflt, r.ru_minflt,
3290 r.ru_nswap - Save_r.ru_nswap,
3292 appendStringInfo(&str,
3293 "!\t%ld [%ld] signals rcvd, %ld/%ld [%ld/%ld] messages rcvd/sent\n",
3294 r.ru_nsignals - Save_r.ru_nsignals,
3296 r.ru_msgrcv - Save_r.ru_msgrcv,
3297 r.ru_msgsnd - Save_r.ru_msgsnd,
3298 r.ru_msgrcv, r.ru_msgsnd);
3299 appendStringInfo(&str,
3300 "!\t%ld/%ld [%ld/%ld] voluntary/involuntary context switches\n",
3301 r.ru_nvcsw - Save_r.ru_nvcsw,
3302 r.ru_nivcsw - Save_r.ru_nivcsw,
3303 r.ru_nvcsw, r.ru_nivcsw);
3304 #endif /* HAVE_GETRUSAGE */
3306 bufusage = ShowBufferUsage();
3307 appendStringInfo(&str, "! buffer usage stats:\n%s", bufusage);
3310 /* remove trailing newline */
3311 if (str.data[str.len - 1] == '\n')
3312 str.data[--str.len] = '\0';
3315 (errmsg_internal("%s", title),
3316 errdetail("%s", str.data)));
3322 * on_proc_exit handler to log end of session
3325 log_disconnections(int code, Datum arg)
3327 Port *port = MyProcPort;
3329 int hours, minutes, seconds;
3331 char session_time[20];
3332 char uname[6+NAMEDATALEN];
3333 char dbname[10+NAMEDATALEN];
3334 char remote_host[7 + NI_MAXHOST];
3335 char remote_port[7 + NI_MAXSERV];
3337 snprintf(uname, sizeof(uname)," user=%s",port->user_name);
3338 snprintf(dbname, sizeof(dbname)," database=%s",port->database_name);
3339 snprintf(remote_host,sizeof(remote_host)," host=%s",
3341 snprintf(remote_port,sizeof(remote_port)," port=%s",port->remote_port);
3344 gettimeofday(&end,NULL);
3346 if (end.tv_usec < port->session_start.tv_usec)
3349 end.tv_usec += 1000000;
3351 end.tv_sec -= port->session_start.tv_sec;
3352 end.tv_usec -= port->session_start.tv_usec;
3354 hours = end.tv_sec / 3600;
3356 minutes = end.tv_sec / 60;
3357 seconds = end.tv_sec % 60;
3359 /* if time has gone backwards for some reason say so, or print time */
3362 snprintf(session_time,sizeof(session_time),"negative!");
3364 /* for stricter accuracy here we could round - this is close enough */
3365 snprintf(session_time, sizeof(session_time),
3366 "%d:%02d:%02d.%02d",
3367 hours, minutes, seconds, (int) (end.tv_usec/10000));
3371 (errmsg("disconnection: session time: %s%s%s%s%s",
3372 session_time,uname,dbname,remote_host,remote_port)));